diff --git a/accessapproval/apiv1/access_approval_client.go b/accessapproval/apiv1/access_approval_client.go index 42d4a58d2898..40a9c00c9aed 100644 --- a/accessapproval/apiv1/access_approval_client.go +++ b/accessapproval/apiv1/access_approval_client.go @@ -17,21 +17,27 @@ package accessapproval import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" accessapprovalpb "cloud.google.com/go/accessapproval/apiv1/accessapprovalpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -106,6 +112,47 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + ListApprovalRequests: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetApprovalRequest: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ApproveApprovalRequest: []gax.CallOption{}, + DismissApprovalRequest: []gax.CallOption{}, + InvalidateApprovalRequest: []gax.CallOption{}, + GetAccessApprovalSettings: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UpdateAccessApprovalSettings: []gax.CallOption{}, + DeleteAccessApprovalSettings: []gax.CallOption{}, + GetAccessApprovalServiceAccount: []gax.CallOption{}, + } +} + // internalClient is an interface that defines the methods available from Access Approval API. type internalClient interface { Close() error @@ -377,6 +424,107 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new access approval rest client. +// +// This API allows a customer to manage accesses to cloud resources by +// Google personnel. It defines the following resource model: +// +// The API has a collection of +// ApprovalRequest +// resources, named approvalRequests/{approval_request} +// +// The API has top-level settings per Project/Folder/Organization, named +// accessApprovalSettings +// +// The service also periodically emails a list of recipients, defined at the +// Project/Folder/Organization level in the accessApprovalSettings, when there +// is a pending ApprovalRequest for them to act on. The ApprovalRequests can +// also optionally be published to a Pub/Sub topic owned by the customer +// (contact support if you would like to enable Pub/Sub notifications). +// +// ApprovalRequests can be approved or dismissed. Google personnel can only +// access the indicated resource or resources if the request is approved +// (subject to some exclusions: +// https://cloud.google.com/access-approval/docs/overview#exclusions (at https://cloud.google.com/access-approval/docs/overview#exclusions)). +// +// Note: Using Access Approval functionality will mean that Google may not be +// able to meet the SLAs for your chosen products, as any support response times +// may be dramatically increased. As such the SLAs do not apply to any service +// disruption to the extent impacted by Customer’s use of Access Approval. Do +// not enable Access Approval for projects where you may require high service +// availability and rapid response by Google Cloud Support. +// +// After a request is approved or dismissed, no further action may be taken on +// it. Requests with the requested_expiration in the past or with no activity +// for 14 days are considered dismissed. When an approval expires, the request +// is considered dismissed. +// +// If a request is not approved or dismissed, we call it pending. +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://accessapproval.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://accessapproval.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://accessapproval.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) ListApprovalRequests(ctx context.Context, req *accessapprovalpb.ListApprovalRequestsMessage, opts ...gax.CallOption) *ApprovalRequestIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -589,6 +737,603 @@ func (c *gRPCClient) GetAccessApprovalServiceAccount(ctx context.Context, req *a return resp, nil } +// ListApprovalRequests lists approval requests associated with a project, folder, or organization. +// Approval requests can be filtered by state (pending, active, dismissed). +// The order is reverse chronological. +func (c *restClient) ListApprovalRequests(ctx context.Context, req *accessapprovalpb.ListApprovalRequestsMessage, opts ...gax.CallOption) *ApprovalRequestIterator { + it := &ApprovalRequestIterator{} + req = proto.Clone(req).(*accessapprovalpb.ListApprovalRequestsMessage) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*accessapprovalpb.ApprovalRequest, string, error) { + resp := &accessapprovalpb.ListApprovalRequestsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/approvalRequests", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetApprovalRequests(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetApprovalRequest gets an approval request. Returns NOT_FOUND if the request does not exist. +func (c *restClient) GetApprovalRequest(ctx context.Context, req *accessapprovalpb.GetApprovalRequestMessage, opts ...gax.CallOption) (*accessapprovalpb.ApprovalRequest, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetApprovalRequest[0:len((*c.CallOptions).GetApprovalRequest):len((*c.CallOptions).GetApprovalRequest)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &accessapprovalpb.ApprovalRequest{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ApproveApprovalRequest approves a request and returns the updated ApprovalRequest. +// +// Returns NOT_FOUND if the request does not exist. Returns +// FAILED_PRECONDITION if the request exists but is not in a pending state. +func (c *restClient) ApproveApprovalRequest(ctx context.Context, req *accessapprovalpb.ApproveApprovalRequestMessage, opts ...gax.CallOption) (*accessapprovalpb.ApprovalRequest, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:approve", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).ApproveApprovalRequest[0:len((*c.CallOptions).ApproveApprovalRequest):len((*c.CallOptions).ApproveApprovalRequest)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &accessapprovalpb.ApprovalRequest{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DismissApprovalRequest dismisses a request. Returns the updated ApprovalRequest. +// +// NOTE: This does not deny access to the resource if another request has been +// made and approved. It is equivalent in effect to ignoring the request +// altogether. +// +// Returns NOT_FOUND if the request does not exist. +// +// Returns FAILED_PRECONDITION if the request exists but is not in a pending +// state. +func (c *restClient) DismissApprovalRequest(ctx context.Context, req *accessapprovalpb.DismissApprovalRequestMessage, opts ...gax.CallOption) (*accessapprovalpb.ApprovalRequest, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:dismiss", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).DismissApprovalRequest[0:len((*c.CallOptions).DismissApprovalRequest):len((*c.CallOptions).DismissApprovalRequest)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &accessapprovalpb.ApprovalRequest{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// InvalidateApprovalRequest invalidates an existing ApprovalRequest. Returns the updated +// ApprovalRequest. +// +// NOTE: This does not deny access to the resource if another request has been +// made and approved. It only invalidates a single approval. +// +// Returns FAILED_PRECONDITION if the request exists but is not in an approved +// state. +func (c *restClient) InvalidateApprovalRequest(ctx context.Context, req *accessapprovalpb.InvalidateApprovalRequestMessage, opts ...gax.CallOption) (*accessapprovalpb.ApprovalRequest, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:invalidate", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).InvalidateApprovalRequest[0:len((*c.CallOptions).InvalidateApprovalRequest):len((*c.CallOptions).InvalidateApprovalRequest)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &accessapprovalpb.ApprovalRequest{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetAccessApprovalSettings gets the settings associated with a project, folder, or organization. +func (c *restClient) GetAccessApprovalSettings(ctx context.Context, req *accessapprovalpb.GetAccessApprovalSettingsMessage, opts ...gax.CallOption) (*accessapprovalpb.AccessApprovalSettings, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetAccessApprovalSettings[0:len((*c.CallOptions).GetAccessApprovalSettings):len((*c.CallOptions).GetAccessApprovalSettings)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &accessapprovalpb.AccessApprovalSettings{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateAccessApprovalSettings updates the settings associated with a project, folder, or organization. +// Settings to update are determined by the value of field_mask. +func (c *restClient) UpdateAccessApprovalSettings(ctx context.Context, req *accessapprovalpb.UpdateAccessApprovalSettingsMessage, opts ...gax.CallOption) (*accessapprovalpb.AccessApprovalSettings, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetSettings() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetSettings().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "settings.name", url.QueryEscape(req.GetSettings().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateAccessApprovalSettings[0:len((*c.CallOptions).UpdateAccessApprovalSettings):len((*c.CallOptions).UpdateAccessApprovalSettings)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &accessapprovalpb.AccessApprovalSettings{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteAccessApprovalSettings deletes the settings associated with a project, folder, or organization. +// This will have the effect of disabling Access Approval for the project, +// folder, or organization, but only if all ancestors also have Access +// Approval disabled. If Access Approval is enabled at a higher level of the +// hierarchy, then Access Approval will still be enabled at this level as +// the settings are inherited. +func (c *restClient) DeleteAccessApprovalSettings(ctx context.Context, req *accessapprovalpb.DeleteAccessApprovalSettingsMessage, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetAccessApprovalServiceAccount retrieves the service account that is used by Access Approval to access KMS +// keys for signing approved approval requests. +func (c *restClient) GetAccessApprovalServiceAccount(ctx context.Context, req *accessapprovalpb.GetAccessApprovalServiceAccountMessage, opts ...gax.CallOption) (*accessapprovalpb.AccessApprovalServiceAccount, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetAccessApprovalServiceAccount[0:len((*c.CallOptions).GetAccessApprovalServiceAccount):len((*c.CallOptions).GetAccessApprovalServiceAccount)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &accessapprovalpb.AccessApprovalServiceAccount{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + // ApprovalRequestIterator manages a stream of *accessapprovalpb.ApprovalRequest. type ApprovalRequestIterator struct { items []*accessapprovalpb.ApprovalRequest diff --git a/accessapproval/apiv1/access_approval_client_example_test.go b/accessapproval/apiv1/access_approval_client_example_test.go index 1d7f8d6ff5fa..6ddd35429b96 100644 --- a/accessapproval/apiv1/access_approval_client_example_test.go +++ b/accessapproval/apiv1/access_approval_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := accessapproval.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_ListApprovalRequests() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/accessapproval/apiv1/accessapprovalpb/accessapproval.pb.go b/accessapproval/apiv1/accessapprovalpb/accessapproval.pb.go index b73f3b51e683..ebe38a6a6731 100644 --- a/accessapproval/apiv1/accessapprovalpb/accessapproval.pb.go +++ b/accessapproval/apiv1/accessapprovalpb/accessapproval.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/accessapproval/v1/accessapproval.proto package accessapprovalpb @@ -101,12 +101,12 @@ const ( // Customer made a request or raised an issue that required the principal to // access customer data. `detail` is of the form ("#####" is the issue ID): // - // - "Feedback Report: #####" - // - "Case Number: #####" - // - "Case ID: #####" - // - "E-PIN Reference: #####" - // - "Google-#####" - // - "T-#####" + // * "Feedback Report: #####" + // * "Case Number: #####" + // * "Case ID: #####" + // * "E-PIN Reference: #####" + // * "Google-#####" + // * "T-#####" AccessReason_CUSTOMER_INITIATED_SUPPORT AccessReason_Type = 1 // The principal accessed customer data in order to diagnose or resolve a // suspected issue in services. Often this access is used to confirm that @@ -184,14 +184,14 @@ type AccessLocations struct { // of a country code. // Possible Region Codes: // - // - ASI: Asia - // - EUR: Europe - // - OCE: Oceania - // - AFR: Africa - // - NAM: North America - // - SAM: South America - // - ANT: Antarctica - // - ANY: Any location + // * ASI: Asia + // * EUR: Europe + // * OCE: Oceania + // * AFR: Africa + // * NAM: North America + // * SAM: South America + // * ANT: Antarctica + // * ANY: Any location PrincipalOfficeCountry string `protobuf:"bytes,1,opt,name=principal_office_country,json=principalOfficeCountry,proto3" json:"principal_office_country,omitempty"` // Physical location of the principal at the time of the access. A // two-letter country code (ISO 3166-1 alpha-2), such as "US", "DE" or "GB" or @@ -199,14 +199,14 @@ type AccessLocations struct { // a region code instead of a country code. // Possible Region Codes: // - // - ASI: Asia - // - EUR: Europe - // - OCE: Oceania - // - AFR: Africa - // - NAM: North America - // - SAM: South America - // - ANT: Antarctica - // - ANY: Any location + // * ASI: Asia + // * EUR: Europe + // * OCE: Oceania + // * AFR: Africa + // * NAM: North America + // * SAM: South America + // * ANT: Antarctica + // * ANY: Any location PrincipalPhysicalLocationCountry string `protobuf:"bytes,2,opt,name=principal_physical_location_country,json=principalPhysicalLocationCountry,proto3" json:"principal_physical_location_country,omitempty"` } @@ -324,7 +324,6 @@ type SignatureInfo struct { // How this signature may be verified. // // Types that are assignable to VerificationInfo: - // // *SignatureInfo_GooglePublicKeyPem // *SignatureInfo_CustomerKmsKeyVersion VerificationInfo isSignatureInfo_VerificationInfo `protobuf_oneof:"verification_info"` @@ -636,7 +635,6 @@ type ApprovalRequest struct { // The current decision on the approval request. // // Types that are assignable to Decision: - // // *ApprovalRequest_Approve // *ApprovalRequest_Dismiss Decision isApprovalRequest_Decision `protobuf_oneof:"decision"` @@ -771,55 +769,55 @@ type EnrolledService struct { // The product for which Access Approval will be enrolled. Allowed values are // listed below (case-sensitive): // - // - all - // - GA - // - App Engine - // - BigQuery - // - Cloud Bigtable - // - Cloud Key Management Service - // - Compute Engine - // - Cloud Dataflow - // - Cloud Dataproc - // - Cloud DLP - // - Cloud EKM - // - Cloud HSM - // - Cloud Identity and Access Management - // - Cloud Logging - // - Cloud Pub/Sub - // - Cloud Spanner - // - Cloud SQL - // - Cloud Storage - // - Google Kubernetes Engine - // - Organization Policy Serivice - // - Persistent Disk - // - Resource Manager - // - Secret Manager - // - Speaker ID + // * all + // * GA + // * App Engine + // * BigQuery + // * Cloud Bigtable + // * Cloud Key Management Service + // * Compute Engine + // * Cloud Dataflow + // * Cloud Dataproc + // * Cloud DLP + // * Cloud EKM + // * Cloud HSM + // * Cloud Identity and Access Management + // * Cloud Logging + // * Cloud Pub/Sub + // * Cloud Spanner + // * Cloud SQL + // * Cloud Storage + // * Google Kubernetes Engine + // * Organization Policy Serivice + // * Persistent Disk + // * Resource Manager + // * Secret Manager + // * Speaker ID // // Note: These values are supported as input for legacy purposes, but will not // be returned from the API. // - // - all - // - ga-only - // - appengine.googleapis.com - // - bigquery.googleapis.com - // - bigtable.googleapis.com - // - container.googleapis.com - // - cloudkms.googleapis.com - // - cloudresourcemanager.googleapis.com - // - cloudsql.googleapis.com - // - compute.googleapis.com - // - dataflow.googleapis.com - // - dataproc.googleapis.com - // - dlp.googleapis.com - // - iam.googleapis.com - // - logging.googleapis.com - // - orgpolicy.googleapis.com - // - pubsub.googleapis.com - // - spanner.googleapis.com - // - secretmanager.googleapis.com - // - speakerid.googleapis.com - // - storage.googleapis.com + // * all + // * ga-only + // * appengine.googleapis.com + // * bigquery.googleapis.com + // * bigtable.googleapis.com + // * container.googleapis.com + // * cloudkms.googleapis.com + // * cloudresourcemanager.googleapis.com + // * cloudsql.googleapis.com + // * compute.googleapis.com + // * dataflow.googleapis.com + // * dataproc.googleapis.com + // * dlp.googleapis.com + // * iam.googleapis.com + // * logging.googleapis.com + // * orgpolicy.googleapis.com + // * pubsub.googleapis.com + // * spanner.googleapis.com + // * secretmanager.googleapis.com + // * speakerid.googleapis.com + // * storage.googleapis.com // // Calls to UpdateAccessApprovalSettings using 'all' or any of the // XXX.googleapis.com will be translated to the associated product name @@ -889,9 +887,9 @@ type AccessApprovalSettings struct { // The resource name of the settings. Format is one of: // - // - "projects/{project}/accessApprovalSettings" - // - "folders/{folder}/accessApprovalSettings" - // - "organizations/{organization}/accessApprovalSettings" + // * "projects/{project}/accessApprovalSettings" + // * "folders/{folder}/accessApprovalSettings" + // * "organizations/{organization}/accessApprovalSettings" Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // A list of email addresses to which notifications relating to approval // requests should be sent. Notifications relating to a resource will be sent @@ -1025,9 +1023,9 @@ type AccessApprovalServiceAccount struct { // The resource name of the Access Approval service account. Format is one of: // - // - "projects/{project}/serviceAccount" - // - "folders/{folder}/serviceAccount" - // - "organizations/{organization}/serviceAccount" + // * "projects/{project}/serviceAccount" + // * "folders/{folder}/serviceAccount" + // * "organizations/{organization}/serviceAccount" Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Email address of the service account. AccountEmail string `protobuf:"bytes,2,opt,name=account_email,json=accountEmail,proto3" json:"account_email,omitempty"` @@ -1091,15 +1089,15 @@ type ListApprovalRequestsMessage struct { // A filter on the type of approval requests to retrieve. Must be one of the // following values: // - // - [not set]: Requests that are pending or have active approvals. - // - ALL: All requests. - // - PENDING: Only pending requests. - // - ACTIVE: Only active (i.e. currently approved) requests. - // - DISMISSED: Only requests that have been dismissed, or requests that + // * [not set]: Requests that are pending or have active approvals. + // * ALL: All requests. + // * PENDING: Only pending requests. + // * ACTIVE: Only active (i.e. currently approved) requests. + // * DISMISSED: Only requests that have been dismissed, or requests that // are not approved and past expiration. - // - EXPIRED: Only requests that have been approved, and the approval has + // * EXPIRED: Only requests that have been approved, and the approval has // expired. - // - HISTORY: Active, dismissed and expired requests. + // * HISTORY: Active, dismissed and expired requests. Filter string `protobuf:"bytes,2,opt,name=filter,proto3" json:"filter,omitempty"` // Requested page size. PageSize int32 `protobuf:"varint,3,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"` diff --git a/accessapproval/apiv1/doc.go b/accessapproval/apiv1/doc.go index 6cb86572980c..0c8bdfd0fba1 100644 --- a/accessapproval/apiv1/doc.go +++ b/accessapproval/apiv1/doc.go @@ -86,6 +86,8 @@ package accessapproval // import "cloud.google.com/go/accessapproval/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -174,3 +176,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/accessapproval/apiv1/gapic_metadata.json b/accessapproval/apiv1/gapic_metadata.json index 3e70729770b7..84dded84377d 100644 --- a/accessapproval/apiv1/gapic_metadata.json +++ b/accessapproval/apiv1/gapic_metadata.json @@ -56,6 +56,56 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "ApproveApprovalRequest": { + "methods": [ + "ApproveApprovalRequest" + ] + }, + "DeleteAccessApprovalSettings": { + "methods": [ + "DeleteAccessApprovalSettings" + ] + }, + "DismissApprovalRequest": { + "methods": [ + "DismissApprovalRequest" + ] + }, + "GetAccessApprovalServiceAccount": { + "methods": [ + "GetAccessApprovalServiceAccount" + ] + }, + "GetAccessApprovalSettings": { + "methods": [ + "GetAccessApprovalSettings" + ] + }, + "GetApprovalRequest": { + "methods": [ + "GetApprovalRequest" + ] + }, + "InvalidateApprovalRequest": { + "methods": [ + "InvalidateApprovalRequest" + ] + }, + "ListApprovalRequests": { + "methods": [ + "ListApprovalRequests" + ] + }, + "UpdateAccessApprovalSettings": { + "methods": [ + "UpdateAccessApprovalSettings" + ] + } + } } } } diff --git a/accesscontextmanager/apiv1/access_context_manager_client.go b/accesscontextmanager/apiv1/access_context_manager_client.go index 5d7ecdeb7ff2..6b3cdfef823c 100644 --- a/accesscontextmanager/apiv1/access_context_manager_client.go +++ b/accesscontextmanager/apiv1/access_context_manager_client.go @@ -17,9 +17,12 @@ package accesscontextmanager import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,14 +30,17 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" iampb "google.golang.org/genproto/googleapis/iam/v1" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -115,6 +121,38 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + ListAccessPolicies: []gax.CallOption{}, + GetAccessPolicy: []gax.CallOption{}, + CreateAccessPolicy: []gax.CallOption{}, + UpdateAccessPolicy: []gax.CallOption{}, + DeleteAccessPolicy: []gax.CallOption{}, + ListAccessLevels: []gax.CallOption{}, + GetAccessLevel: []gax.CallOption{}, + CreateAccessLevel: []gax.CallOption{}, + UpdateAccessLevel: []gax.CallOption{}, + DeleteAccessLevel: []gax.CallOption{}, + ReplaceAccessLevels: []gax.CallOption{}, + ListServicePerimeters: []gax.CallOption{}, + GetServicePerimeter: []gax.CallOption{}, + CreateServicePerimeter: []gax.CallOption{}, + UpdateServicePerimeter: []gax.CallOption{}, + DeleteServicePerimeter: []gax.CallOption{}, + ReplaceServicePerimeters: []gax.CallOption{}, + CommitServicePerimeters: []gax.CallOption{}, + ListGcpUserAccessBindings: []gax.CallOption{}, + GetGcpUserAccessBinding: []gax.CallOption{}, + CreateGcpUserAccessBinding: []gax.CallOption{}, + UpdateGcpUserAccessBinding: []gax.CallOption{}, + DeleteGcpUserAccessBinding: []gax.CallOption{}, + SetIamPolicy: []gax.CallOption{}, + GetIamPolicy: []gax.CallOption{}, + TestIamPermissions: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + } +} + // internalClient is an interface that defines the methods available from Access Context Manager API. type internalClient interface { Close() error @@ -684,6 +722,99 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new access context manager rest client. +// +// API for setting [access levels] +// [google.identity.accesscontextmanager.v1.AccessLevel] and [service +// perimeters] [google.identity.accesscontextmanager.v1.ServicePerimeter] +// for Google Cloud projects. Each organization has one [access policy] +// [google.identity.accesscontextmanager.v1.AccessPolicy] that contains the +// [access levels] [google.identity.accesscontextmanager.v1.AccessLevel] +// and [service perimeters] +// [google.identity.accesscontextmanager.v1.ServicePerimeter]. This +// [access policy] [google.identity.accesscontextmanager.v1.AccessPolicy] is +// applicable to all resources in the organization. +// AccessPolicies +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://accesscontextmanager.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://accesscontextmanager.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://accesscontextmanager.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) ListAccessPolicies(ctx context.Context, req *accesscontextmanagerpb.ListAccessPoliciesRequest, opts ...gax.CallOption) *AccessPolicyIterator { ctx = insertMetadata(ctx, c.xGoogMetadata) opts = append((*c.CallOptions).ListAccessPolicies[0:len((*c.CallOptions).ListAccessPolicies):len((*c.CallOptions).ListAccessPolicies)], opts...) @@ -1391,126 +1522,2157 @@ func (c *gRPCClient) GetOperation(ctx context.Context, req *longrunningpb.GetOpe return resp, nil } -// CommitServicePerimetersOperation manages a long-running operation from CommitServicePerimeters. -type CommitServicePerimetersOperation struct { - lro *longrunning.Operation -} +// ListAccessPolicies lists all [access policies] +// [google.identity.accesscontextmanager.v1.AccessPolicy] in an +// organization. +func (c *restClient) ListAccessPolicies(ctx context.Context, req *accesscontextmanagerpb.ListAccessPoliciesRequest, opts ...gax.CallOption) *AccessPolicyIterator { + it := &AccessPolicyIterator{} + req = proto.Clone(req).(*accesscontextmanagerpb.ListAccessPoliciesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*accesscontextmanagerpb.AccessPolicy, string, error) { + resp := &accesscontextmanagerpb.ListAccessPoliciesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/accessPolicies") -// CommitServicePerimetersOperation returns a new CommitServicePerimetersOperation from a given name. -// The name must be that of a previously created CommitServicePerimetersOperation, possibly from a different process. -func (c *gRPCClient) CommitServicePerimetersOperation(name string) *CommitServicePerimetersOperation { - return &CommitServicePerimetersOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + params.Add("parent", fmt.Sprintf("%v", req.GetParent())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetAccessPolicies(), resp.GetNextPageToken(), nil } -} -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *CommitServicePerimetersOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*accesscontextmanagerpb.CommitServicePerimetersResponse, error) { - var resp accesscontextmanagerpb.CommitServicePerimetersResponse - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { - return nil, err + 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 } - return &resp, nil -} -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *CommitServicePerimetersOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*accesscontextmanagerpb.CommitServicePerimetersResponse, error) { - var resp accesscontextmanagerpb.CommitServicePerimetersResponse - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { - return nil, err - } - if !op.Done() { - return nil, nil - } - return &resp, nil + it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it } -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *CommitServicePerimetersOperation) Metadata() (*accesscontextmanagerpb.AccessContextManagerOperationMetadata, error) { - var meta accesscontextmanagerpb.AccessContextManagerOperationMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { +// GetAccessPolicy returns an [access policy] +// [google.identity.accesscontextmanager.v1.AccessPolicy] based on the name. +func (c *restClient) GetAccessPolicy(ctx context.Context, req *accesscontextmanagerpb.GetAccessPolicyRequest, opts ...gax.CallOption) (*accesscontextmanagerpb.AccessPolicy, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - return &meta, nil -} + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) -// Done reports whether the long-running operation has completed. -func (op *CommitServicePerimetersOperation) Done() bool { - return op.lro.Done() -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") -// 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 *CommitServicePerimetersOperation) Name() string { - return op.lro.Name() -} + baseUrl.RawQuery = params.Encode() -// CreateAccessLevelOperation manages a long-running operation from CreateAccessLevel. -type CreateAccessLevelOperation struct { - lro *longrunning.Operation -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) -// CreateAccessLevelOperation returns a new CreateAccessLevelOperation from a given name. -// The name must be that of a previously created CreateAccessLevelOperation, possibly from a different process. -func (c *gRPCClient) CreateAccessLevelOperation(name string) *CreateAccessLevelOperation { - return &CreateAccessLevelOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetAccessPolicy[0:len((*c.CallOptions).GetAccessPolicy):len((*c.CallOptions).GetAccessPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &accesscontextmanagerpb.AccessPolicy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e } + return resp, nil } -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *CreateAccessLevelOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*accesscontextmanagerpb.AccessLevel, error) { - var resp accesscontextmanagerpb.AccessLevel - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { +// CreateAccessPolicy creates an access policy. This method fails if the organization already has +// an access policy. The long-running operation has a successful status +// after the access policy propagates to long-lasting storage. +// Syntactic and basic semantic errors are returned in metadata as a +// BadRequest proto. +func (c *restClient) CreateAccessPolicy(ctx context.Context, req *accesscontextmanagerpb.AccessPolicy, opts ...gax.CallOption) (*CreateAccessPolicyOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { return nil, err } - return &resp, nil -} -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *CreateAccessLevelOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*accesscontextmanagerpb.AccessLevel, error) { - var resp accesscontextmanagerpb.AccessLevel - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - if !op.Done() { - return nil, nil - } - return &resp, nil -} + baseUrl.Path += fmt.Sprintf("/v1/accessPolicies") -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *CreateAccessLevelOperation) Metadata() (*accesscontextmanagerpb.AccessContextManagerOperationMetadata, error) { - var meta accesscontextmanagerpb.AccessContextManagerOperationMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateAccessPolicyOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateAccessPolicy updates an [access policy] +// [google.identity.accesscontextmanager.v1.AccessPolicy]. The +// long-running operation from this RPC has a successful status after the +// changes to the [access policy] +// [google.identity.accesscontextmanager.v1.AccessPolicy] propagate +// to long-lasting storage. +func (c *restClient) UpdateAccessPolicy(ctx context.Context, req *accesscontextmanagerpb.UpdateAccessPolicyRequest, opts ...gax.CallOption) (*UpdateAccessPolicyOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetPolicy() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetPolicy().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "policy.name", url.QueryEscape(req.GetPolicy().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateAccessPolicyOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteAccessPolicy deletes an [access policy] +// [google.identity.accesscontextmanager.v1.AccessPolicy] based on the +// resource name. The long-running operation has a successful status after the +// [access policy] [google.identity.accesscontextmanager.v1.AccessPolicy] +// is removed from long-lasting storage. +func (c *restClient) DeleteAccessPolicy(ctx context.Context, req *accesscontextmanagerpb.DeleteAccessPolicyRequest, opts ...gax.CallOption) (*DeleteAccessPolicyOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteAccessPolicyOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListAccessLevels lists all [access levels] +// [google.identity.accesscontextmanager.v1.AccessLevel] for an access +// policy. +func (c *restClient) ListAccessLevels(ctx context.Context, req *accesscontextmanagerpb.ListAccessLevelsRequest, opts ...gax.CallOption) *AccessLevelIterator { + it := &AccessLevelIterator{} + req = proto.Clone(req).(*accesscontextmanagerpb.ListAccessLevelsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*accesscontextmanagerpb.AccessLevel, string, error) { + resp := &accesscontextmanagerpb.ListAccessLevelsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/accessLevels", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetAccessLevelFormat() != 0 { + params.Add("accessLevelFormat", fmt.Sprintf("%v", req.GetAccessLevelFormat())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetAccessLevels(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetAccessLevel gets an [access level] +// [google.identity.accesscontextmanager.v1.AccessLevel] based on the resource +// name. +func (c *restClient) GetAccessLevel(ctx context.Context, req *accesscontextmanagerpb.GetAccessLevelRequest, opts ...gax.CallOption) (*accesscontextmanagerpb.AccessLevel, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetAccessLevelFormat() != 0 { + params.Add("accessLevelFormat", fmt.Sprintf("%v", req.GetAccessLevelFormat())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetAccessLevel[0:len((*c.CallOptions).GetAccessLevel):len((*c.CallOptions).GetAccessLevel)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &accesscontextmanagerpb.AccessLevel{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateAccessLevel creates an [access level] +// [google.identity.accesscontextmanager.v1.AccessLevel]. The long-running +// operation from this RPC has a successful status after the [access +// level] [google.identity.accesscontextmanager.v1.AccessLevel] +// propagates to long-lasting storage. If [access levels] +// [google.identity.accesscontextmanager.v1.AccessLevel] contain +// errors, an error response is returned for the first error encountered. +func (c *restClient) CreateAccessLevel(ctx context.Context, req *accesscontextmanagerpb.CreateAccessLevelRequest, opts ...gax.CallOption) (*CreateAccessLevelOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetAccessLevel() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/accessLevels", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateAccessLevelOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateAccessLevel updates an [access level] +// [google.identity.accesscontextmanager.v1.AccessLevel]. The long-running +// operation from this RPC has a successful status after the changes to +// the [access level] +// [google.identity.accesscontextmanager.v1.AccessLevel] propagate +// to long-lasting storage. If [access levels] +// [google.identity.accesscontextmanager.v1.AccessLevel] contain +// errors, an error response is returned for the first error encountered. +func (c *restClient) UpdateAccessLevel(ctx context.Context, req *accesscontextmanagerpb.UpdateAccessLevelRequest, opts ...gax.CallOption) (*UpdateAccessLevelOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetAccessLevel() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetAccessLevel().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "access_level.name", url.QueryEscape(req.GetAccessLevel().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateAccessLevelOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteAccessLevel deletes an [access level] +// [google.identity.accesscontextmanager.v1.AccessLevel] based on the resource +// name. The long-running operation from this RPC has a successful status +// after the [access level] +// [google.identity.accesscontextmanager.v1.AccessLevel] has been removed +// from long-lasting storage. +func (c *restClient) DeleteAccessLevel(ctx context.Context, req *accesscontextmanagerpb.DeleteAccessLevelRequest, opts ...gax.CallOption) (*DeleteAccessLevelOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteAccessLevelOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ReplaceAccessLevels replaces all existing [access levels] +// [google.identity.accesscontextmanager.v1.AccessLevel] in an [access +// policy] [google.identity.accesscontextmanager.v1.AccessPolicy] with +// the [access levels] +// [google.identity.accesscontextmanager.v1.AccessLevel] provided. This +// is done atomically. The long-running operation from this RPC has a +// successful status after all replacements propagate to long-lasting +// storage. If the replacement contains errors, an error response is returned +// for the first error encountered. Upon error, the replacement is cancelled, +// and existing [access levels] +// [google.identity.accesscontextmanager.v1.AccessLevel] are not +// affected. The Operation.response field contains +// ReplaceAccessLevelsResponse. Removing [access levels] +// [google.identity.accesscontextmanager.v1.AccessLevel] contained in existing +// [service perimeters] +// [google.identity.accesscontextmanager.v1.ServicePerimeter] result in an +// error. +func (c *restClient) ReplaceAccessLevels(ctx context.Context, req *accesscontextmanagerpb.ReplaceAccessLevelsRequest, opts ...gax.CallOption) (*ReplaceAccessLevelsOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/accessLevels:replaceAll", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &ReplaceAccessLevelsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListServicePerimeters lists all [service perimeters] +// [google.identity.accesscontextmanager.v1.ServicePerimeter] for an +// access policy. +func (c *restClient) ListServicePerimeters(ctx context.Context, req *accesscontextmanagerpb.ListServicePerimetersRequest, opts ...gax.CallOption) *ServicePerimeterIterator { + it := &ServicePerimeterIterator{} + req = proto.Clone(req).(*accesscontextmanagerpb.ListServicePerimetersRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*accesscontextmanagerpb.ServicePerimeter, string, error) { + resp := &accesscontextmanagerpb.ListServicePerimetersResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/servicePerimeters", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetServicePerimeters(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetServicePerimeter gets a [service perimeter] +// [google.identity.accesscontextmanager.v1.ServicePerimeter] based on the +// resource name. +func (c *restClient) GetServicePerimeter(ctx context.Context, req *accesscontextmanagerpb.GetServicePerimeterRequest, opts ...gax.CallOption) (*accesscontextmanagerpb.ServicePerimeter, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetServicePerimeter[0:len((*c.CallOptions).GetServicePerimeter):len((*c.CallOptions).GetServicePerimeter)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &accesscontextmanagerpb.ServicePerimeter{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateServicePerimeter creates a [service perimeter] +// [google.identity.accesscontextmanager.v1.ServicePerimeter]. The +// long-running operation from this RPC has a successful status after the +// [service perimeter] +// [google.identity.accesscontextmanager.v1.ServicePerimeter] +// propagates to long-lasting storage. If a [service perimeter] +// [google.identity.accesscontextmanager.v1.ServicePerimeter] contains +// errors, an error response is returned for the first error encountered. +func (c *restClient) CreateServicePerimeter(ctx context.Context, req *accesscontextmanagerpb.CreateServicePerimeterRequest, opts ...gax.CallOption) (*CreateServicePerimeterOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetServicePerimeter() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/servicePerimeters", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateServicePerimeterOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateServicePerimeter updates a [service perimeter] +// [google.identity.accesscontextmanager.v1.ServicePerimeter]. The +// long-running operation from this RPC has a successful status after the +// [service perimeter] +// [google.identity.accesscontextmanager.v1.ServicePerimeter] +// propagates to long-lasting storage. If a [service perimeter] +// [google.identity.accesscontextmanager.v1.ServicePerimeter] contains +// errors, an error response is returned for the first error encountered. +func (c *restClient) UpdateServicePerimeter(ctx context.Context, req *accesscontextmanagerpb.UpdateServicePerimeterRequest, opts ...gax.CallOption) (*UpdateServicePerimeterOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetServicePerimeter() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetServicePerimeter().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "service_perimeter.name", url.QueryEscape(req.GetServicePerimeter().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateServicePerimeterOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteServicePerimeter deletes a [service perimeter] +// [google.identity.accesscontextmanager.v1.ServicePerimeter] based on the +// resource name. The long-running operation from this RPC has a successful +// status after the [service perimeter] +// [google.identity.accesscontextmanager.v1.ServicePerimeter] is removed from +// long-lasting storage. +func (c *restClient) DeleteServicePerimeter(ctx context.Context, req *accesscontextmanagerpb.DeleteServicePerimeterRequest, opts ...gax.CallOption) (*DeleteServicePerimeterOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteServicePerimeterOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ReplaceServicePerimeters replace all existing [service perimeters] +// [google.identity.accesscontextmanager.v1.ServicePerimeter] in an [access +// policy] [google.identity.accesscontextmanager.v1.AccessPolicy] with the +// [service perimeters] +// [google.identity.accesscontextmanager.v1.ServicePerimeter] provided. This +// is done atomically. The long-running operation from this RPC has a +// successful status after all replacements propagate to long-lasting storage. +// Replacements containing errors result in an error response for the first +// error encountered. Upon an error, replacement are cancelled and existing +// [service perimeters] +// [google.identity.accesscontextmanager.v1.ServicePerimeter] are not +// affected. The Operation.response field contains +// ReplaceServicePerimetersResponse. +func (c *restClient) ReplaceServicePerimeters(ctx context.Context, req *accesscontextmanagerpb.ReplaceServicePerimetersRequest, opts ...gax.CallOption) (*ReplaceServicePerimetersOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/servicePerimeters:replaceAll", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &ReplaceServicePerimetersOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// CommitServicePerimeters commits the dry-run specification for all the [service perimeters] +// [google.identity.accesscontextmanager.v1.ServicePerimeter] in an +// [access policy][google.identity.accesscontextmanager.v1.AccessPolicy]. +// A commit operation on a service perimeter involves copying its spec field +// to the status field of the service perimeter. Only [service perimeters] +// [google.identity.accesscontextmanager.v1.ServicePerimeter] with +// use_explicit_dry_run_spec field set to true are affected by a commit +// operation. The long-running operation from this RPC has a successful +// status after the dry-run specifications for all the [service perimeters] +// [google.identity.accesscontextmanager.v1.ServicePerimeter] have been +// committed. If a commit fails, it causes the long-running operation to +// return an error response and the entire commit operation is cancelled. +// When successful, the Operation.response field contains +// CommitServicePerimetersResponse. The dry_run and the spec fields are +// cleared after a successful commit operation. +func (c *restClient) CommitServicePerimeters(ctx context.Context, req *accesscontextmanagerpb.CommitServicePerimetersRequest, opts ...gax.CallOption) (*CommitServicePerimetersOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/servicePerimeters:commit", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CommitServicePerimetersOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListGcpUserAccessBindings lists all [GcpUserAccessBindings] +// [google.identity.accesscontextmanager.v1.GcpUserAccessBinding] for a +// Google Cloud organization. +func (c *restClient) ListGcpUserAccessBindings(ctx context.Context, req *accesscontextmanagerpb.ListGcpUserAccessBindingsRequest, opts ...gax.CallOption) *GcpUserAccessBindingIterator { + it := &GcpUserAccessBindingIterator{} + req = proto.Clone(req).(*accesscontextmanagerpb.ListGcpUserAccessBindingsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*accesscontextmanagerpb.GcpUserAccessBinding, string, error) { + resp := &accesscontextmanagerpb.ListGcpUserAccessBindingsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/gcpUserAccessBindings", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetGcpUserAccessBindings(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetGcpUserAccessBinding gets the [GcpUserAccessBinding] +// [google.identity.accesscontextmanager.v1.GcpUserAccessBinding] with +// the given name. +func (c *restClient) GetGcpUserAccessBinding(ctx context.Context, req *accesscontextmanagerpb.GetGcpUserAccessBindingRequest, opts ...gax.CallOption) (*accesscontextmanagerpb.GcpUserAccessBinding, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetGcpUserAccessBinding[0:len((*c.CallOptions).GetGcpUserAccessBinding):len((*c.CallOptions).GetGcpUserAccessBinding)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &accesscontextmanagerpb.GcpUserAccessBinding{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateGcpUserAccessBinding creates a [GcpUserAccessBinding] +// [google.identity.accesscontextmanager.v1.GcpUserAccessBinding]. If the +// client specifies a [name] +// [google.identity.accesscontextmanager.v1.GcpUserAccessBinding.name (at http://google.identity.accesscontextmanager.v1.GcpUserAccessBinding.name)], +// the server ignores it. Fails if a resource already exists with the same +// [group_key] +// [google.identity.accesscontextmanager.v1.GcpUserAccessBinding.group_key]. +// Completion of this long-running operation does not necessarily signify that +// the new binding is deployed onto all affected users, which may take more +// time. +func (c *restClient) CreateGcpUserAccessBinding(ctx context.Context, req *accesscontextmanagerpb.CreateGcpUserAccessBindingRequest, opts ...gax.CallOption) (*CreateGcpUserAccessBindingOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetGcpUserAccessBinding() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/gcpUserAccessBindings", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateGcpUserAccessBindingOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateGcpUserAccessBinding updates a [GcpUserAccessBinding] +// [google.identity.accesscontextmanager.v1.GcpUserAccessBinding]. +// Completion of this long-running operation does not necessarily signify that +// the changed binding is deployed onto all affected users, which may take +// more time. +func (c *restClient) UpdateGcpUserAccessBinding(ctx context.Context, req *accesscontextmanagerpb.UpdateGcpUserAccessBindingRequest, opts ...gax.CallOption) (*UpdateGcpUserAccessBindingOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetGcpUserAccessBinding() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetGcpUserAccessBinding().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "gcp_user_access_binding.name", url.QueryEscape(req.GetGcpUserAccessBinding().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateGcpUserAccessBindingOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteGcpUserAccessBinding deletes a [GcpUserAccessBinding] +// [google.identity.accesscontextmanager.v1.GcpUserAccessBinding]. +// Completion of this long-running operation does not necessarily signify that +// the binding deletion is deployed onto all affected users, which may take +// more time. +func (c *restClient) DeleteGcpUserAccessBinding(ctx context.Context, req *accesscontextmanagerpb.DeleteGcpUserAccessBindingRequest, opts ...gax.CallOption) (*DeleteGcpUserAccessBindingOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteGcpUserAccessBindingOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// SetIamPolicy sets the IAM policy for the specified Access Context Manager +// [access policy][google.identity.accesscontextmanager.v1.AccessPolicy]. +// This method replaces the existing IAM policy on the access policy. The IAM +// policy controls the set of users who can perform specific operations on the +// Access Context Manager [access +// policy][google.identity.accesscontextmanager.v1.AccessPolicy]. +func (c *restClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:setIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetIamPolicy gets the IAM policy for the specified Access Context Manager +// [access policy][google.identity.accesscontextmanager.v1.AccessPolicy]. +func (c *restClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:getIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// TestIamPermissions returns the IAM permissions that the caller has on the specified Access +// Context Manager resource. The resource can be an +// AccessPolicy, +// AccessLevel, or +// [ServicePerimeter][google.identity.accesscontextmanager.v1.ServicePerimeter +// ]. This method does not support other resources. +func (c *restClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:testIamPermissions", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.TestIamPermissionsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *restClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CommitServicePerimetersOperation manages a long-running operation from CommitServicePerimeters. +type CommitServicePerimetersOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CommitServicePerimetersOperation returns a new CommitServicePerimetersOperation from a given name. +// The name must be that of a previously created CommitServicePerimetersOperation, possibly from a different process. +func (c *gRPCClient) CommitServicePerimetersOperation(name string) *CommitServicePerimetersOperation { + return &CommitServicePerimetersOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CommitServicePerimetersOperation returns a new CommitServicePerimetersOperation from a given name. +// The name must be that of a previously created CommitServicePerimetersOperation, possibly from a different process. +func (c *restClient) CommitServicePerimetersOperation(name string) *CommitServicePerimetersOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CommitServicePerimetersOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CommitServicePerimetersOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*accesscontextmanagerpb.CommitServicePerimetersResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp accesscontextmanagerpb.CommitServicePerimetersResponse + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *CommitServicePerimetersOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*accesscontextmanagerpb.CommitServicePerimetersResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp accesscontextmanagerpb.CommitServicePerimetersResponse + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *CommitServicePerimetersOperation) Metadata() (*accesscontextmanagerpb.AccessContextManagerOperationMetadata, error) { + var meta accesscontextmanagerpb.AccessContextManagerOperationMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *CommitServicePerimetersOperation) Done() bool { + return op.lro.Done() +} + +// 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 *CommitServicePerimetersOperation) Name() string { + return op.lro.Name() +} + +// CreateAccessLevelOperation manages a long-running operation from CreateAccessLevel. +type CreateAccessLevelOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateAccessLevelOperation returns a new CreateAccessLevelOperation from a given name. +// The name must be that of a previously created CreateAccessLevelOperation, possibly from a different process. +func (c *gRPCClient) CreateAccessLevelOperation(name string) *CreateAccessLevelOperation { + return &CreateAccessLevelOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateAccessLevelOperation returns a new CreateAccessLevelOperation from a given name. +// The name must be that of a previously created CreateAccessLevelOperation, possibly from a different process. +func (c *restClient) CreateAccessLevelOperation(name string) *CreateAccessLevelOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateAccessLevelOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CreateAccessLevelOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*accesscontextmanagerpb.AccessLevel, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp accesscontextmanagerpb.AccessLevel + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *CreateAccessLevelOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*accesscontextmanagerpb.AccessLevel, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp accesscontextmanagerpb.AccessLevel + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *CreateAccessLevelOperation) Metadata() (*accesscontextmanagerpb.AccessContextManagerOperationMetadata, error) { + var meta accesscontextmanagerpb.AccessContextManagerOperationMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { return nil, nil } else if err != nil { return nil, err @@ -1531,7 +3693,8 @@ func (op *CreateAccessLevelOperation) Name() string { // CreateAccessPolicyOperation manages a long-running operation from CreateAccessPolicy. type CreateAccessPolicyOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateAccessPolicyOperation returns a new CreateAccessPolicyOperation from a given name. @@ -1542,10 +3705,21 @@ func (c *gRPCClient) CreateAccessPolicyOperation(name string) *CreateAccessPolic } } +// CreateAccessPolicyOperation returns a new CreateAccessPolicyOperation from a given name. +// The name must be that of a previously created CreateAccessPolicyOperation, possibly from a different process. +func (c *restClient) CreateAccessPolicyOperation(name string) *CreateAccessPolicyOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateAccessPolicyOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateAccessPolicyOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*accesscontextmanagerpb.AccessPolicy, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp accesscontextmanagerpb.AccessPolicy if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1563,6 +3737,7 @@ func (op *CreateAccessPolicyOperation) Wait(ctx context.Context, opts ...gax.Cal // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateAccessPolicyOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*accesscontextmanagerpb.AccessPolicy, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp accesscontextmanagerpb.AccessPolicy if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1600,7 +3775,8 @@ func (op *CreateAccessPolicyOperation) Name() string { // CreateGcpUserAccessBindingOperation manages a long-running operation from CreateGcpUserAccessBinding. type CreateGcpUserAccessBindingOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateGcpUserAccessBindingOperation returns a new CreateGcpUserAccessBindingOperation from a given name. @@ -1611,10 +3787,21 @@ func (c *gRPCClient) CreateGcpUserAccessBindingOperation(name string) *CreateGcp } } +// CreateGcpUserAccessBindingOperation returns a new CreateGcpUserAccessBindingOperation from a given name. +// The name must be that of a previously created CreateGcpUserAccessBindingOperation, possibly from a different process. +func (c *restClient) CreateGcpUserAccessBindingOperation(name string) *CreateGcpUserAccessBindingOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateGcpUserAccessBindingOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateGcpUserAccessBindingOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*accesscontextmanagerpb.GcpUserAccessBinding, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp accesscontextmanagerpb.GcpUserAccessBinding if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1632,6 +3819,7 @@ func (op *CreateGcpUserAccessBindingOperation) Wait(ctx context.Context, opts .. // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateGcpUserAccessBindingOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*accesscontextmanagerpb.GcpUserAccessBinding, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp accesscontextmanagerpb.GcpUserAccessBinding if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1669,7 +3857,8 @@ func (op *CreateGcpUserAccessBindingOperation) Name() string { // CreateServicePerimeterOperation manages a long-running operation from CreateServicePerimeter. type CreateServicePerimeterOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateServicePerimeterOperation returns a new CreateServicePerimeterOperation from a given name. @@ -1680,10 +3869,21 @@ func (c *gRPCClient) CreateServicePerimeterOperation(name string) *CreateService } } +// CreateServicePerimeterOperation returns a new CreateServicePerimeterOperation from a given name. +// The name must be that of a previously created CreateServicePerimeterOperation, possibly from a different process. +func (c *restClient) CreateServicePerimeterOperation(name string) *CreateServicePerimeterOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateServicePerimeterOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateServicePerimeterOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*accesscontextmanagerpb.ServicePerimeter, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp accesscontextmanagerpb.ServicePerimeter if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1701,6 +3901,7 @@ func (op *CreateServicePerimeterOperation) Wait(ctx context.Context, opts ...gax // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateServicePerimeterOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*accesscontextmanagerpb.ServicePerimeter, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp accesscontextmanagerpb.ServicePerimeter if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1738,7 +3939,8 @@ func (op *CreateServicePerimeterOperation) Name() string { // DeleteAccessLevelOperation manages a long-running operation from DeleteAccessLevel. type DeleteAccessLevelOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteAccessLevelOperation returns a new DeleteAccessLevelOperation from a given name. @@ -1749,10 +3951,21 @@ func (c *gRPCClient) DeleteAccessLevelOperation(name string) *DeleteAccessLevelO } } +// DeleteAccessLevelOperation returns a new DeleteAccessLevelOperation from a given name. +// The name must be that of a previously created DeleteAccessLevelOperation, possibly from a different process. +func (c *restClient) DeleteAccessLevelOperation(name string) *DeleteAccessLevelOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteAccessLevelOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteAccessLevelOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -1766,6 +3979,7 @@ func (op *DeleteAccessLevelOperation) Wait(ctx context.Context, opts ...gax.Call // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteAccessLevelOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -1796,7 +4010,8 @@ func (op *DeleteAccessLevelOperation) Name() string { // DeleteAccessPolicyOperation manages a long-running operation from DeleteAccessPolicy. type DeleteAccessPolicyOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteAccessPolicyOperation returns a new DeleteAccessPolicyOperation from a given name. @@ -1807,10 +4022,21 @@ func (c *gRPCClient) DeleteAccessPolicyOperation(name string) *DeleteAccessPolic } } +// DeleteAccessPolicyOperation returns a new DeleteAccessPolicyOperation from a given name. +// The name must be that of a previously created DeleteAccessPolicyOperation, possibly from a different process. +func (c *restClient) DeleteAccessPolicyOperation(name string) *DeleteAccessPolicyOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteAccessPolicyOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteAccessPolicyOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -1824,6 +4050,7 @@ func (op *DeleteAccessPolicyOperation) Wait(ctx context.Context, opts ...gax.Cal // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteAccessPolicyOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -1854,7 +4081,8 @@ func (op *DeleteAccessPolicyOperation) Name() string { // DeleteGcpUserAccessBindingOperation manages a long-running operation from DeleteGcpUserAccessBinding. type DeleteGcpUserAccessBindingOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteGcpUserAccessBindingOperation returns a new DeleteGcpUserAccessBindingOperation from a given name. @@ -1865,10 +4093,21 @@ func (c *gRPCClient) DeleteGcpUserAccessBindingOperation(name string) *DeleteGcp } } +// DeleteGcpUserAccessBindingOperation returns a new DeleteGcpUserAccessBindingOperation from a given name. +// The name must be that of a previously created DeleteGcpUserAccessBindingOperation, possibly from a different process. +func (c *restClient) DeleteGcpUserAccessBindingOperation(name string) *DeleteGcpUserAccessBindingOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteGcpUserAccessBindingOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteGcpUserAccessBindingOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -1882,6 +4121,7 @@ func (op *DeleteGcpUserAccessBindingOperation) Wait(ctx context.Context, opts .. // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteGcpUserAccessBindingOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -1912,7 +4152,8 @@ func (op *DeleteGcpUserAccessBindingOperation) Name() string { // DeleteServicePerimeterOperation manages a long-running operation from DeleteServicePerimeter. type DeleteServicePerimeterOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteServicePerimeterOperation returns a new DeleteServicePerimeterOperation from a given name. @@ -1923,10 +4164,21 @@ func (c *gRPCClient) DeleteServicePerimeterOperation(name string) *DeleteService } } +// DeleteServicePerimeterOperation returns a new DeleteServicePerimeterOperation from a given name. +// The name must be that of a previously created DeleteServicePerimeterOperation, possibly from a different process. +func (c *restClient) DeleteServicePerimeterOperation(name string) *DeleteServicePerimeterOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteServicePerimeterOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteServicePerimeterOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -1940,6 +4192,7 @@ func (op *DeleteServicePerimeterOperation) Wait(ctx context.Context, opts ...gax // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteServicePerimeterOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -1970,7 +4223,8 @@ func (op *DeleteServicePerimeterOperation) Name() string { // ReplaceAccessLevelsOperation manages a long-running operation from ReplaceAccessLevels. type ReplaceAccessLevelsOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // ReplaceAccessLevelsOperation returns a new ReplaceAccessLevelsOperation from a given name. @@ -1981,10 +4235,21 @@ func (c *gRPCClient) ReplaceAccessLevelsOperation(name string) *ReplaceAccessLev } } +// ReplaceAccessLevelsOperation returns a new ReplaceAccessLevelsOperation from a given name. +// The name must be that of a previously created ReplaceAccessLevelsOperation, possibly from a different process. +func (c *restClient) ReplaceAccessLevelsOperation(name string) *ReplaceAccessLevelsOperation { + override := fmt.Sprintf("/v1/%s", name) + return &ReplaceAccessLevelsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *ReplaceAccessLevelsOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*accesscontextmanagerpb.ReplaceAccessLevelsResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp accesscontextmanagerpb.ReplaceAccessLevelsResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2002,6 +4267,7 @@ func (op *ReplaceAccessLevelsOperation) Wait(ctx context.Context, opts ...gax.Ca // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *ReplaceAccessLevelsOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*accesscontextmanagerpb.ReplaceAccessLevelsResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp accesscontextmanagerpb.ReplaceAccessLevelsResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2039,7 +4305,8 @@ func (op *ReplaceAccessLevelsOperation) Name() string { // ReplaceServicePerimetersOperation manages a long-running operation from ReplaceServicePerimeters. type ReplaceServicePerimetersOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // ReplaceServicePerimetersOperation returns a new ReplaceServicePerimetersOperation from a given name. @@ -2050,10 +4317,21 @@ func (c *gRPCClient) ReplaceServicePerimetersOperation(name string) *ReplaceServ } } +// ReplaceServicePerimetersOperation returns a new ReplaceServicePerimetersOperation from a given name. +// The name must be that of a previously created ReplaceServicePerimetersOperation, possibly from a different process. +func (c *restClient) ReplaceServicePerimetersOperation(name string) *ReplaceServicePerimetersOperation { + override := fmt.Sprintf("/v1/%s", name) + return &ReplaceServicePerimetersOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *ReplaceServicePerimetersOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*accesscontextmanagerpb.ReplaceServicePerimetersResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp accesscontextmanagerpb.ReplaceServicePerimetersResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2071,6 +4349,7 @@ func (op *ReplaceServicePerimetersOperation) Wait(ctx context.Context, opts ...g // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *ReplaceServicePerimetersOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*accesscontextmanagerpb.ReplaceServicePerimetersResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp accesscontextmanagerpb.ReplaceServicePerimetersResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2108,7 +4387,8 @@ func (op *ReplaceServicePerimetersOperation) Name() string { // UpdateAccessLevelOperation manages a long-running operation from UpdateAccessLevel. type UpdateAccessLevelOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateAccessLevelOperation returns a new UpdateAccessLevelOperation from a given name. @@ -2119,10 +4399,21 @@ func (c *gRPCClient) UpdateAccessLevelOperation(name string) *UpdateAccessLevelO } } +// UpdateAccessLevelOperation returns a new UpdateAccessLevelOperation from a given name. +// The name must be that of a previously created UpdateAccessLevelOperation, possibly from a different process. +func (c *restClient) UpdateAccessLevelOperation(name string) *UpdateAccessLevelOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateAccessLevelOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateAccessLevelOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*accesscontextmanagerpb.AccessLevel, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp accesscontextmanagerpb.AccessLevel if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2140,6 +4431,7 @@ func (op *UpdateAccessLevelOperation) Wait(ctx context.Context, opts ...gax.Call // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateAccessLevelOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*accesscontextmanagerpb.AccessLevel, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp accesscontextmanagerpb.AccessLevel if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2177,7 +4469,8 @@ func (op *UpdateAccessLevelOperation) Name() string { // UpdateAccessPolicyOperation manages a long-running operation from UpdateAccessPolicy. type UpdateAccessPolicyOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateAccessPolicyOperation returns a new UpdateAccessPolicyOperation from a given name. @@ -2188,10 +4481,21 @@ func (c *gRPCClient) UpdateAccessPolicyOperation(name string) *UpdateAccessPolic } } +// UpdateAccessPolicyOperation returns a new UpdateAccessPolicyOperation from a given name. +// The name must be that of a previously created UpdateAccessPolicyOperation, possibly from a different process. +func (c *restClient) UpdateAccessPolicyOperation(name string) *UpdateAccessPolicyOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateAccessPolicyOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateAccessPolicyOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*accesscontextmanagerpb.AccessPolicy, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp accesscontextmanagerpb.AccessPolicy if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2209,6 +4513,7 @@ func (op *UpdateAccessPolicyOperation) Wait(ctx context.Context, opts ...gax.Cal // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateAccessPolicyOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*accesscontextmanagerpb.AccessPolicy, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp accesscontextmanagerpb.AccessPolicy if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2246,7 +4551,8 @@ func (op *UpdateAccessPolicyOperation) Name() string { // UpdateGcpUserAccessBindingOperation manages a long-running operation from UpdateGcpUserAccessBinding. type UpdateGcpUserAccessBindingOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateGcpUserAccessBindingOperation returns a new UpdateGcpUserAccessBindingOperation from a given name. @@ -2257,10 +4563,21 @@ func (c *gRPCClient) UpdateGcpUserAccessBindingOperation(name string) *UpdateGcp } } +// UpdateGcpUserAccessBindingOperation returns a new UpdateGcpUserAccessBindingOperation from a given name. +// The name must be that of a previously created UpdateGcpUserAccessBindingOperation, possibly from a different process. +func (c *restClient) UpdateGcpUserAccessBindingOperation(name string) *UpdateGcpUserAccessBindingOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateGcpUserAccessBindingOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateGcpUserAccessBindingOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*accesscontextmanagerpb.GcpUserAccessBinding, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp accesscontextmanagerpb.GcpUserAccessBinding if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2278,6 +4595,7 @@ func (op *UpdateGcpUserAccessBindingOperation) Wait(ctx context.Context, opts .. // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateGcpUserAccessBindingOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*accesscontextmanagerpb.GcpUserAccessBinding, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp accesscontextmanagerpb.GcpUserAccessBinding if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2315,7 +4633,8 @@ func (op *UpdateGcpUserAccessBindingOperation) Name() string { // UpdateServicePerimeterOperation manages a long-running operation from UpdateServicePerimeter. type UpdateServicePerimeterOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateServicePerimeterOperation returns a new UpdateServicePerimeterOperation from a given name. @@ -2326,10 +4645,21 @@ func (c *gRPCClient) UpdateServicePerimeterOperation(name string) *UpdateService } } +// UpdateServicePerimeterOperation returns a new UpdateServicePerimeterOperation from a given name. +// The name must be that of a previously created UpdateServicePerimeterOperation, possibly from a different process. +func (c *restClient) UpdateServicePerimeterOperation(name string) *UpdateServicePerimeterOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateServicePerimeterOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateServicePerimeterOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*accesscontextmanagerpb.ServicePerimeter, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp accesscontextmanagerpb.ServicePerimeter if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2347,6 +4677,7 @@ func (op *UpdateServicePerimeterOperation) Wait(ctx context.Context, opts ...gax // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateServicePerimeterOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*accesscontextmanagerpb.ServicePerimeter, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp accesscontextmanagerpb.ServicePerimeter if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/accesscontextmanager/apiv1/access_context_manager_client_example_test.go b/accesscontextmanager/apiv1/access_context_manager_client_example_test.go index 06c66d4f3b51..cf3555c1b28e 100644 --- a/accesscontextmanager/apiv1/access_context_manager_client_example_test.go +++ b/accesscontextmanager/apiv1/access_context_manager_client_example_test.go @@ -43,6 +43,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := accesscontextmanager.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_ListAccessPolicies() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/accesscontextmanager/apiv1/accesscontextmanagerpb/access_context_manager.pb.go b/accesscontextmanager/apiv1/accesscontextmanagerpb/access_context_manager.pb.go index 3da77c75baf0..39a77c63598b 100644 --- a/accesscontextmanager/apiv1/accesscontextmanagerpb/access_context_manager.pb.go +++ b/accesscontextmanager/apiv1/accesscontextmanagerpb/access_context_manager.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/identity/accesscontextmanager/v1/access_context_manager.proto package accesscontextmanagerpb diff --git a/accesscontextmanager/apiv1/accesscontextmanagerpb/access_level.pb.go b/accesscontextmanager/apiv1/accesscontextmanagerpb/access_level.pb.go index 9c195ffb2f1e..7357d5ff29b1 100644 --- a/accesscontextmanager/apiv1/accesscontextmanagerpb/access_level.pb.go +++ b/accesscontextmanager/apiv1/accesscontextmanagerpb/access_level.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/identity/accesscontextmanager/v1/access_level.proto package accesscontextmanagerpb @@ -109,7 +109,6 @@ type AccessLevel struct { // Required. Describes the necessary conditions for the level to apply. // // Types that are assignable to Level: - // // *AccessLevel_Basic // *AccessLevel_Custom Level isAccessLevel_Level `protobuf_oneof:"level"` @@ -615,7 +614,7 @@ func (x *OsConstraint) GetOsType() _type.OsType { if x != nil { return x.OsType } - return _type.OsType_OS_UNSPECIFIED + return _type.OsType(0) } func (x *OsConstraint) GetMinimumVersion() string { diff --git a/accesscontextmanager/apiv1/accesscontextmanagerpb/access_policy.pb.go b/accesscontextmanager/apiv1/accesscontextmanagerpb/access_policy.pb.go index f342c83c1243..784bcfe2588a 100644 --- a/accesscontextmanager/apiv1/accesscontextmanagerpb/access_policy.pb.go +++ b/accesscontextmanager/apiv1/accesscontextmanagerpb/access_policy.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/identity/accesscontextmanager/v1/access_policy.proto package accesscontextmanagerpb diff --git a/accesscontextmanager/apiv1/accesscontextmanagerpb/gcp_user_access_binding.pb.go b/accesscontextmanager/apiv1/accesscontextmanagerpb/gcp_user_access_binding.pb.go index 9510e68754e5..22079ebaa0e9 100644 --- a/accesscontextmanager/apiv1/accesscontextmanagerpb/gcp_user_access_binding.pb.go +++ b/accesscontextmanager/apiv1/accesscontextmanagerpb/gcp_user_access_binding.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/identity/accesscontextmanager/v1/gcp_user_access_binding.proto package accesscontextmanagerpb diff --git a/accesscontextmanager/apiv1/accesscontextmanagerpb/service_perimeter.pb.go b/accesscontextmanager/apiv1/accesscontextmanagerpb/service_perimeter.pb.go index 3ba9d925c99a..82b2152c2e59 100644 --- a/accesscontextmanager/apiv1/accesscontextmanagerpb/service_perimeter.pb.go +++ b/accesscontextmanager/apiv1/accesscontextmanagerpb/service_perimeter.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/identity/accesscontextmanager/v1/service_perimeter.proto package accesscontextmanagerpb @@ -508,7 +508,6 @@ type ServicePerimeterConfig_MethodSelector struct { // The API method name or Cloud IAM permission name to allow. // // Types that are assignable to Kind: - // // *ServicePerimeterConfig_MethodSelector_Method // *ServicePerimeterConfig_MethodSelector_Permission Kind isServicePerimeterConfig_MethodSelector_Kind `protobuf_oneof:"kind"` @@ -674,7 +673,6 @@ type ServicePerimeterConfig_IngressSource struct { // Cloud resource. // // Types that are assignable to Source: - // // *ServicePerimeterConfig_IngressSource_AccessLevel // *ServicePerimeterConfig_IngressSource_Resource Source isServicePerimeterConfig_IngressSource_Source `protobuf_oneof:"source"` diff --git a/accesscontextmanager/apiv1/doc.go b/accesscontextmanager/apiv1/doc.go index 0cef3506ebbf..8706de67cce8 100644 --- a/accesscontextmanager/apiv1/doc.go +++ b/accesscontextmanager/apiv1/doc.go @@ -87,6 +87,8 @@ package accesscontextmanager // import "cloud.google.com/go/accesscontextmanager import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -175,3 +177,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/accesscontextmanager/apiv1/gapic_metadata.json b/accesscontextmanager/apiv1/gapic_metadata.json index 7e081e05d911..b2bf8526a1a0 100644 --- a/accesscontextmanager/apiv1/gapic_metadata.json +++ b/accesscontextmanager/apiv1/gapic_metadata.json @@ -146,6 +146,146 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "CommitServicePerimeters": { + "methods": [ + "CommitServicePerimeters" + ] + }, + "CreateAccessLevel": { + "methods": [ + "CreateAccessLevel" + ] + }, + "CreateAccessPolicy": { + "methods": [ + "CreateAccessPolicy" + ] + }, + "CreateGcpUserAccessBinding": { + "methods": [ + "CreateGcpUserAccessBinding" + ] + }, + "CreateServicePerimeter": { + "methods": [ + "CreateServicePerimeter" + ] + }, + "DeleteAccessLevel": { + "methods": [ + "DeleteAccessLevel" + ] + }, + "DeleteAccessPolicy": { + "methods": [ + "DeleteAccessPolicy" + ] + }, + "DeleteGcpUserAccessBinding": { + "methods": [ + "DeleteGcpUserAccessBinding" + ] + }, + "DeleteServicePerimeter": { + "methods": [ + "DeleteServicePerimeter" + ] + }, + "GetAccessLevel": { + "methods": [ + "GetAccessLevel" + ] + }, + "GetAccessPolicy": { + "methods": [ + "GetAccessPolicy" + ] + }, + "GetGcpUserAccessBinding": { + "methods": [ + "GetGcpUserAccessBinding" + ] + }, + "GetIamPolicy": { + "methods": [ + "GetIamPolicy" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "GetServicePerimeter": { + "methods": [ + "GetServicePerimeter" + ] + }, + "ListAccessLevels": { + "methods": [ + "ListAccessLevels" + ] + }, + "ListAccessPolicies": { + "methods": [ + "ListAccessPolicies" + ] + }, + "ListGcpUserAccessBindings": { + "methods": [ + "ListGcpUserAccessBindings" + ] + }, + "ListServicePerimeters": { + "methods": [ + "ListServicePerimeters" + ] + }, + "ReplaceAccessLevels": { + "methods": [ + "ReplaceAccessLevels" + ] + }, + "ReplaceServicePerimeters": { + "methods": [ + "ReplaceServicePerimeters" + ] + }, + "SetIamPolicy": { + "methods": [ + "SetIamPolicy" + ] + }, + "TestIamPermissions": { + "methods": [ + "TestIamPermissions" + ] + }, + "UpdateAccessLevel": { + "methods": [ + "UpdateAccessLevel" + ] + }, + "UpdateAccessPolicy": { + "methods": [ + "UpdateAccessPolicy" + ] + }, + "UpdateGcpUserAccessBinding": { + "methods": [ + "UpdateGcpUserAccessBinding" + ] + }, + "UpdateServicePerimeter": { + "methods": [ + "UpdateServicePerimeter" + ] + } + } } } } diff --git a/aiplatform/apiv1/aiplatformpb/accelerator_type.pb.go b/aiplatform/apiv1/aiplatformpb/accelerator_type.pb.go index e71507371b37..09c7022035aa 100644 --- a/aiplatform/apiv1/aiplatformpb/accelerator_type.pb.go +++ b/aiplatform/apiv1/aiplatformpb/accelerator_type.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/accelerator_type.proto package aiplatformpb diff --git a/aiplatform/apiv1/aiplatformpb/annotation.pb.go b/aiplatform/apiv1/aiplatformpb/annotation.pb.go index 6ff1e880d9b4..eceb4e7973c8 100644 --- a/aiplatform/apiv1/aiplatformpb/annotation.pb.go +++ b/aiplatform/apiv1/aiplatformpb/annotation.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/annotation.proto package aiplatformpb @@ -79,13 +79,13 @@ type Annotation struct { // System reserved label keys are prefixed with "aiplatform.googleapis.com/" // and are immutable. Following system labels exist for each Annotation: // - // - "aiplatform.googleapis.com/annotation_set_name": - // optional, name of the UI's annotation set this Annotation belongs to. - // If not set, the Annotation is not visible in the UI. + // * "aiplatform.googleapis.com/annotation_set_name": + // optional, name of the UI's annotation set this Annotation belongs to. + // If not set, the Annotation is not visible in the UI. // - // - "aiplatform.googleapis.com/payload_schema": - // output only, its value is the [payload_schema's][google.cloud.aiplatform.v1.Annotation.payload_schema_uri] - // title. + // * "aiplatform.googleapis.com/payload_schema": + // output only, its value is the [payload_schema's][google.cloud.aiplatform.v1.Annotation.payload_schema_uri] + // title. Labels map[string]string `protobuf:"bytes,6,rep,name=labels,proto3" json:"labels,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` } diff --git a/aiplatform/apiv1/aiplatformpb/annotation_spec.pb.go b/aiplatform/apiv1/aiplatformpb/annotation_spec.pb.go index 75c336ae2cfc..df271d827e40 100644 --- a/aiplatform/apiv1/aiplatformpb/annotation_spec.pb.go +++ b/aiplatform/apiv1/aiplatformpb/annotation_spec.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/annotation_spec.proto package aiplatformpb diff --git a/aiplatform/apiv1/aiplatformpb/artifact.pb.go b/aiplatform/apiv1/aiplatformpb/artifact.pb.go index 97d82edd9379..a33b14b5fc62 100644 --- a/aiplatform/apiv1/aiplatformpb/artifact.pb.go +++ b/aiplatform/apiv1/aiplatformpb/artifact.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/artifact.proto package aiplatformpb diff --git a/aiplatform/apiv1/aiplatformpb/batch_prediction_job.pb.go b/aiplatform/apiv1/aiplatformpb/batch_prediction_job.pb.go index b01301ff3722..20504df140a3 100644 --- a/aiplatform/apiv1/aiplatformpb/batch_prediction_job.pb.go +++ b/aiplatform/apiv1/aiplatformpb/batch_prediction_job.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/batch_prediction_job.proto package aiplatformpb @@ -111,12 +111,12 @@ type BatchPredictionJob struct { // `predictions_format` field of the // [BatchPredictionJob.output_config][google.cloud.aiplatform.v1.BatchPredictionJob.output_config] object: // - // - `bigquery`: output includes a column named `explanation`. The value - // is a struct that conforms to the [Explanation][google.cloud.aiplatform.v1.Explanation] object. - // - `jsonl`: The JSON objects on each line include an additional entry - // keyed `explanation`. The value of the entry is a JSON object that - // conforms to the [Explanation][google.cloud.aiplatform.v1.Explanation] object. - // - `csv`: Generating explanations for CSV format is not supported. + // * `bigquery`: output includes a column named `explanation`. The value + // is a struct that conforms to the [Explanation][google.cloud.aiplatform.v1.Explanation] object. + // * `jsonl`: The JSON objects on each line include an additional entry + // keyed `explanation`. The value of the entry is a JSON object that + // conforms to the [Explanation][google.cloud.aiplatform.v1.Explanation] object. + // * `csv`: Generating explanations for CSV format is not supported. // // If this field is set to true, either the [Model.explanation_spec][google.cloud.aiplatform.v1.Model.explanation_spec] or // [explanation_spec][google.cloud.aiplatform.v1.BatchPredictionJob.explanation_spec] must be populated. @@ -392,7 +392,6 @@ type BatchPredictionJob_InputConfig struct { // Required. The source of the input. // // Types that are assignable to Source: - // // *BatchPredictionJob_InputConfig_GcsSource // *BatchPredictionJob_InputConfig_BigquerySource Source isBatchPredictionJob_InputConfig_Source `protobuf_oneof:"source"` @@ -495,7 +494,6 @@ type BatchPredictionJob_OutputConfig struct { // Required. The destination of the output. // // Types that are assignable to Destination: - // // *BatchPredictionJob_OutputConfig_GcsDestination // *BatchPredictionJob_OutputConfig_BigqueryDestination Destination isBatchPredictionJob_OutputConfig_Destination `protobuf_oneof:"destination"` @@ -631,7 +629,6 @@ type BatchPredictionJob_OutputInfo struct { // The output location into which prediction output is written. // // Types that are assignable to OutputLocation: - // // *BatchPredictionJob_OutputInfo_GcsOutputDirectory // *BatchPredictionJob_OutputInfo_BigqueryOutputDataset OutputLocation isBatchPredictionJob_OutputInfo_OutputLocation `protobuf_oneof:"output_location"` diff --git a/aiplatform/apiv1/aiplatformpb/completion_stats.pb.go b/aiplatform/apiv1/aiplatformpb/completion_stats.pb.go index 968155468f37..1be391f388cd 100644 --- a/aiplatform/apiv1/aiplatformpb/completion_stats.pb.go +++ b/aiplatform/apiv1/aiplatformpb/completion_stats.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/completion_stats.proto package aiplatformpb diff --git a/aiplatform/apiv1/aiplatformpb/context.pb.go b/aiplatform/apiv1/aiplatformpb/context.pb.go index a2e39c53cf53..de773bc05693 100644 --- a/aiplatform/apiv1/aiplatformpb/context.pb.go +++ b/aiplatform/apiv1/aiplatformpb/context.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/context.proto package aiplatformpb diff --git a/aiplatform/apiv1/aiplatformpb/custom_job.pb.go b/aiplatform/apiv1/aiplatformpb/custom_job.pb.go index 59b100b4841a..3f1af1640ee1 100644 --- a/aiplatform/apiv1/aiplatformpb/custom_job.pb.go +++ b/aiplatform/apiv1/aiplatformpb/custom_job.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/custom_job.proto package aiplatformpb @@ -264,17 +264,17 @@ type CustomJobSpec struct { // The following Vertex AI environment variables will be passed to // containers or python modules when this field is set: // - // For CustomJob: + // For CustomJob: // - // * AIP_MODEL_DIR = `/model/` - // * AIP_CHECKPOINT_DIR = `/checkpoints/` - // * AIP_TENSORBOARD_LOG_DIR = `/logs/` + // * AIP_MODEL_DIR = `/model/` + // * AIP_CHECKPOINT_DIR = `/checkpoints/` + // * AIP_TENSORBOARD_LOG_DIR = `/logs/` // - // For CustomJob backing a Trial of HyperparameterTuningJob: + // For CustomJob backing a Trial of HyperparameterTuningJob: // - // * AIP_MODEL_DIR = `//model/` - // * AIP_CHECKPOINT_DIR = `//checkpoints/` - // * AIP_TENSORBOARD_LOG_DIR = `//logs/` + // * AIP_MODEL_DIR = `//model/` + // * AIP_CHECKPOINT_DIR = `//checkpoints/` + // * AIP_TENSORBOARD_LOG_DIR = `//logs/` BaseOutputDirectory *GcsDestination `protobuf:"bytes,6,opt,name=base_output_directory,json=baseOutputDirectory,proto3" json:"base_output_directory,omitempty"` // Optional. The name of a Vertex AI [Tensorboard][google.cloud.aiplatform.v1.Tensorboard] resource to which this CustomJob // will upload Tensorboard logs. @@ -388,7 +388,6 @@ type WorkerPoolSpec struct { // The custom task to be executed in this worker pool. // // Types that are assignable to Task: - // // *WorkerPoolSpec_ContainerSpec // *WorkerPoolSpec_PythonPackageSpec Task isWorkerPoolSpec_Task `protobuf_oneof:"task"` diff --git a/aiplatform/apiv1/aiplatformpb/data_item.pb.go b/aiplatform/apiv1/aiplatformpb/data_item.pb.go index 9343ee52edbb..691d83aa2f55 100644 --- a/aiplatform/apiv1/aiplatformpb/data_item.pb.go +++ b/aiplatform/apiv1/aiplatformpb/data_item.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/data_item.proto package aiplatformpb diff --git a/aiplatform/apiv1/aiplatformpb/data_labeling_job.pb.go b/aiplatform/apiv1/aiplatformpb/data_labeling_job.pb.go index 94c865354d87..bfa1b160ceac 100644 --- a/aiplatform/apiv1/aiplatformpb/data_labeling_job.pb.go +++ b/aiplatform/apiv1/aiplatformpb/data_labeling_job.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/data_labeling_job.proto package aiplatformpb @@ -157,8 +157,8 @@ type DataLabelingJob struct { // System reserved label keys are prefixed with "aiplatform.googleapis.com/" // and are immutable. Following system labels exist for each DataLabelingJob: // - // - "aiplatform.googleapis.com/schema": output only, its value is the - // [inputs_schema][google.cloud.aiplatform.v1.DataLabelingJob.inputs_schema_uri]'s title. + // * "aiplatform.googleapis.com/schema": output only, its value is the + // [inputs_schema][google.cloud.aiplatform.v1.DataLabelingJob.inputs_schema_uri]'s title. Labels map[string]string `protobuf:"bytes,11,rep,name=labels,proto3" json:"labels,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` // The SpecialistPools' resource names associated with this job. SpecialistPools []string `protobuf:"bytes,16,rep,name=specialist_pools,json=specialistPools,proto3" json:"specialist_pools,omitempty"` @@ -345,7 +345,6 @@ type ActiveLearningConfig struct { // machine. // // Types that are assignable to HumanLabelingBudget: - // // *ActiveLearningConfig_MaxDataItemCount // *ActiveLearningConfig_MaxDataItemPercentage HumanLabelingBudget isActiveLearningConfig_HumanLabelingBudget `protobuf_oneof:"human_labeling_budget"` @@ -454,14 +453,12 @@ type SampleConfig struct { // is used by default. // // Types that are assignable to InitialBatchSampleSize: - // // *SampleConfig_InitialBatchSamplePercentage InitialBatchSampleSize isSampleConfig_InitialBatchSampleSize `protobuf_oneof:"initial_batch_sample_size"` // Decides sample size for the following batches. // following_batch_sample_percentage is used by default. // // Types that are assignable to FollowingBatchSampleSize: - // // *SampleConfig_FollowingBatchSamplePercentage FollowingBatchSampleSize isSampleConfig_FollowingBatchSampleSize `protobuf_oneof:"following_batch_sample_size"` // Field to choose sampling strategy. Sampling strategy will decide which data diff --git a/aiplatform/apiv1/aiplatformpb/dataset.pb.go b/aiplatform/apiv1/aiplatformpb/dataset.pb.go index 8352ccd11ef8..6df323c99402 100644 --- a/aiplatform/apiv1/aiplatformpb/dataset.pb.go +++ b/aiplatform/apiv1/aiplatformpb/dataset.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/dataset.proto package aiplatformpb @@ -79,8 +79,8 @@ type Dataset struct { // System reserved label keys are prefixed with "aiplatform.googleapis.com/" // and are immutable. Following system labels exist for each Dataset: // - // - "aiplatform.googleapis.com/dataset_metadata_schema": output only, its - // value is the [metadata_schema's][google.cloud.aiplatform.v1.Dataset.metadata_schema_uri] title. + // * "aiplatform.googleapis.com/dataset_metadata_schema": output only, its + // value is the [metadata_schema's][google.cloud.aiplatform.v1.Dataset.metadata_schema_uri] title. Labels map[string]string `protobuf:"bytes,7,rep,name=labels,proto3" json:"labels,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` // Customer-managed encryption key spec for a Dataset. If set, this Dataset // and all sub-resources of this Dataset will be secured by this key. @@ -210,7 +210,6 @@ type ImportDataConfig struct { // The source of the input. // // Types that are assignable to Source: - // // *ImportDataConfig_GcsSource Source isImportDataConfig_Source `protobuf_oneof:"source"` // Labels that will be applied to newly imported DataItems. If an identical @@ -328,7 +327,6 @@ type ExportDataConfig struct { // The destination of the output. // // Types that are assignable to Destination: - // // *ExportDataConfig_GcsDestination Destination isExportDataConfig_Destination `protobuf_oneof:"destination"` // A filter on Annotations of the Dataset. Only Annotations on to-be-exported diff --git a/aiplatform/apiv1/aiplatformpb/dataset_service.pb.go b/aiplatform/apiv1/aiplatformpb/dataset_service.pb.go index d38eaef3add3..fa078d74c725 100644 --- a/aiplatform/apiv1/aiplatformpb/dataset_service.pb.go +++ b/aiplatform/apiv1/aiplatformpb/dataset_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/dataset_service.proto package aiplatformpb @@ -220,9 +220,9 @@ type UpdateDatasetRequest struct { // For the `FieldMask` definition, see [google.protobuf.FieldMask][google.protobuf.FieldMask]. // Updatable fields: // - // - `display_name` - // - `description` - // - `labels` + // * `display_name` + // * `description` + // * `labels` UpdateMask *fieldmaskpb.FieldMask `protobuf:"bytes,2,opt,name=update_mask,json=updateMask,proto3" json:"update_mask,omitempty"` } @@ -284,17 +284,17 @@ type ListDatasetsRequest struct { // An expression for filtering the results of the request. For field names // both snake_case and camelCase are supported. // - // - `display_name`: supports = and != - // - `metadata_schema_uri`: supports = and != - // - `labels` supports general map functions that is: - // - `labels.key=value` - key:value equality - // - `labels.key:* or labels:key - key existence - // - A key including a space must be quoted. `labels."a key"`. + // * `display_name`: supports = and != + // * `metadata_schema_uri`: supports = and != + // * `labels` supports general map functions that is: + // * `labels.key=value` - key:value equality + // * `labels.key:* or labels:key - key existence + // * A key including a space must be quoted. `labels."a key"`. // // Some examples: // - // - `displayName="myDisplayName"` - // - `labels.myKey="myValue"` + // * `displayName="myDisplayName"` + // * `labels.myKey="myValue"` Filter string `protobuf:"bytes,2,opt,name=filter,proto3" json:"filter,omitempty"` // The standard list page size. PageSize int32 `protobuf:"varint,3,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"` @@ -306,9 +306,9 @@ type ListDatasetsRequest struct { // Use "desc" after a field name for descending. // Supported fields: // - // - `display_name` - // - `create_time` - // - `update_time` + // * `display_name` + // * `create_time` + // * `update_time` OrderBy string `protobuf:"bytes,6,opt,name=order_by,json=orderBy,proto3" json:"order_by,omitempty"` } @@ -967,6 +967,364 @@ func (x *ListDataItemsResponse) GetNextPageToken() string { return "" } +// Request message for [DatasetService.SearchDataItems][google.cloud.aiplatform.v1.DatasetService.SearchDataItems]. +type SearchDataItemsRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // Types that are assignable to Order: + // *SearchDataItemsRequest_OrderByDataItem + // *SearchDataItemsRequest_OrderByAnnotation_ + Order isSearchDataItemsRequest_Order `protobuf_oneof:"order"` + // Required. The resource name of the Dataset from which to search DataItems. + // Format: + // `projects/{project}/locations/{location}/datasets/{dataset}` + Dataset string `protobuf:"bytes,1,opt,name=dataset,proto3" json:"dataset,omitempty"` + // The resource name of a SavedQuery(annotation set in UI). + // Format: + // `projects/{project}/locations/{location}/datasets/{dataset}/savedQueries/{saved_query}` + // All of the search will be done in the context of this SavedQuery. + // + // Deprecated: Do not use. + SavedQuery string `protobuf:"bytes,2,opt,name=saved_query,json=savedQuery,proto3" json:"saved_query,omitempty"` + // The resource name of a DataLabelingJob. + // Format: + // `projects/{project}/locations/{location}/dataLabelingJobs/{data_labeling_job}` + // If this field is set, all of the search will be done in the context of + // this DataLabelingJob. + DataLabelingJob string `protobuf:"bytes,3,opt,name=data_labeling_job,json=dataLabelingJob,proto3" json:"data_labeling_job,omitempty"` + // An expression for filtering the DataItem that will be returned. + // + // * `data_item_id` - for = or !=. + // * `labeled` - for = or !=. + // * `has_annotation(ANNOTATION_SPEC_ID)` - true only for DataItem that + // have at least one annotation with annotation_spec_id = + // `ANNOTATION_SPEC_ID` in the context of SavedQuery or DataLabelingJob. + // + // For example: + // + // * `data_item=1` + // * `has_annotation(5)` + DataItemFilter string `protobuf:"bytes,4,opt,name=data_item_filter,json=dataItemFilter,proto3" json:"data_item_filter,omitempty"` + // An expression for filtering the Annotations that will be returned per + // DataItem. + // * `annotation_spec_id` - for = or !=. + // + // Deprecated: Do not use. + AnnotationsFilter string `protobuf:"bytes,5,opt,name=annotations_filter,json=annotationsFilter,proto3" json:"annotations_filter,omitempty"` + // An expression that specifies what Annotations will be returned per + // DataItem. Annotations satisfied either of the conditions will be returned. + // * `annotation_spec_id` - for = or !=. + // Must specify `saved_query_id=` - saved query id that annotations should + // belong to. + AnnotationFilters []string `protobuf:"bytes,11,rep,name=annotation_filters,json=annotationFilters,proto3" json:"annotation_filters,omitempty"` + // Mask specifying which fields of [DataItemView][google.cloud.aiplatform.v1.DataItemView] to read. + FieldMask *fieldmaskpb.FieldMask `protobuf:"bytes,6,opt,name=field_mask,json=fieldMask,proto3" json:"field_mask,omitempty"` + // If set, only up to this many of Annotations will be returned per + // DataItemView. The maximum value is 1000. If not set, the maximum value will + // be used. + AnnotationsLimit int32 `protobuf:"varint,7,opt,name=annotations_limit,json=annotationsLimit,proto3" json:"annotations_limit,omitempty"` + // Requested page size. Server may return fewer results than requested. + // Default and maximum page size is 100. + PageSize int32 `protobuf:"varint,8,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"` + // A comma-separated list of fields to order by, sorted in ascending order. + // Use "desc" after a field name for descending. + // + // Deprecated: Do not use. + OrderBy string `protobuf:"bytes,9,opt,name=order_by,json=orderBy,proto3" json:"order_by,omitempty"` + // A token identifying a page of results for the server to return + // Typically obtained via + // [SearchDataItemsResponse.next_page_token][google.cloud.aiplatform.v1.SearchDataItemsResponse.next_page_token] of the previous + // [DatasetService.SearchDataItems][google.cloud.aiplatform.v1.DatasetService.SearchDataItems] call. + PageToken string `protobuf:"bytes,10,opt,name=page_token,json=pageToken,proto3" json:"page_token,omitempty"` +} + +func (x *SearchDataItemsRequest) Reset() { + *x = SearchDataItemsRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_google_cloud_aiplatform_v1_dataset_service_proto_msgTypes[15] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *SearchDataItemsRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SearchDataItemsRequest) ProtoMessage() {} + +func (x *SearchDataItemsRequest) ProtoReflect() protoreflect.Message { + mi := &file_google_cloud_aiplatform_v1_dataset_service_proto_msgTypes[15] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SearchDataItemsRequest.ProtoReflect.Descriptor instead. +func (*SearchDataItemsRequest) Descriptor() ([]byte, []int) { + return file_google_cloud_aiplatform_v1_dataset_service_proto_rawDescGZIP(), []int{15} +} + +func (m *SearchDataItemsRequest) GetOrder() isSearchDataItemsRequest_Order { + if m != nil { + return m.Order + } + return nil +} + +func (x *SearchDataItemsRequest) GetOrderByDataItem() string { + if x, ok := x.GetOrder().(*SearchDataItemsRequest_OrderByDataItem); ok { + return x.OrderByDataItem + } + return "" +} + +func (x *SearchDataItemsRequest) GetOrderByAnnotation() *SearchDataItemsRequest_OrderByAnnotation { + if x, ok := x.GetOrder().(*SearchDataItemsRequest_OrderByAnnotation_); ok { + return x.OrderByAnnotation + } + return nil +} + +func (x *SearchDataItemsRequest) GetDataset() string { + if x != nil { + return x.Dataset + } + return "" +} + +// Deprecated: Do not use. +func (x *SearchDataItemsRequest) GetSavedQuery() string { + if x != nil { + return x.SavedQuery + } + return "" +} + +func (x *SearchDataItemsRequest) GetDataLabelingJob() string { + if x != nil { + return x.DataLabelingJob + } + return "" +} + +func (x *SearchDataItemsRequest) GetDataItemFilter() string { + if x != nil { + return x.DataItemFilter + } + return "" +} + +// Deprecated: Do not use. +func (x *SearchDataItemsRequest) GetAnnotationsFilter() string { + if x != nil { + return x.AnnotationsFilter + } + return "" +} + +func (x *SearchDataItemsRequest) GetAnnotationFilters() []string { + if x != nil { + return x.AnnotationFilters + } + return nil +} + +func (x *SearchDataItemsRequest) GetFieldMask() *fieldmaskpb.FieldMask { + if x != nil { + return x.FieldMask + } + return nil +} + +func (x *SearchDataItemsRequest) GetAnnotationsLimit() int32 { + if x != nil { + return x.AnnotationsLimit + } + return 0 +} + +func (x *SearchDataItemsRequest) GetPageSize() int32 { + if x != nil { + return x.PageSize + } + return 0 +} + +// Deprecated: Do not use. +func (x *SearchDataItemsRequest) GetOrderBy() string { + if x != nil { + return x.OrderBy + } + return "" +} + +func (x *SearchDataItemsRequest) GetPageToken() string { + if x != nil { + return x.PageToken + } + return "" +} + +type isSearchDataItemsRequest_Order interface { + isSearchDataItemsRequest_Order() +} + +type SearchDataItemsRequest_OrderByDataItem struct { + // A comma-separated list of data item fields to order by, sorted in + // ascending order. Use "desc" after a field name for descending. + OrderByDataItem string `protobuf:"bytes,12,opt,name=order_by_data_item,json=orderByDataItem,proto3,oneof"` +} + +type SearchDataItemsRequest_OrderByAnnotation_ struct { + // Expression that allows ranking results based on annotation's property. + OrderByAnnotation *SearchDataItemsRequest_OrderByAnnotation `protobuf:"bytes,13,opt,name=order_by_annotation,json=orderByAnnotation,proto3,oneof"` +} + +func (*SearchDataItemsRequest_OrderByDataItem) isSearchDataItemsRequest_Order() {} + +func (*SearchDataItemsRequest_OrderByAnnotation_) isSearchDataItemsRequest_Order() {} + +// Response message for [DatasetService.SearchDataItems][google.cloud.aiplatform.v1.DatasetService.SearchDataItems]. +type SearchDataItemsResponse struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // The DataItemViews read. + DataItemViews []*DataItemView `protobuf:"bytes,1,rep,name=data_item_views,json=dataItemViews,proto3" json:"data_item_views,omitempty"` + // A token to retrieve next page of results. + // Pass to [SearchDataItemsRequest.page_token][google.cloud.aiplatform.v1.SearchDataItemsRequest.page_token] to obtain that page. + NextPageToken string `protobuf:"bytes,2,opt,name=next_page_token,json=nextPageToken,proto3" json:"next_page_token,omitempty"` +} + +func (x *SearchDataItemsResponse) Reset() { + *x = SearchDataItemsResponse{} + if protoimpl.UnsafeEnabled { + mi := &file_google_cloud_aiplatform_v1_dataset_service_proto_msgTypes[16] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *SearchDataItemsResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SearchDataItemsResponse) ProtoMessage() {} + +func (x *SearchDataItemsResponse) ProtoReflect() protoreflect.Message { + mi := &file_google_cloud_aiplatform_v1_dataset_service_proto_msgTypes[16] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SearchDataItemsResponse.ProtoReflect.Descriptor instead. +func (*SearchDataItemsResponse) Descriptor() ([]byte, []int) { + return file_google_cloud_aiplatform_v1_dataset_service_proto_rawDescGZIP(), []int{16} +} + +func (x *SearchDataItemsResponse) GetDataItemViews() []*DataItemView { + if x != nil { + return x.DataItemViews + } + return nil +} + +func (x *SearchDataItemsResponse) GetNextPageToken() string { + if x != nil { + return x.NextPageToken + } + return "" +} + +// A container for a single DataItem and Annotations on it. +type DataItemView struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // The DataItem. + DataItem *DataItem `protobuf:"bytes,1,opt,name=data_item,json=dataItem,proto3" json:"data_item,omitempty"` + // The Annotations on the DataItem. If too many Annotations should be returned + // for the DataItem, this field will be truncated per annotations_limit in + // request. If it was, then the has_truncated_annotations will be set to true. + Annotations []*Annotation `protobuf:"bytes,2,rep,name=annotations,proto3" json:"annotations,omitempty"` + // True if and only if the Annotations field has been truncated. It happens if + // more Annotations for this DataItem met the request's annotation_filter than + // are allowed to be returned by annotations_limit. + // Note that if Annotations field is not being returned due to field mask, + // then this field will not be set to true no matter how many Annotations are + // there. + HasTruncatedAnnotations bool `protobuf:"varint,3,opt,name=has_truncated_annotations,json=hasTruncatedAnnotations,proto3" json:"has_truncated_annotations,omitempty"` +} + +func (x *DataItemView) Reset() { + *x = DataItemView{} + if protoimpl.UnsafeEnabled { + mi := &file_google_cloud_aiplatform_v1_dataset_service_proto_msgTypes[17] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *DataItemView) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*DataItemView) ProtoMessage() {} + +func (x *DataItemView) ProtoReflect() protoreflect.Message { + mi := &file_google_cloud_aiplatform_v1_dataset_service_proto_msgTypes[17] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use DataItemView.ProtoReflect.Descriptor instead. +func (*DataItemView) Descriptor() ([]byte, []int) { + return file_google_cloud_aiplatform_v1_dataset_service_proto_rawDescGZIP(), []int{17} +} + +func (x *DataItemView) GetDataItem() *DataItem { + if x != nil { + return x.DataItem + } + return nil +} + +func (x *DataItemView) GetAnnotations() []*Annotation { + if x != nil { + return x.Annotations + } + return nil +} + +func (x *DataItemView) GetHasTruncatedAnnotations() bool { + if x != nil { + return x.HasTruncatedAnnotations + } + return false +} + // Request message for [DatasetService.ListSavedQueries][google.cloud.aiplatform.v1.DatasetService.ListSavedQueries]. type ListSavedQueriesRequest struct { state protoimpl.MessageState @@ -993,7 +1351,7 @@ type ListSavedQueriesRequest struct { func (x *ListSavedQueriesRequest) Reset() { *x = ListSavedQueriesRequest{} if protoimpl.UnsafeEnabled { - mi := &file_google_cloud_aiplatform_v1_dataset_service_proto_msgTypes[15] + mi := &file_google_cloud_aiplatform_v1_dataset_service_proto_msgTypes[18] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1006,7 +1364,7 @@ func (x *ListSavedQueriesRequest) String() string { func (*ListSavedQueriesRequest) ProtoMessage() {} func (x *ListSavedQueriesRequest) ProtoReflect() protoreflect.Message { - mi := &file_google_cloud_aiplatform_v1_dataset_service_proto_msgTypes[15] + mi := &file_google_cloud_aiplatform_v1_dataset_service_proto_msgTypes[18] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1019,7 +1377,7 @@ func (x *ListSavedQueriesRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ListSavedQueriesRequest.ProtoReflect.Descriptor instead. func (*ListSavedQueriesRequest) Descriptor() ([]byte, []int) { - return file_google_cloud_aiplatform_v1_dataset_service_proto_rawDescGZIP(), []int{15} + return file_google_cloud_aiplatform_v1_dataset_service_proto_rawDescGZIP(), []int{18} } func (x *ListSavedQueriesRequest) GetParent() string { @@ -1079,7 +1437,7 @@ type ListSavedQueriesResponse struct { func (x *ListSavedQueriesResponse) Reset() { *x = ListSavedQueriesResponse{} if protoimpl.UnsafeEnabled { - mi := &file_google_cloud_aiplatform_v1_dataset_service_proto_msgTypes[16] + mi := &file_google_cloud_aiplatform_v1_dataset_service_proto_msgTypes[19] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1092,7 +1450,7 @@ func (x *ListSavedQueriesResponse) String() string { func (*ListSavedQueriesResponse) ProtoMessage() {} func (x *ListSavedQueriesResponse) ProtoReflect() protoreflect.Message { - mi := &file_google_cloud_aiplatform_v1_dataset_service_proto_msgTypes[16] + mi := &file_google_cloud_aiplatform_v1_dataset_service_proto_msgTypes[19] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1105,7 +1463,7 @@ func (x *ListSavedQueriesResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ListSavedQueriesResponse.ProtoReflect.Descriptor instead. func (*ListSavedQueriesResponse) Descriptor() ([]byte, []int) { - return file_google_cloud_aiplatform_v1_dataset_service_proto_rawDescGZIP(), []int{16} + return file_google_cloud_aiplatform_v1_dataset_service_proto_rawDescGZIP(), []int{19} } func (x *ListSavedQueriesResponse) GetSavedQueries() []*SavedQuery { @@ -1139,7 +1497,7 @@ type GetAnnotationSpecRequest struct { func (x *GetAnnotationSpecRequest) Reset() { *x = GetAnnotationSpecRequest{} if protoimpl.UnsafeEnabled { - mi := &file_google_cloud_aiplatform_v1_dataset_service_proto_msgTypes[17] + mi := &file_google_cloud_aiplatform_v1_dataset_service_proto_msgTypes[20] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1152,7 +1510,7 @@ func (x *GetAnnotationSpecRequest) String() string { func (*GetAnnotationSpecRequest) ProtoMessage() {} func (x *GetAnnotationSpecRequest) ProtoReflect() protoreflect.Message { - mi := &file_google_cloud_aiplatform_v1_dataset_service_proto_msgTypes[17] + mi := &file_google_cloud_aiplatform_v1_dataset_service_proto_msgTypes[20] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1165,7 +1523,7 @@ func (x *GetAnnotationSpecRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use GetAnnotationSpecRequest.ProtoReflect.Descriptor instead. func (*GetAnnotationSpecRequest) Descriptor() ([]byte, []int) { - return file_google_cloud_aiplatform_v1_dataset_service_proto_rawDescGZIP(), []int{17} + return file_google_cloud_aiplatform_v1_dataset_service_proto_rawDescGZIP(), []int{20} } func (x *GetAnnotationSpecRequest) GetName() string { @@ -1208,7 +1566,7 @@ type ListAnnotationsRequest struct { func (x *ListAnnotationsRequest) Reset() { *x = ListAnnotationsRequest{} if protoimpl.UnsafeEnabled { - mi := &file_google_cloud_aiplatform_v1_dataset_service_proto_msgTypes[18] + mi := &file_google_cloud_aiplatform_v1_dataset_service_proto_msgTypes[21] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1221,7 +1579,7 @@ func (x *ListAnnotationsRequest) String() string { func (*ListAnnotationsRequest) ProtoMessage() {} func (x *ListAnnotationsRequest) ProtoReflect() protoreflect.Message { - mi := &file_google_cloud_aiplatform_v1_dataset_service_proto_msgTypes[18] + mi := &file_google_cloud_aiplatform_v1_dataset_service_proto_msgTypes[21] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1234,7 +1592,7 @@ func (x *ListAnnotationsRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ListAnnotationsRequest.ProtoReflect.Descriptor instead. func (*ListAnnotationsRequest) Descriptor() ([]byte, []int) { - return file_google_cloud_aiplatform_v1_dataset_service_proto_rawDescGZIP(), []int{18} + return file_google_cloud_aiplatform_v1_dataset_service_proto_rawDescGZIP(), []int{21} } func (x *ListAnnotationsRequest) GetParent() string { @@ -1294,7 +1652,7 @@ type ListAnnotationsResponse struct { func (x *ListAnnotationsResponse) Reset() { *x = ListAnnotationsResponse{} if protoimpl.UnsafeEnabled { - mi := &file_google_cloud_aiplatform_v1_dataset_service_proto_msgTypes[19] + mi := &file_google_cloud_aiplatform_v1_dataset_service_proto_msgTypes[22] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1307,7 +1665,7 @@ func (x *ListAnnotationsResponse) String() string { func (*ListAnnotationsResponse) ProtoMessage() {} func (x *ListAnnotationsResponse) ProtoReflect() protoreflect.Message { - mi := &file_google_cloud_aiplatform_v1_dataset_service_proto_msgTypes[19] + mi := &file_google_cloud_aiplatform_v1_dataset_service_proto_msgTypes[22] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1320,7 +1678,7 @@ func (x *ListAnnotationsResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ListAnnotationsResponse.ProtoReflect.Descriptor instead. func (*ListAnnotationsResponse) Descriptor() ([]byte, []int) { - return file_google_cloud_aiplatform_v1_dataset_service_proto_rawDescGZIP(), []int{19} + return file_google_cloud_aiplatform_v1_dataset_service_proto_rawDescGZIP(), []int{22} } func (x *ListAnnotationsResponse) GetAnnotations() []*Annotation { @@ -1337,6 +1695,67 @@ func (x *ListAnnotationsResponse) GetNextPageToken() string { return "" } +// Expression that allows ranking results based on annotation's property. +type SearchDataItemsRequest_OrderByAnnotation struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // Required. Saved query of the Annotation. Only Annotations belong to this saved + // query will be considered for ordering. + SavedQuery string `protobuf:"bytes,1,opt,name=saved_query,json=savedQuery,proto3" json:"saved_query,omitempty"` + // A comma-separated list of annotation fields to order by, sorted in + // ascending order. Use "desc" after a field name for descending. Must also + // specify saved_query. + OrderBy string `protobuf:"bytes,2,opt,name=order_by,json=orderBy,proto3" json:"order_by,omitempty"` +} + +func (x *SearchDataItemsRequest_OrderByAnnotation) Reset() { + *x = SearchDataItemsRequest_OrderByAnnotation{} + if protoimpl.UnsafeEnabled { + mi := &file_google_cloud_aiplatform_v1_dataset_service_proto_msgTypes[23] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *SearchDataItemsRequest_OrderByAnnotation) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SearchDataItemsRequest_OrderByAnnotation) ProtoMessage() {} + +func (x *SearchDataItemsRequest_OrderByAnnotation) ProtoReflect() protoreflect.Message { + mi := &file_google_cloud_aiplatform_v1_dataset_service_proto_msgTypes[23] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SearchDataItemsRequest_OrderByAnnotation.ProtoReflect.Descriptor instead. +func (*SearchDataItemsRequest_OrderByAnnotation) Descriptor() ([]byte, []int) { + return file_google_cloud_aiplatform_v1_dataset_service_proto_rawDescGZIP(), []int{15, 0} +} + +func (x *SearchDataItemsRequest_OrderByAnnotation) GetSavedQuery() string { + if x != nil { + return x.SavedQuery + } + return "" +} + +func (x *SearchDataItemsRequest_OrderByAnnotation) GetOrderBy() string { + if x != nil { + return x.OrderBy + } + return "" +} + var File_google_cloud_aiplatform_v1_dataset_service_proto protoreflect.FileDescriptor var file_google_cloud_aiplatform_v1_dataset_service_proto_rawDesc = []byte{ @@ -1511,228 +1930,314 @@ var file_google_cloud_aiplatform_v1_dataset_service_proto_rawDesc = []byte{ 0x61, 0x74, 0x61, 0x49, 0x74, 0x65, 0x6d, 0x73, 0x12, 0x26, 0x0a, 0x0f, 0x6e, 0x65, 0x78, 0x74, 0x5f, 0x70, 0x61, 0x67, 0x65, 0x5f, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0d, 0x6e, 0x65, 0x78, 0x74, 0x50, 0x61, 0x67, 0x65, 0x54, 0x6f, 0x6b, 0x65, 0x6e, - 0x22, 0x84, 0x02, 0x0a, 0x17, 0x4c, 0x69, 0x73, 0x74, 0x53, 0x61, 0x76, 0x65, 0x64, 0x51, 0x75, - 0x65, 0x72, 0x69, 0x65, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x41, 0x0a, 0x06, - 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x42, 0x29, 0xe0, 0x41, - 0x02, 0xfa, 0x41, 0x23, 0x0a, 0x21, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, - 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, - 0x44, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x52, 0x06, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x12, - 0x16, 0x0a, 0x06, 0x66, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, - 0x06, 0x66, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x12, 0x1b, 0x0a, 0x09, 0x70, 0x61, 0x67, 0x65, 0x5f, - 0x73, 0x69, 0x7a, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x05, 0x52, 0x08, 0x70, 0x61, 0x67, 0x65, - 0x53, 0x69, 0x7a, 0x65, 0x12, 0x1d, 0x0a, 0x0a, 0x70, 0x61, 0x67, 0x65, 0x5f, 0x74, 0x6f, 0x6b, - 0x65, 0x6e, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x70, 0x61, 0x67, 0x65, 0x54, 0x6f, - 0x6b, 0x65, 0x6e, 0x12, 0x37, 0x0a, 0x09, 0x72, 0x65, 0x61, 0x64, 0x5f, 0x6d, 0x61, 0x73, 0x6b, - 0x18, 0x05, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x4d, 0x61, - 0x73, 0x6b, 0x52, 0x08, 0x72, 0x65, 0x61, 0x64, 0x4d, 0x61, 0x73, 0x6b, 0x12, 0x19, 0x0a, 0x08, - 0x6f, 0x72, 0x64, 0x65, 0x72, 0x5f, 0x62, 0x79, 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, - 0x6f, 0x72, 0x64, 0x65, 0x72, 0x42, 0x79, 0x22, 0x8f, 0x01, 0x0a, 0x18, 0x4c, 0x69, 0x73, 0x74, - 0x53, 0x61, 0x76, 0x65, 0x64, 0x51, 0x75, 0x65, 0x72, 0x69, 0x65, 0x73, 0x52, 0x65, 0x73, 0x70, - 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x4b, 0x0a, 0x0d, 0x73, 0x61, 0x76, 0x65, 0x64, 0x5f, 0x71, 0x75, - 0x65, 0x72, 0x69, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x26, 0x2e, 0x67, 0x6f, - 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, 0x61, - 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x61, 0x76, 0x65, 0x64, 0x51, 0x75, - 0x65, 0x72, 0x79, 0x52, 0x0c, 0x73, 0x61, 0x76, 0x65, 0x64, 0x51, 0x75, 0x65, 0x72, 0x69, 0x65, + 0x22, 0xac, 0x06, 0x0a, 0x16, 0x53, 0x65, 0x61, 0x72, 0x63, 0x68, 0x44, 0x61, 0x74, 0x61, 0x49, + 0x74, 0x65, 0x6d, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x2d, 0x0a, 0x12, 0x6f, + 0x72, 0x64, 0x65, 0x72, 0x5f, 0x62, 0x79, 0x5f, 0x64, 0x61, 0x74, 0x61, 0x5f, 0x69, 0x74, 0x65, + 0x6d, 0x18, 0x0c, 0x20, 0x01, 0x28, 0x09, 0x48, 0x00, 0x52, 0x0f, 0x6f, 0x72, 0x64, 0x65, 0x72, + 0x42, 0x79, 0x44, 0x61, 0x74, 0x61, 0x49, 0x74, 0x65, 0x6d, 0x12, 0x76, 0x0a, 0x13, 0x6f, 0x72, + 0x64, 0x65, 0x72, 0x5f, 0x62, 0x79, 0x5f, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, + 0x6e, 0x18, 0x0d, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x44, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, + 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, + 0x6d, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x65, 0x61, 0x72, 0x63, 0x68, 0x44, 0x61, 0x74, 0x61, 0x49, + 0x74, 0x65, 0x6d, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x2e, 0x4f, 0x72, 0x64, 0x65, + 0x72, 0x42, 0x79, 0x41, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x48, 0x00, 0x52, + 0x11, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x42, 0x79, 0x41, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, + 0x6f, 0x6e, 0x12, 0x43, 0x0a, 0x07, 0x64, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x18, 0x01, 0x20, + 0x01, 0x28, 0x09, 0x42, 0x29, 0xe0, 0x41, 0x02, 0xfa, 0x41, 0x23, 0x0a, 0x21, 0x61, 0x69, 0x70, + 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, + 0x69, 0x73, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x44, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x52, 0x07, + 0x64, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x12, 0x4c, 0x0a, 0x0b, 0x73, 0x61, 0x76, 0x65, 0x64, + 0x5f, 0x71, 0x75, 0x65, 0x72, 0x79, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x42, 0x2b, 0x18, 0x01, + 0xfa, 0x41, 0x26, 0x0a, 0x24, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, + 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x53, + 0x61, 0x76, 0x65, 0x64, 0x51, 0x75, 0x65, 0x72, 0x79, 0x52, 0x0a, 0x73, 0x61, 0x76, 0x65, 0x64, + 0x51, 0x75, 0x65, 0x72, 0x79, 0x12, 0x2a, 0x0a, 0x11, 0x64, 0x61, 0x74, 0x61, 0x5f, 0x6c, 0x61, + 0x62, 0x65, 0x6c, 0x69, 0x6e, 0x67, 0x5f, 0x6a, 0x6f, 0x62, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, + 0x52, 0x0f, 0x64, 0x61, 0x74, 0x61, 0x4c, 0x61, 0x62, 0x65, 0x6c, 0x69, 0x6e, 0x67, 0x4a, 0x6f, + 0x62, 0x12, 0x28, 0x0a, 0x10, 0x64, 0x61, 0x74, 0x61, 0x5f, 0x69, 0x74, 0x65, 0x6d, 0x5f, 0x66, + 0x69, 0x6c, 0x74, 0x65, 0x72, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0e, 0x64, 0x61, 0x74, + 0x61, 0x49, 0x74, 0x65, 0x6d, 0x46, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x12, 0x31, 0x0a, 0x12, 0x61, + 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x5f, 0x66, 0x69, 0x6c, 0x74, 0x65, + 0x72, 0x18, 0x05, 0x20, 0x01, 0x28, 0x09, 0x42, 0x02, 0x18, 0x01, 0x52, 0x11, 0x61, 0x6e, 0x6e, + 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x46, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x12, 0x2d, + 0x0a, 0x12, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x66, 0x69, 0x6c, + 0x74, 0x65, 0x72, 0x73, 0x18, 0x0b, 0x20, 0x03, 0x28, 0x09, 0x52, 0x11, 0x61, 0x6e, 0x6e, 0x6f, + 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x46, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x73, 0x12, 0x39, 0x0a, + 0x0a, 0x66, 0x69, 0x65, 0x6c, 0x64, 0x5f, 0x6d, 0x61, 0x73, 0x6b, 0x18, 0x06, 0x20, 0x01, 0x28, + 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, + 0x62, 0x75, 0x66, 0x2e, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x4d, 0x61, 0x73, 0x6b, 0x52, 0x09, 0x66, + 0x69, 0x65, 0x6c, 0x64, 0x4d, 0x61, 0x73, 0x6b, 0x12, 0x2b, 0x0a, 0x11, 0x61, 0x6e, 0x6e, 0x6f, + 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x5f, 0x6c, 0x69, 0x6d, 0x69, 0x74, 0x18, 0x07, 0x20, + 0x01, 0x28, 0x05, 0x52, 0x10, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, + 0x4c, 0x69, 0x6d, 0x69, 0x74, 0x12, 0x1b, 0x0a, 0x09, 0x70, 0x61, 0x67, 0x65, 0x5f, 0x73, 0x69, + 0x7a, 0x65, 0x18, 0x08, 0x20, 0x01, 0x28, 0x05, 0x52, 0x08, 0x70, 0x61, 0x67, 0x65, 0x53, 0x69, + 0x7a, 0x65, 0x12, 0x1d, 0x0a, 0x08, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x5f, 0x62, 0x79, 0x18, 0x09, + 0x20, 0x01, 0x28, 0x09, 0x42, 0x02, 0x18, 0x01, 0x52, 0x07, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x42, + 0x79, 0x12, 0x1d, 0x0a, 0x0a, 0x70, 0x61, 0x67, 0x65, 0x5f, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x18, + 0x0a, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x70, 0x61, 0x67, 0x65, 0x54, 0x6f, 0x6b, 0x65, 0x6e, + 0x1a, 0x54, 0x0a, 0x11, 0x4f, 0x72, 0x64, 0x65, 0x72, 0x42, 0x79, 0x41, 0x6e, 0x6e, 0x6f, 0x74, + 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x24, 0x0a, 0x0b, 0x73, 0x61, 0x76, 0x65, 0x64, 0x5f, 0x71, + 0x75, 0x65, 0x72, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x42, 0x03, 0xe0, 0x41, 0x02, 0x52, + 0x0a, 0x73, 0x61, 0x76, 0x65, 0x64, 0x51, 0x75, 0x65, 0x72, 0x79, 0x12, 0x19, 0x0a, 0x08, 0x6f, + 0x72, 0x64, 0x65, 0x72, 0x5f, 0x62, 0x79, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x6f, + 0x72, 0x64, 0x65, 0x72, 0x42, 0x79, 0x42, 0x07, 0x0a, 0x05, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x22, + 0x93, 0x01, 0x0a, 0x17, 0x53, 0x65, 0x61, 0x72, 0x63, 0x68, 0x44, 0x61, 0x74, 0x61, 0x49, 0x74, + 0x65, 0x6d, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x50, 0x0a, 0x0f, 0x64, + 0x61, 0x74, 0x61, 0x5f, 0x69, 0x74, 0x65, 0x6d, 0x5f, 0x76, 0x69, 0x65, 0x77, 0x73, 0x18, 0x01, + 0x20, 0x03, 0x28, 0x0b, 0x32, 0x28, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, + 0x6f, 0x75, 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, + 0x31, 0x2e, 0x44, 0x61, 0x74, 0x61, 0x49, 0x74, 0x65, 0x6d, 0x56, 0x69, 0x65, 0x77, 0x52, 0x0d, + 0x64, 0x61, 0x74, 0x61, 0x49, 0x74, 0x65, 0x6d, 0x56, 0x69, 0x65, 0x77, 0x73, 0x12, 0x26, 0x0a, + 0x0f, 0x6e, 0x65, 0x78, 0x74, 0x5f, 0x70, 0x61, 0x67, 0x65, 0x5f, 0x74, 0x6f, 0x6b, 0x65, 0x6e, + 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0d, 0x6e, 0x65, 0x78, 0x74, 0x50, 0x61, 0x67, 0x65, + 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x22, 0xd7, 0x01, 0x0a, 0x0c, 0x44, 0x61, 0x74, 0x61, 0x49, 0x74, + 0x65, 0x6d, 0x56, 0x69, 0x65, 0x77, 0x12, 0x41, 0x0a, 0x09, 0x64, 0x61, 0x74, 0x61, 0x5f, 0x69, + 0x74, 0x65, 0x6d, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x24, 0x2e, 0x67, 0x6f, 0x6f, 0x67, + 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, + 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x2e, 0x44, 0x61, 0x74, 0x61, 0x49, 0x74, 0x65, 0x6d, 0x52, + 0x08, 0x64, 0x61, 0x74, 0x61, 0x49, 0x74, 0x65, 0x6d, 0x12, 0x48, 0x0a, 0x0b, 0x61, 0x6e, 0x6e, + 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x26, + 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, 0x69, + 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x2e, 0x41, 0x6e, 0x6e, 0x6f, + 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0b, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, + 0x6f, 0x6e, 0x73, 0x12, 0x3a, 0x0a, 0x19, 0x68, 0x61, 0x73, 0x5f, 0x74, 0x72, 0x75, 0x6e, 0x63, + 0x61, 0x74, 0x65, 0x64, 0x5f, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, + 0x18, 0x03, 0x20, 0x01, 0x28, 0x08, 0x52, 0x17, 0x68, 0x61, 0x73, 0x54, 0x72, 0x75, 0x6e, 0x63, + 0x61, 0x74, 0x65, 0x64, 0x41, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x22, + 0x84, 0x02, 0x0a, 0x17, 0x4c, 0x69, 0x73, 0x74, 0x53, 0x61, 0x76, 0x65, 0x64, 0x51, 0x75, 0x65, + 0x72, 0x69, 0x65, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x41, 0x0a, 0x06, 0x70, + 0x61, 0x72, 0x65, 0x6e, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x42, 0x29, 0xe0, 0x41, 0x02, + 0xfa, 0x41, 0x23, 0x0a, 0x21, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, + 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x44, + 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x52, 0x06, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x12, 0x16, + 0x0a, 0x06, 0x66, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, + 0x66, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x12, 0x1b, 0x0a, 0x09, 0x70, 0x61, 0x67, 0x65, 0x5f, 0x73, + 0x69, 0x7a, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x05, 0x52, 0x08, 0x70, 0x61, 0x67, 0x65, 0x53, + 0x69, 0x7a, 0x65, 0x12, 0x1d, 0x0a, 0x0a, 0x70, 0x61, 0x67, 0x65, 0x5f, 0x74, 0x6f, 0x6b, 0x65, + 0x6e, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x70, 0x61, 0x67, 0x65, 0x54, 0x6f, 0x6b, + 0x65, 0x6e, 0x12, 0x37, 0x0a, 0x09, 0x72, 0x65, 0x61, 0x64, 0x5f, 0x6d, 0x61, 0x73, 0x6b, 0x18, + 0x05, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, + 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x4d, 0x61, 0x73, + 0x6b, 0x52, 0x08, 0x72, 0x65, 0x61, 0x64, 0x4d, 0x61, 0x73, 0x6b, 0x12, 0x19, 0x0a, 0x08, 0x6f, + 0x72, 0x64, 0x65, 0x72, 0x5f, 0x62, 0x79, 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x6f, + 0x72, 0x64, 0x65, 0x72, 0x42, 0x79, 0x22, 0x8f, 0x01, 0x0a, 0x18, 0x4c, 0x69, 0x73, 0x74, 0x53, + 0x61, 0x76, 0x65, 0x64, 0x51, 0x75, 0x65, 0x72, 0x69, 0x65, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, + 0x6e, 0x73, 0x65, 0x12, 0x4b, 0x0a, 0x0d, 0x73, 0x61, 0x76, 0x65, 0x64, 0x5f, 0x71, 0x75, 0x65, + 0x72, 0x69, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x26, 0x2e, 0x67, 0x6f, 0x6f, + 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, + 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x61, 0x76, 0x65, 0x64, 0x51, 0x75, 0x65, + 0x72, 0x79, 0x52, 0x0c, 0x73, 0x61, 0x76, 0x65, 0x64, 0x51, 0x75, 0x65, 0x72, 0x69, 0x65, 0x73, + 0x12, 0x26, 0x0a, 0x0f, 0x6e, 0x65, 0x78, 0x74, 0x5f, 0x70, 0x61, 0x67, 0x65, 0x5f, 0x74, 0x6f, + 0x6b, 0x65, 0x6e, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0d, 0x6e, 0x65, 0x78, 0x74, 0x50, + 0x61, 0x67, 0x65, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x22, 0x99, 0x01, 0x0a, 0x18, 0x47, 0x65, 0x74, + 0x41, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x53, 0x70, 0x65, 0x63, 0x52, 0x65, + 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x44, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, + 0x01, 0x28, 0x09, 0x42, 0x30, 0xe0, 0x41, 0x02, 0xfa, 0x41, 0x2a, 0x0a, 0x28, 0x61, 0x69, 0x70, + 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, + 0x69, 0x73, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x41, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, + 0x6e, 0x53, 0x70, 0x65, 0x63, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x37, 0x0a, 0x09, 0x72, + 0x65, 0x61, 0x64, 0x5f, 0x6d, 0x61, 0x73, 0x6b, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, + 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, + 0x2e, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x4d, 0x61, 0x73, 0x6b, 0x52, 0x08, 0x72, 0x65, 0x61, 0x64, + 0x4d, 0x61, 0x73, 0x6b, 0x22, 0x84, 0x02, 0x0a, 0x16, 0x4c, 0x69, 0x73, 0x74, 0x41, 0x6e, 0x6e, + 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, + 0x42, 0x0a, 0x06, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x42, + 0x2a, 0xe0, 0x41, 0x02, 0xfa, 0x41, 0x24, 0x0a, 0x22, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, + 0x6f, 0x72, 0x6d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2e, 0x63, + 0x6f, 0x6d, 0x2f, 0x44, 0x61, 0x74, 0x61, 0x49, 0x74, 0x65, 0x6d, 0x52, 0x06, 0x70, 0x61, 0x72, + 0x65, 0x6e, 0x74, 0x12, 0x16, 0x0a, 0x06, 0x66, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x18, 0x02, 0x20, + 0x01, 0x28, 0x09, 0x52, 0x06, 0x66, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x12, 0x1b, 0x0a, 0x09, 0x70, + 0x61, 0x67, 0x65, 0x5f, 0x73, 0x69, 0x7a, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x05, 0x52, 0x08, + 0x70, 0x61, 0x67, 0x65, 0x53, 0x69, 0x7a, 0x65, 0x12, 0x1d, 0x0a, 0x0a, 0x70, 0x61, 0x67, 0x65, + 0x5f, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x70, 0x61, + 0x67, 0x65, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x12, 0x37, 0x0a, 0x09, 0x72, 0x65, 0x61, 0x64, 0x5f, + 0x6d, 0x61, 0x73, 0x6b, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, + 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x46, 0x69, 0x65, + 0x6c, 0x64, 0x4d, 0x61, 0x73, 0x6b, 0x52, 0x08, 0x72, 0x65, 0x61, 0x64, 0x4d, 0x61, 0x73, 0x6b, + 0x12, 0x19, 0x0a, 0x08, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x5f, 0x62, 0x79, 0x18, 0x06, 0x20, 0x01, + 0x28, 0x09, 0x52, 0x07, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x42, 0x79, 0x22, 0x8b, 0x01, 0x0a, 0x17, + 0x4c, 0x69, 0x73, 0x74, 0x41, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x52, + 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x48, 0x0a, 0x0b, 0x61, 0x6e, 0x6e, 0x6f, 0x74, + 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x26, 0x2e, 0x67, + 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, + 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x2e, 0x41, 0x6e, 0x6e, 0x6f, 0x74, 0x61, + 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0b, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x26, 0x0a, 0x0f, 0x6e, 0x65, 0x78, 0x74, 0x5f, 0x70, 0x61, 0x67, 0x65, 0x5f, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0d, 0x6e, 0x65, 0x78, 0x74, - 0x50, 0x61, 0x67, 0x65, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x22, 0x99, 0x01, 0x0a, 0x18, 0x47, 0x65, - 0x74, 0x41, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x53, 0x70, 0x65, 0x63, 0x52, - 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x44, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, - 0x20, 0x01, 0x28, 0x09, 0x42, 0x30, 0xe0, 0x41, 0x02, 0xfa, 0x41, 0x2a, 0x0a, 0x28, 0x61, 0x69, - 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, - 0x70, 0x69, 0x73, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x41, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, - 0x6f, 0x6e, 0x53, 0x70, 0x65, 0x63, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x37, 0x0a, 0x09, - 0x72, 0x65, 0x61, 0x64, 0x5f, 0x6d, 0x61, 0x73, 0x6b, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, - 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, - 0x66, 0x2e, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x4d, 0x61, 0x73, 0x6b, 0x52, 0x08, 0x72, 0x65, 0x61, - 0x64, 0x4d, 0x61, 0x73, 0x6b, 0x22, 0x84, 0x02, 0x0a, 0x16, 0x4c, 0x69, 0x73, 0x74, 0x41, 0x6e, - 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, - 0x12, 0x42, 0x0a, 0x06, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, - 0x42, 0x2a, 0xe0, 0x41, 0x02, 0xfa, 0x41, 0x24, 0x0a, 0x22, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, - 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2e, - 0x63, 0x6f, 0x6d, 0x2f, 0x44, 0x61, 0x74, 0x61, 0x49, 0x74, 0x65, 0x6d, 0x52, 0x06, 0x70, 0x61, - 0x72, 0x65, 0x6e, 0x74, 0x12, 0x16, 0x0a, 0x06, 0x66, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x18, 0x02, - 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x66, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x12, 0x1b, 0x0a, 0x09, - 0x70, 0x61, 0x67, 0x65, 0x5f, 0x73, 0x69, 0x7a, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x05, 0x52, - 0x08, 0x70, 0x61, 0x67, 0x65, 0x53, 0x69, 0x7a, 0x65, 0x12, 0x1d, 0x0a, 0x0a, 0x70, 0x61, 0x67, - 0x65, 0x5f, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x70, - 0x61, 0x67, 0x65, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x12, 0x37, 0x0a, 0x09, 0x72, 0x65, 0x61, 0x64, - 0x5f, 0x6d, 0x61, 0x73, 0x6b, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, - 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x46, 0x69, - 0x65, 0x6c, 0x64, 0x4d, 0x61, 0x73, 0x6b, 0x52, 0x08, 0x72, 0x65, 0x61, 0x64, 0x4d, 0x61, 0x73, - 0x6b, 0x12, 0x19, 0x0a, 0x08, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x5f, 0x62, 0x79, 0x18, 0x06, 0x20, - 0x01, 0x28, 0x09, 0x52, 0x07, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x42, 0x79, 0x22, 0x8b, 0x01, 0x0a, - 0x17, 0x4c, 0x69, 0x73, 0x74, 0x41, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, - 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x48, 0x0a, 0x0b, 0x61, 0x6e, 0x6e, 0x6f, - 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x26, 0x2e, - 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, 0x69, 0x70, - 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x2e, 0x41, 0x6e, 0x6e, 0x6f, 0x74, - 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0b, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, - 0x6e, 0x73, 0x12, 0x26, 0x0a, 0x0f, 0x6e, 0x65, 0x78, 0x74, 0x5f, 0x70, 0x61, 0x67, 0x65, 0x5f, - 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0d, 0x6e, 0x65, 0x78, - 0x74, 0x50, 0x61, 0x67, 0x65, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x32, 0xa6, 0x12, 0x0a, 0x0e, 0x44, - 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0xdc, 0x01, - 0x0a, 0x0d, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x44, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x12, - 0x30, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, - 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x2e, 0x43, 0x72, 0x65, - 0x61, 0x74, 0x65, 0x44, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, - 0x74, 0x1a, 0x1d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x6c, 0x6f, 0x6e, 0x67, 0x72, - 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x2e, 0x4f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, - 0x22, 0x7a, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x37, 0x22, 0x2c, 0x2f, 0x76, 0x31, 0x2f, 0x7b, 0x70, - 0x61, 0x72, 0x65, 0x6e, 0x74, 0x3d, 0x70, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x2f, 0x2a, - 0x2f, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x2a, 0x7d, 0x2f, 0x64, 0x61, - 0x74, 0x61, 0x73, 0x65, 0x74, 0x73, 0x3a, 0x07, 0x64, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0xda, - 0x41, 0x0e, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x2c, 0x64, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, - 0xca, 0x41, 0x29, 0x0a, 0x07, 0x44, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x12, 0x1e, 0x43, 0x72, - 0x65, 0x61, 0x74, 0x65, 0x44, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x4f, 0x70, 0x65, 0x72, 0x61, - 0x74, 0x69, 0x6f, 0x6e, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x12, 0x9d, 0x01, 0x0a, - 0x0a, 0x47, 0x65, 0x74, 0x44, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x12, 0x2d, 0x2e, 0x67, 0x6f, - 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, 0x61, - 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x2e, 0x47, 0x65, 0x74, 0x44, 0x61, 0x74, 0x61, - 0x73, 0x65, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x23, 0x2e, 0x67, 0x6f, 0x6f, - 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, - 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x2e, 0x44, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x22, - 0x3b, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x2e, 0x12, 0x2c, 0x2f, 0x76, 0x31, 0x2f, 0x7b, 0x6e, 0x61, - 0x6d, 0x65, 0x3d, 0x70, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x2f, 0x2a, 0x2f, 0x6c, 0x6f, - 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x2a, 0x2f, 0x64, 0x61, 0x74, 0x61, 0x73, 0x65, - 0x74, 0x73, 0x2f, 0x2a, 0x7d, 0xda, 0x41, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0xc3, 0x01, 0x0a, - 0x0d, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x44, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x12, 0x30, + 0x50, 0x61, 0x67, 0x65, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x32, 0xec, 0x13, 0x0a, 0x0e, 0x44, 0x61, + 0x74, 0x61, 0x73, 0x65, 0x74, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0xdc, 0x01, 0x0a, + 0x0d, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x44, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x12, 0x30, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, 0x69, - 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x2e, 0x55, 0x70, 0x64, 0x61, + 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x2e, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x44, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, - 0x1a, 0x23, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, - 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x2e, 0x44, 0x61, - 0x74, 0x61, 0x73, 0x65, 0x74, 0x22, 0x5b, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x3f, 0x32, 0x34, 0x2f, - 0x76, 0x31, 0x2f, 0x7b, 0x64, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x2e, 0x6e, 0x61, 0x6d, 0x65, - 0x3d, 0x70, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x2f, 0x2a, 0x2f, 0x6c, 0x6f, 0x63, 0x61, - 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x2a, 0x2f, 0x64, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x73, - 0x2f, 0x2a, 0x7d, 0x3a, 0x07, 0x64, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0xda, 0x41, 0x13, 0x64, - 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x2c, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x5f, 0x6d, 0x61, - 0x73, 0x6b, 0x12, 0xb0, 0x01, 0x0a, 0x0c, 0x4c, 0x69, 0x73, 0x74, 0x44, 0x61, 0x74, 0x61, 0x73, - 0x65, 0x74, 0x73, 0x12, 0x2f, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, - 0x75, 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, - 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x44, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x73, 0x52, 0x65, 0x71, - 0x75, 0x65, 0x73, 0x74, 0x1a, 0x30, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, - 0x6f, 0x75, 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, - 0x31, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x44, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x73, 0x52, 0x65, - 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x3d, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x2e, 0x12, 0x2c, - 0x2f, 0x76, 0x31, 0x2f, 0x7b, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x3d, 0x70, 0x72, 0x6f, 0x6a, - 0x65, 0x63, 0x74, 0x73, 0x2f, 0x2a, 0x2f, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, - 0x2f, 0x2a, 0x7d, 0x2f, 0x64, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x73, 0xda, 0x41, 0x06, 0x70, - 0x61, 0x72, 0x65, 0x6e, 0x74, 0x12, 0xd0, 0x01, 0x0a, 0x0d, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, - 0x44, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x12, 0x30, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, - 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, - 0x6d, 0x2e, 0x76, 0x31, 0x2e, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x44, 0x61, 0x74, 0x61, 0x73, - 0x65, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x1d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, - 0x6c, 0x65, 0x2e, 0x6c, 0x6f, 0x6e, 0x67, 0x72, 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x2e, 0x4f, - 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x22, 0x6e, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x2e, - 0x2a, 0x2c, 0x2f, 0x76, 0x31, 0x2f, 0x7b, 0x6e, 0x61, 0x6d, 0x65, 0x3d, 0x70, 0x72, 0x6f, 0x6a, - 0x65, 0x63, 0x74, 0x73, 0x2f, 0x2a, 0x2f, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, - 0x2f, 0x2a, 0x2f, 0x64, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x73, 0x2f, 0x2a, 0x7d, 0xda, 0x41, - 0x04, 0x6e, 0x61, 0x6d, 0x65, 0xca, 0x41, 0x30, 0x0a, 0x15, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, - 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, - 0x17, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x4f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, - 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x12, 0xe5, 0x01, 0x0a, 0x0a, 0x49, 0x6d, 0x70, - 0x6f, 0x72, 0x74, 0x44, 0x61, 0x74, 0x61, 0x12, 0x2d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, - 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, - 0x6d, 0x2e, 0x76, 0x31, 0x2e, 0x49, 0x6d, 0x70, 0x6f, 0x72, 0x74, 0x44, 0x61, 0x74, 0x61, 0x52, - 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x1d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, - 0x6c, 0x6f, 0x6e, 0x67, 0x72, 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x2e, 0x4f, 0x70, 0x65, 0x72, - 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x22, 0x88, 0x01, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x38, 0x22, 0x33, - 0x2f, 0x76, 0x31, 0x2f, 0x7b, 0x6e, 0x61, 0x6d, 0x65, 0x3d, 0x70, 0x72, 0x6f, 0x6a, 0x65, 0x63, - 0x74, 0x73, 0x2f, 0x2a, 0x2f, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x2a, - 0x2f, 0x64, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x73, 0x2f, 0x2a, 0x7d, 0x3a, 0x69, 0x6d, 0x70, - 0x6f, 0x72, 0x74, 0x3a, 0x01, 0x2a, 0xda, 0x41, 0x13, 0x6e, 0x61, 0x6d, 0x65, 0x2c, 0x69, 0x6d, - 0x70, 0x6f, 0x72, 0x74, 0x5f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x73, 0xca, 0x41, 0x31, 0x0a, - 0x12, 0x49, 0x6d, 0x70, 0x6f, 0x72, 0x74, 0x44, 0x61, 0x74, 0x61, 0x52, 0x65, 0x73, 0x70, 0x6f, - 0x6e, 0x73, 0x65, 0x12, 0x1b, 0x49, 0x6d, 0x70, 0x6f, 0x72, 0x74, 0x44, 0x61, 0x74, 0x61, 0x4f, - 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, - 0x12, 0xe4, 0x01, 0x0a, 0x0a, 0x45, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x44, 0x61, 0x74, 0x61, 0x12, - 0x2d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, - 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x2e, 0x45, 0x78, 0x70, - 0x6f, 0x72, 0x74, 0x44, 0x61, 0x74, 0x61, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x1d, - 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x6c, 0x6f, 0x6e, 0x67, 0x72, 0x75, 0x6e, 0x6e, - 0x69, 0x6e, 0x67, 0x2e, 0x4f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x22, 0x87, 0x01, - 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x38, 0x22, 0x33, 0x2f, 0x76, 0x31, 0x2f, 0x7b, 0x6e, 0x61, 0x6d, + 0x1a, 0x1d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x6c, 0x6f, 0x6e, 0x67, 0x72, 0x75, + 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x2e, 0x4f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x22, + 0x7a, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x37, 0x22, 0x2c, 0x2f, 0x76, 0x31, 0x2f, 0x7b, 0x70, 0x61, + 0x72, 0x65, 0x6e, 0x74, 0x3d, 0x70, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x2f, 0x2a, 0x2f, + 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x2a, 0x7d, 0x2f, 0x64, 0x61, 0x74, + 0x61, 0x73, 0x65, 0x74, 0x73, 0x3a, 0x07, 0x64, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0xda, 0x41, + 0x0e, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x2c, 0x64, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0xca, + 0x41, 0x29, 0x0a, 0x07, 0x44, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x12, 0x1e, 0x43, 0x72, 0x65, + 0x61, 0x74, 0x65, 0x44, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x4f, 0x70, 0x65, 0x72, 0x61, 0x74, + 0x69, 0x6f, 0x6e, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x12, 0x9d, 0x01, 0x0a, 0x0a, + 0x47, 0x65, 0x74, 0x44, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x12, 0x2d, 0x2e, 0x67, 0x6f, 0x6f, + 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, + 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x2e, 0x47, 0x65, 0x74, 0x44, 0x61, 0x74, 0x61, 0x73, + 0x65, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x23, 0x2e, 0x67, 0x6f, 0x6f, 0x67, + 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, + 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x2e, 0x44, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x22, 0x3b, + 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x2e, 0x12, 0x2c, 0x2f, 0x76, 0x31, 0x2f, 0x7b, 0x6e, 0x61, 0x6d, 0x65, 0x3d, 0x70, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x2f, 0x2a, 0x2f, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x2a, 0x2f, 0x64, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, - 0x73, 0x2f, 0x2a, 0x7d, 0x3a, 0x65, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x3a, 0x01, 0x2a, 0xda, 0x41, - 0x12, 0x6e, 0x61, 0x6d, 0x65, 0x2c, 0x65, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x5f, 0x63, 0x6f, 0x6e, - 0x66, 0x69, 0x67, 0xca, 0x41, 0x31, 0x0a, 0x12, 0x45, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x44, 0x61, - 0x74, 0x61, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x1b, 0x45, 0x78, 0x70, 0x6f, - 0x72, 0x74, 0x44, 0x61, 0x74, 0x61, 0x4f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x4d, - 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x12, 0xbf, 0x01, 0x0a, 0x0d, 0x4c, 0x69, 0x73, 0x74, - 0x44, 0x61, 0x74, 0x61, 0x49, 0x74, 0x65, 0x6d, 0x73, 0x12, 0x30, 0x2e, 0x67, 0x6f, 0x6f, 0x67, - 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, - 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x44, 0x61, 0x74, 0x61, 0x49, - 0x74, 0x65, 0x6d, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x31, 0x2e, 0x67, 0x6f, - 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, 0x61, - 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x44, 0x61, 0x74, - 0x61, 0x49, 0x74, 0x65, 0x6d, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x49, - 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x3a, 0x12, 0x38, 0x2f, 0x76, 0x31, 0x2f, 0x7b, 0x70, 0x61, 0x72, - 0x65, 0x6e, 0x74, 0x3d, 0x70, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x2f, 0x2a, 0x2f, 0x6c, - 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x2a, 0x2f, 0x64, 0x61, 0x74, 0x61, 0x73, - 0x65, 0x74, 0x73, 0x2f, 0x2a, 0x7d, 0x2f, 0x64, 0x61, 0x74, 0x61, 0x49, 0x74, 0x65, 0x6d, 0x73, - 0xda, 0x41, 0x06, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x12, 0xcb, 0x01, 0x0a, 0x10, 0x4c, 0x69, - 0x73, 0x74, 0x53, 0x61, 0x76, 0x65, 0x64, 0x51, 0x75, 0x65, 0x72, 0x69, 0x65, 0x73, 0x12, 0x33, - 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, 0x69, - 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x2e, 0x4c, 0x69, 0x73, 0x74, - 0x53, 0x61, 0x76, 0x65, 0x64, 0x51, 0x75, 0x65, 0x72, 0x69, 0x65, 0x73, 0x52, 0x65, 0x71, 0x75, - 0x65, 0x73, 0x74, 0x1a, 0x34, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, - 0x75, 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, - 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x53, 0x61, 0x76, 0x65, 0x64, 0x51, 0x75, 0x65, 0x72, 0x69, 0x65, - 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x4c, 0x82, 0xd3, 0xe4, 0x93, 0x02, - 0x3d, 0x12, 0x3b, 0x2f, 0x76, 0x31, 0x2f, 0x7b, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x3d, 0x70, - 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x2f, 0x2a, 0x2f, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, - 0x6f, 0x6e, 0x73, 0x2f, 0x2a, 0x2f, 0x64, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x73, 0x2f, 0x2a, - 0x7d, 0x2f, 0x73, 0x61, 0x76, 0x65, 0x64, 0x51, 0x75, 0x65, 0x72, 0x69, 0x65, 0x73, 0xda, 0x41, - 0x06, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x12, 0xc4, 0x01, 0x0a, 0x11, 0x47, 0x65, 0x74, 0x41, - 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x53, 0x70, 0x65, 0x63, 0x12, 0x34, 0x2e, + 0x73, 0x2f, 0x2a, 0x7d, 0xda, 0x41, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0xc3, 0x01, 0x0a, 0x0d, + 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x44, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x12, 0x30, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, 0x69, 0x70, - 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x2e, 0x47, 0x65, 0x74, 0x41, 0x6e, - 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x53, 0x70, 0x65, 0x63, 0x52, 0x65, 0x71, 0x75, - 0x65, 0x73, 0x74, 0x1a, 0x2a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, - 0x75, 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, - 0x2e, 0x41, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x53, 0x70, 0x65, 0x63, 0x22, - 0x4d, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x40, 0x12, 0x3e, 0x2f, 0x76, 0x31, 0x2f, 0x7b, 0x6e, 0x61, - 0x6d, 0x65, 0x3d, 0x70, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x2f, 0x2a, 0x2f, 0x6c, 0x6f, - 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x2a, 0x2f, 0x64, 0x61, 0x74, 0x61, 0x73, 0x65, - 0x74, 0x73, 0x2f, 0x2a, 0x2f, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x53, - 0x70, 0x65, 0x63, 0x73, 0x2f, 0x2a, 0x7d, 0xda, 0x41, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0xd3, - 0x01, 0x0a, 0x0f, 0x4c, 0x69, 0x73, 0x74, 0x41, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, - 0x6e, 0x73, 0x12, 0x32, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, + 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x2e, 0x55, 0x70, 0x64, 0x61, 0x74, + 0x65, 0x44, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, + 0x23, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, + 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x2e, 0x44, 0x61, 0x74, + 0x61, 0x73, 0x65, 0x74, 0x22, 0x5b, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x3f, 0x32, 0x34, 0x2f, 0x76, + 0x31, 0x2f, 0x7b, 0x64, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x2e, 0x6e, 0x61, 0x6d, 0x65, 0x3d, + 0x70, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x2f, 0x2a, 0x2f, 0x6c, 0x6f, 0x63, 0x61, 0x74, + 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x2a, 0x2f, 0x64, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x73, 0x2f, + 0x2a, 0x7d, 0x3a, 0x07, 0x64, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0xda, 0x41, 0x13, 0x64, 0x61, + 0x74, 0x61, 0x73, 0x65, 0x74, 0x2c, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x5f, 0x6d, 0x61, 0x73, + 0x6b, 0x12, 0xb0, 0x01, 0x0a, 0x0c, 0x4c, 0x69, 0x73, 0x74, 0x44, 0x61, 0x74, 0x61, 0x73, 0x65, + 0x74, 0x73, 0x12, 0x2f, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x2e, - 0x4c, 0x69, 0x73, 0x74, 0x41, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x52, - 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x33, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, + 0x4c, 0x69, 0x73, 0x74, 0x44, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x73, 0x52, 0x65, 0x71, 0x75, + 0x65, 0x73, 0x74, 0x1a, 0x30, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, + 0x75, 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, + 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x44, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x73, 0x52, 0x65, 0x73, + 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x3d, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x2e, 0x12, 0x2c, 0x2f, + 0x76, 0x31, 0x2f, 0x7b, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x3d, 0x70, 0x72, 0x6f, 0x6a, 0x65, + 0x63, 0x74, 0x73, 0x2f, 0x2a, 0x2f, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, + 0x2a, 0x7d, 0x2f, 0x64, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x73, 0xda, 0x41, 0x06, 0x70, 0x61, + 0x72, 0x65, 0x6e, 0x74, 0x12, 0xd0, 0x01, 0x0a, 0x0d, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x44, + 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x12, 0x30, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, + 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, + 0x2e, 0x76, 0x31, 0x2e, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x44, 0x61, 0x74, 0x61, 0x73, 0x65, + 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x1d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, + 0x65, 0x2e, 0x6c, 0x6f, 0x6e, 0x67, 0x72, 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x2e, 0x4f, 0x70, + 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x22, 0x6e, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x2e, 0x2a, + 0x2c, 0x2f, 0x76, 0x31, 0x2f, 0x7b, 0x6e, 0x61, 0x6d, 0x65, 0x3d, 0x70, 0x72, 0x6f, 0x6a, 0x65, + 0x63, 0x74, 0x73, 0x2f, 0x2a, 0x2f, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, + 0x2a, 0x2f, 0x64, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x73, 0x2f, 0x2a, 0x7d, 0xda, 0x41, 0x04, + 0x6e, 0x61, 0x6d, 0x65, 0xca, 0x41, 0x30, 0x0a, 0x15, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, + 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x17, + 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x4f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x4d, + 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x12, 0xe5, 0x01, 0x0a, 0x0a, 0x49, 0x6d, 0x70, 0x6f, + 0x72, 0x74, 0x44, 0x61, 0x74, 0x61, 0x12, 0x2d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, - 0x2e, 0x76, 0x31, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x41, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, - 0x6f, 0x6e, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x57, 0x82, 0xd3, 0xe4, - 0x93, 0x02, 0x48, 0x12, 0x46, 0x2f, 0x76, 0x31, 0x2f, 0x7b, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, + 0x2e, 0x76, 0x31, 0x2e, 0x49, 0x6d, 0x70, 0x6f, 0x72, 0x74, 0x44, 0x61, 0x74, 0x61, 0x52, 0x65, + 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x1d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x6c, + 0x6f, 0x6e, 0x67, 0x72, 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x2e, 0x4f, 0x70, 0x65, 0x72, 0x61, + 0x74, 0x69, 0x6f, 0x6e, 0x22, 0x88, 0x01, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x38, 0x22, 0x33, 0x2f, + 0x76, 0x31, 0x2f, 0x7b, 0x6e, 0x61, 0x6d, 0x65, 0x3d, 0x70, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74, + 0x73, 0x2f, 0x2a, 0x2f, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x2a, 0x2f, + 0x64, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x73, 0x2f, 0x2a, 0x7d, 0x3a, 0x69, 0x6d, 0x70, 0x6f, + 0x72, 0x74, 0x3a, 0x01, 0x2a, 0xda, 0x41, 0x13, 0x6e, 0x61, 0x6d, 0x65, 0x2c, 0x69, 0x6d, 0x70, + 0x6f, 0x72, 0x74, 0x5f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x73, 0xca, 0x41, 0x31, 0x0a, 0x12, + 0x49, 0x6d, 0x70, 0x6f, 0x72, 0x74, 0x44, 0x61, 0x74, 0x61, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, + 0x73, 0x65, 0x12, 0x1b, 0x49, 0x6d, 0x70, 0x6f, 0x72, 0x74, 0x44, 0x61, 0x74, 0x61, 0x4f, 0x70, + 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x12, + 0xe4, 0x01, 0x0a, 0x0a, 0x45, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x44, 0x61, 0x74, 0x61, 0x12, 0x2d, + 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, 0x69, + 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x2e, 0x45, 0x78, 0x70, 0x6f, + 0x72, 0x74, 0x44, 0x61, 0x74, 0x61, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x1d, 0x2e, + 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x6c, 0x6f, 0x6e, 0x67, 0x72, 0x75, 0x6e, 0x6e, 0x69, + 0x6e, 0x67, 0x2e, 0x4f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x22, 0x87, 0x01, 0x82, + 0xd3, 0xe4, 0x93, 0x02, 0x38, 0x22, 0x33, 0x2f, 0x76, 0x31, 0x2f, 0x7b, 0x6e, 0x61, 0x6d, 0x65, 0x3d, 0x70, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x2f, 0x2a, 0x2f, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x2a, 0x2f, 0x64, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x73, - 0x2f, 0x2a, 0x2f, 0x64, 0x61, 0x74, 0x61, 0x49, 0x74, 0x65, 0x6d, 0x73, 0x2f, 0x2a, 0x7d, 0x2f, - 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0xda, 0x41, 0x06, 0x70, 0x61, - 0x72, 0x65, 0x6e, 0x74, 0x1a, 0x4d, 0xca, 0x41, 0x19, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, - 0x6f, 0x72, 0x6d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2e, 0x63, - 0x6f, 0x6d, 0xd2, 0x41, 0x2e, 0x68, 0x74, 0x74, 0x70, 0x73, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, - 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, - 0x61, 0x75, 0x74, 0x68, 0x2f, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2d, 0x70, 0x6c, 0x61, 0x74, 0x66, - 0x6f, 0x72, 0x6d, 0x42, 0xd7, 0x01, 0x0a, 0x1e, 0x63, 0x6f, 0x6d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, - 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, - 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x42, 0x13, 0x44, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x53, - 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x44, 0x67, - 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2e, 0x6f, 0x72, 0x67, - 0x2f, 0x67, 0x65, 0x6e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, - 0x61, 0x70, 0x69, 0x73, 0x2f, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2f, 0x61, 0x69, 0x70, 0x6c, 0x61, - 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2f, 0x76, 0x31, 0x3b, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, - 0x6f, 0x72, 0x6d, 0xaa, 0x02, 0x1a, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x43, 0x6c, 0x6f, - 0x75, 0x64, 0x2e, 0x41, 0x49, 0x50, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x56, 0x31, - 0xca, 0x02, 0x1a, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x5c, 0x43, 0x6c, 0x6f, 0x75, 0x64, 0x5c, - 0x41, 0x49, 0x50, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x5c, 0x56, 0x31, 0xea, 0x02, 0x1d, - 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x3a, 0x3a, 0x43, 0x6c, 0x6f, 0x75, 0x64, 0x3a, 0x3a, 0x41, - 0x49, 0x50, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x3a, 0x3a, 0x56, 0x31, 0x62, 0x06, 0x70, - 0x72, 0x6f, 0x74, 0x6f, 0x33, + 0x2f, 0x2a, 0x7d, 0x3a, 0x65, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x3a, 0x01, 0x2a, 0xda, 0x41, 0x12, + 0x6e, 0x61, 0x6d, 0x65, 0x2c, 0x65, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x5f, 0x63, 0x6f, 0x6e, 0x66, + 0x69, 0x67, 0xca, 0x41, 0x31, 0x0a, 0x12, 0x45, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x44, 0x61, 0x74, + 0x61, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x1b, 0x45, 0x78, 0x70, 0x6f, 0x72, + 0x74, 0x44, 0x61, 0x74, 0x61, 0x4f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x4d, 0x65, + 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x12, 0xbf, 0x01, 0x0a, 0x0d, 0x4c, 0x69, 0x73, 0x74, 0x44, + 0x61, 0x74, 0x61, 0x49, 0x74, 0x65, 0x6d, 0x73, 0x12, 0x30, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, + 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, + 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x44, 0x61, 0x74, 0x61, 0x49, 0x74, + 0x65, 0x6d, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x31, 0x2e, 0x67, 0x6f, 0x6f, + 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, + 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x44, 0x61, 0x74, 0x61, + 0x49, 0x74, 0x65, 0x6d, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x49, 0x82, + 0xd3, 0xe4, 0x93, 0x02, 0x3a, 0x12, 0x38, 0x2f, 0x76, 0x31, 0x2f, 0x7b, 0x70, 0x61, 0x72, 0x65, + 0x6e, 0x74, 0x3d, 0x70, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x2f, 0x2a, 0x2f, 0x6c, 0x6f, + 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x2a, 0x2f, 0x64, 0x61, 0x74, 0x61, 0x73, 0x65, + 0x74, 0x73, 0x2f, 0x2a, 0x7d, 0x2f, 0x64, 0x61, 0x74, 0x61, 0x49, 0x74, 0x65, 0x6d, 0x73, 0xda, + 0x41, 0x06, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x12, 0xc3, 0x01, 0x0a, 0x0f, 0x53, 0x65, 0x61, + 0x72, 0x63, 0x68, 0x44, 0x61, 0x74, 0x61, 0x49, 0x74, 0x65, 0x6d, 0x73, 0x12, 0x32, 0x2e, 0x67, + 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, + 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x65, 0x61, 0x72, 0x63, 0x68, + 0x44, 0x61, 0x74, 0x61, 0x49, 0x74, 0x65, 0x6d, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, + 0x1a, 0x33, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, + 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x65, + 0x61, 0x72, 0x63, 0x68, 0x44, 0x61, 0x74, 0x61, 0x49, 0x74, 0x65, 0x6d, 0x73, 0x52, 0x65, 0x73, + 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x47, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x41, 0x12, 0x3f, 0x2f, + 0x76, 0x31, 0x2f, 0x7b, 0x64, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x3d, 0x70, 0x72, 0x6f, 0x6a, + 0x65, 0x63, 0x74, 0x73, 0x2f, 0x2a, 0x2f, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, + 0x2f, 0x2a, 0x2f, 0x64, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x73, 0x2f, 0x2a, 0x7d, 0x3a, 0x73, + 0x65, 0x61, 0x72, 0x63, 0x68, 0x44, 0x61, 0x74, 0x61, 0x49, 0x74, 0x65, 0x6d, 0x73, 0x12, 0xcb, + 0x01, 0x0a, 0x10, 0x4c, 0x69, 0x73, 0x74, 0x53, 0x61, 0x76, 0x65, 0x64, 0x51, 0x75, 0x65, 0x72, + 0x69, 0x65, 0x73, 0x12, 0x33, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, + 0x75, 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, + 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x53, 0x61, 0x76, 0x65, 0x64, 0x51, 0x75, 0x65, 0x72, 0x69, 0x65, + 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x34, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, + 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, + 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x53, 0x61, 0x76, 0x65, 0x64, 0x51, + 0x75, 0x65, 0x72, 0x69, 0x65, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x4c, + 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x3d, 0x12, 0x3b, 0x2f, 0x76, 0x31, 0x2f, 0x7b, 0x70, 0x61, 0x72, + 0x65, 0x6e, 0x74, 0x3d, 0x70, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x2f, 0x2a, 0x2f, 0x6c, + 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x2a, 0x2f, 0x64, 0x61, 0x74, 0x61, 0x73, + 0x65, 0x74, 0x73, 0x2f, 0x2a, 0x7d, 0x2f, 0x73, 0x61, 0x76, 0x65, 0x64, 0x51, 0x75, 0x65, 0x72, + 0x69, 0x65, 0x73, 0xda, 0x41, 0x06, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x12, 0xc4, 0x01, 0x0a, + 0x11, 0x47, 0x65, 0x74, 0x41, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x53, 0x70, + 0x65, 0x63, 0x12, 0x34, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, + 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x2e, + 0x47, 0x65, 0x74, 0x41, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x53, 0x70, 0x65, + 0x63, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x2a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, + 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, + 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x2e, 0x41, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, + 0x53, 0x70, 0x65, 0x63, 0x22, 0x4d, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x40, 0x12, 0x3e, 0x2f, 0x76, + 0x31, 0x2f, 0x7b, 0x6e, 0x61, 0x6d, 0x65, 0x3d, 0x70, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74, 0x73, + 0x2f, 0x2a, 0x2f, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x2a, 0x2f, 0x64, + 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x73, 0x2f, 0x2a, 0x2f, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, + 0x74, 0x69, 0x6f, 0x6e, 0x53, 0x70, 0x65, 0x63, 0x73, 0x2f, 0x2a, 0x7d, 0xda, 0x41, 0x04, 0x6e, + 0x61, 0x6d, 0x65, 0x12, 0xd3, 0x01, 0x0a, 0x0f, 0x4c, 0x69, 0x73, 0x74, 0x41, 0x6e, 0x6e, 0x6f, + 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x32, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, + 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, + 0x6d, 0x2e, 0x76, 0x31, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x41, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, + 0x69, 0x6f, 0x6e, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x33, 0x2e, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, 0x61, + 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x41, 0x6e, 0x6e, + 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, + 0x22, 0x57, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x48, 0x12, 0x46, 0x2f, 0x76, 0x31, 0x2f, 0x7b, 0x70, + 0x61, 0x72, 0x65, 0x6e, 0x74, 0x3d, 0x70, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x2f, 0x2a, + 0x2f, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x2a, 0x2f, 0x64, 0x61, 0x74, + 0x61, 0x73, 0x65, 0x74, 0x73, 0x2f, 0x2a, 0x2f, 0x64, 0x61, 0x74, 0x61, 0x49, 0x74, 0x65, 0x6d, + 0x73, 0x2f, 0x2a, 0x7d, 0x2f, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, + 0xda, 0x41, 0x06, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x1a, 0x4d, 0xca, 0x41, 0x19, 0x61, 0x69, + 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, + 0x70, 0x69, 0x73, 0x2e, 0x63, 0x6f, 0x6d, 0xd2, 0x41, 0x2e, 0x68, 0x74, 0x74, 0x70, 0x73, 0x3a, + 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, + 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x61, 0x75, 0x74, 0x68, 0x2f, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2d, + 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x42, 0xd7, 0x01, 0x0a, 0x1e, 0x63, 0x6f, 0x6d, + 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, 0x69, + 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x42, 0x13, 0x44, 0x61, 0x74, + 0x61, 0x73, 0x65, 0x74, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x50, 0x72, 0x6f, 0x74, 0x6f, + 0x50, 0x01, 0x5a, 0x44, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x67, 0x6f, 0x6c, 0x61, 0x6e, + 0x67, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x67, 0x65, 0x6e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x67, + 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2f, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2f, + 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2f, 0x76, 0x31, 0x3b, 0x61, 0x69, + 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0xaa, 0x02, 0x1a, 0x47, 0x6f, 0x6f, 0x67, 0x6c, + 0x65, 0x2e, 0x43, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x41, 0x49, 0x50, 0x6c, 0x61, 0x74, 0x66, 0x6f, + 0x72, 0x6d, 0x2e, 0x56, 0x31, 0xca, 0x02, 0x1a, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x5c, 0x43, + 0x6c, 0x6f, 0x75, 0x64, 0x5c, 0x41, 0x49, 0x50, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x5c, + 0x56, 0x31, 0xea, 0x02, 0x1d, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x3a, 0x3a, 0x43, 0x6c, 0x6f, + 0x75, 0x64, 0x3a, 0x3a, 0x41, 0x49, 0x50, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x3a, 0x3a, + 0x56, 0x31, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( @@ -1747,85 +2252,96 @@ func file_google_cloud_aiplatform_v1_dataset_service_proto_rawDescGZIP() []byte return file_google_cloud_aiplatform_v1_dataset_service_proto_rawDescData } -var file_google_cloud_aiplatform_v1_dataset_service_proto_msgTypes = make([]protoimpl.MessageInfo, 20) +var file_google_cloud_aiplatform_v1_dataset_service_proto_msgTypes = make([]protoimpl.MessageInfo, 24) var file_google_cloud_aiplatform_v1_dataset_service_proto_goTypes = []interface{}{ - (*CreateDatasetRequest)(nil), // 0: google.cloud.aiplatform.v1.CreateDatasetRequest - (*CreateDatasetOperationMetadata)(nil), // 1: google.cloud.aiplatform.v1.CreateDatasetOperationMetadata - (*GetDatasetRequest)(nil), // 2: google.cloud.aiplatform.v1.GetDatasetRequest - (*UpdateDatasetRequest)(nil), // 3: google.cloud.aiplatform.v1.UpdateDatasetRequest - (*ListDatasetsRequest)(nil), // 4: google.cloud.aiplatform.v1.ListDatasetsRequest - (*ListDatasetsResponse)(nil), // 5: google.cloud.aiplatform.v1.ListDatasetsResponse - (*DeleteDatasetRequest)(nil), // 6: google.cloud.aiplatform.v1.DeleteDatasetRequest - (*ImportDataRequest)(nil), // 7: google.cloud.aiplatform.v1.ImportDataRequest - (*ImportDataResponse)(nil), // 8: google.cloud.aiplatform.v1.ImportDataResponse - (*ImportDataOperationMetadata)(nil), // 9: google.cloud.aiplatform.v1.ImportDataOperationMetadata - (*ExportDataRequest)(nil), // 10: google.cloud.aiplatform.v1.ExportDataRequest - (*ExportDataResponse)(nil), // 11: google.cloud.aiplatform.v1.ExportDataResponse - (*ExportDataOperationMetadata)(nil), // 12: google.cloud.aiplatform.v1.ExportDataOperationMetadata - (*ListDataItemsRequest)(nil), // 13: google.cloud.aiplatform.v1.ListDataItemsRequest - (*ListDataItemsResponse)(nil), // 14: google.cloud.aiplatform.v1.ListDataItemsResponse - (*ListSavedQueriesRequest)(nil), // 15: google.cloud.aiplatform.v1.ListSavedQueriesRequest - (*ListSavedQueriesResponse)(nil), // 16: google.cloud.aiplatform.v1.ListSavedQueriesResponse - (*GetAnnotationSpecRequest)(nil), // 17: google.cloud.aiplatform.v1.GetAnnotationSpecRequest - (*ListAnnotationsRequest)(nil), // 18: google.cloud.aiplatform.v1.ListAnnotationsRequest - (*ListAnnotationsResponse)(nil), // 19: google.cloud.aiplatform.v1.ListAnnotationsResponse - (*Dataset)(nil), // 20: google.cloud.aiplatform.v1.Dataset - (*GenericOperationMetadata)(nil), // 21: google.cloud.aiplatform.v1.GenericOperationMetadata - (*fieldmaskpb.FieldMask)(nil), // 22: google.protobuf.FieldMask - (*ImportDataConfig)(nil), // 23: google.cloud.aiplatform.v1.ImportDataConfig - (*ExportDataConfig)(nil), // 24: google.cloud.aiplatform.v1.ExportDataConfig - (*DataItem)(nil), // 25: google.cloud.aiplatform.v1.DataItem - (*SavedQuery)(nil), // 26: google.cloud.aiplatform.v1.SavedQuery - (*Annotation)(nil), // 27: google.cloud.aiplatform.v1.Annotation - (*longrunning.Operation)(nil), // 28: google.longrunning.Operation - (*AnnotationSpec)(nil), // 29: google.cloud.aiplatform.v1.AnnotationSpec + (*CreateDatasetRequest)(nil), // 0: google.cloud.aiplatform.v1.CreateDatasetRequest + (*CreateDatasetOperationMetadata)(nil), // 1: google.cloud.aiplatform.v1.CreateDatasetOperationMetadata + (*GetDatasetRequest)(nil), // 2: google.cloud.aiplatform.v1.GetDatasetRequest + (*UpdateDatasetRequest)(nil), // 3: google.cloud.aiplatform.v1.UpdateDatasetRequest + (*ListDatasetsRequest)(nil), // 4: google.cloud.aiplatform.v1.ListDatasetsRequest + (*ListDatasetsResponse)(nil), // 5: google.cloud.aiplatform.v1.ListDatasetsResponse + (*DeleteDatasetRequest)(nil), // 6: google.cloud.aiplatform.v1.DeleteDatasetRequest + (*ImportDataRequest)(nil), // 7: google.cloud.aiplatform.v1.ImportDataRequest + (*ImportDataResponse)(nil), // 8: google.cloud.aiplatform.v1.ImportDataResponse + (*ImportDataOperationMetadata)(nil), // 9: google.cloud.aiplatform.v1.ImportDataOperationMetadata + (*ExportDataRequest)(nil), // 10: google.cloud.aiplatform.v1.ExportDataRequest + (*ExportDataResponse)(nil), // 11: google.cloud.aiplatform.v1.ExportDataResponse + (*ExportDataOperationMetadata)(nil), // 12: google.cloud.aiplatform.v1.ExportDataOperationMetadata + (*ListDataItemsRequest)(nil), // 13: google.cloud.aiplatform.v1.ListDataItemsRequest + (*ListDataItemsResponse)(nil), // 14: google.cloud.aiplatform.v1.ListDataItemsResponse + (*SearchDataItemsRequest)(nil), // 15: google.cloud.aiplatform.v1.SearchDataItemsRequest + (*SearchDataItemsResponse)(nil), // 16: google.cloud.aiplatform.v1.SearchDataItemsResponse + (*DataItemView)(nil), // 17: google.cloud.aiplatform.v1.DataItemView + (*ListSavedQueriesRequest)(nil), // 18: google.cloud.aiplatform.v1.ListSavedQueriesRequest + (*ListSavedQueriesResponse)(nil), // 19: google.cloud.aiplatform.v1.ListSavedQueriesResponse + (*GetAnnotationSpecRequest)(nil), // 20: google.cloud.aiplatform.v1.GetAnnotationSpecRequest + (*ListAnnotationsRequest)(nil), // 21: google.cloud.aiplatform.v1.ListAnnotationsRequest + (*ListAnnotationsResponse)(nil), // 22: google.cloud.aiplatform.v1.ListAnnotationsResponse + (*SearchDataItemsRequest_OrderByAnnotation)(nil), // 23: google.cloud.aiplatform.v1.SearchDataItemsRequest.OrderByAnnotation + (*Dataset)(nil), // 24: google.cloud.aiplatform.v1.Dataset + (*GenericOperationMetadata)(nil), // 25: google.cloud.aiplatform.v1.GenericOperationMetadata + (*fieldmaskpb.FieldMask)(nil), // 26: google.protobuf.FieldMask + (*ImportDataConfig)(nil), // 27: google.cloud.aiplatform.v1.ImportDataConfig + (*ExportDataConfig)(nil), // 28: google.cloud.aiplatform.v1.ExportDataConfig + (*DataItem)(nil), // 29: google.cloud.aiplatform.v1.DataItem + (*Annotation)(nil), // 30: google.cloud.aiplatform.v1.Annotation + (*SavedQuery)(nil), // 31: google.cloud.aiplatform.v1.SavedQuery + (*longrunning.Operation)(nil), // 32: google.longrunning.Operation + (*AnnotationSpec)(nil), // 33: google.cloud.aiplatform.v1.AnnotationSpec } var file_google_cloud_aiplatform_v1_dataset_service_proto_depIdxs = []int32{ - 20, // 0: google.cloud.aiplatform.v1.CreateDatasetRequest.dataset:type_name -> google.cloud.aiplatform.v1.Dataset - 21, // 1: google.cloud.aiplatform.v1.CreateDatasetOperationMetadata.generic_metadata:type_name -> google.cloud.aiplatform.v1.GenericOperationMetadata - 22, // 2: google.cloud.aiplatform.v1.GetDatasetRequest.read_mask:type_name -> google.protobuf.FieldMask - 20, // 3: google.cloud.aiplatform.v1.UpdateDatasetRequest.dataset:type_name -> google.cloud.aiplatform.v1.Dataset - 22, // 4: google.cloud.aiplatform.v1.UpdateDatasetRequest.update_mask:type_name -> google.protobuf.FieldMask - 22, // 5: google.cloud.aiplatform.v1.ListDatasetsRequest.read_mask:type_name -> google.protobuf.FieldMask - 20, // 6: google.cloud.aiplatform.v1.ListDatasetsResponse.datasets:type_name -> google.cloud.aiplatform.v1.Dataset - 23, // 7: google.cloud.aiplatform.v1.ImportDataRequest.import_configs:type_name -> google.cloud.aiplatform.v1.ImportDataConfig - 21, // 8: google.cloud.aiplatform.v1.ImportDataOperationMetadata.generic_metadata:type_name -> google.cloud.aiplatform.v1.GenericOperationMetadata - 24, // 9: google.cloud.aiplatform.v1.ExportDataRequest.export_config:type_name -> google.cloud.aiplatform.v1.ExportDataConfig - 21, // 10: google.cloud.aiplatform.v1.ExportDataOperationMetadata.generic_metadata:type_name -> google.cloud.aiplatform.v1.GenericOperationMetadata - 22, // 11: google.cloud.aiplatform.v1.ListDataItemsRequest.read_mask:type_name -> google.protobuf.FieldMask - 25, // 12: google.cloud.aiplatform.v1.ListDataItemsResponse.data_items:type_name -> google.cloud.aiplatform.v1.DataItem - 22, // 13: google.cloud.aiplatform.v1.ListSavedQueriesRequest.read_mask:type_name -> google.protobuf.FieldMask - 26, // 14: google.cloud.aiplatform.v1.ListSavedQueriesResponse.saved_queries:type_name -> google.cloud.aiplatform.v1.SavedQuery - 22, // 15: google.cloud.aiplatform.v1.GetAnnotationSpecRequest.read_mask:type_name -> google.protobuf.FieldMask - 22, // 16: google.cloud.aiplatform.v1.ListAnnotationsRequest.read_mask:type_name -> google.protobuf.FieldMask - 27, // 17: google.cloud.aiplatform.v1.ListAnnotationsResponse.annotations:type_name -> google.cloud.aiplatform.v1.Annotation - 0, // 18: google.cloud.aiplatform.v1.DatasetService.CreateDataset:input_type -> google.cloud.aiplatform.v1.CreateDatasetRequest - 2, // 19: google.cloud.aiplatform.v1.DatasetService.GetDataset:input_type -> google.cloud.aiplatform.v1.GetDatasetRequest - 3, // 20: google.cloud.aiplatform.v1.DatasetService.UpdateDataset:input_type -> google.cloud.aiplatform.v1.UpdateDatasetRequest - 4, // 21: google.cloud.aiplatform.v1.DatasetService.ListDatasets:input_type -> google.cloud.aiplatform.v1.ListDatasetsRequest - 6, // 22: google.cloud.aiplatform.v1.DatasetService.DeleteDataset:input_type -> google.cloud.aiplatform.v1.DeleteDatasetRequest - 7, // 23: google.cloud.aiplatform.v1.DatasetService.ImportData:input_type -> google.cloud.aiplatform.v1.ImportDataRequest - 10, // 24: google.cloud.aiplatform.v1.DatasetService.ExportData:input_type -> google.cloud.aiplatform.v1.ExportDataRequest - 13, // 25: google.cloud.aiplatform.v1.DatasetService.ListDataItems:input_type -> google.cloud.aiplatform.v1.ListDataItemsRequest - 15, // 26: google.cloud.aiplatform.v1.DatasetService.ListSavedQueries:input_type -> google.cloud.aiplatform.v1.ListSavedQueriesRequest - 17, // 27: google.cloud.aiplatform.v1.DatasetService.GetAnnotationSpec:input_type -> google.cloud.aiplatform.v1.GetAnnotationSpecRequest - 18, // 28: google.cloud.aiplatform.v1.DatasetService.ListAnnotations:input_type -> google.cloud.aiplatform.v1.ListAnnotationsRequest - 28, // 29: google.cloud.aiplatform.v1.DatasetService.CreateDataset:output_type -> google.longrunning.Operation - 20, // 30: google.cloud.aiplatform.v1.DatasetService.GetDataset:output_type -> google.cloud.aiplatform.v1.Dataset - 20, // 31: google.cloud.aiplatform.v1.DatasetService.UpdateDataset:output_type -> google.cloud.aiplatform.v1.Dataset - 5, // 32: google.cloud.aiplatform.v1.DatasetService.ListDatasets:output_type -> google.cloud.aiplatform.v1.ListDatasetsResponse - 28, // 33: google.cloud.aiplatform.v1.DatasetService.DeleteDataset:output_type -> google.longrunning.Operation - 28, // 34: google.cloud.aiplatform.v1.DatasetService.ImportData:output_type -> google.longrunning.Operation - 28, // 35: google.cloud.aiplatform.v1.DatasetService.ExportData:output_type -> google.longrunning.Operation - 14, // 36: google.cloud.aiplatform.v1.DatasetService.ListDataItems:output_type -> google.cloud.aiplatform.v1.ListDataItemsResponse - 16, // 37: google.cloud.aiplatform.v1.DatasetService.ListSavedQueries:output_type -> google.cloud.aiplatform.v1.ListSavedQueriesResponse - 29, // 38: google.cloud.aiplatform.v1.DatasetService.GetAnnotationSpec:output_type -> google.cloud.aiplatform.v1.AnnotationSpec - 19, // 39: google.cloud.aiplatform.v1.DatasetService.ListAnnotations:output_type -> google.cloud.aiplatform.v1.ListAnnotationsResponse - 29, // [29:40] is the sub-list for method output_type - 18, // [18:29] is the sub-list for method input_type - 18, // [18:18] is the sub-list for extension type_name - 18, // [18:18] is the sub-list for extension extendee - 0, // [0:18] is the sub-list for field type_name + 24, // 0: google.cloud.aiplatform.v1.CreateDatasetRequest.dataset:type_name -> google.cloud.aiplatform.v1.Dataset + 25, // 1: google.cloud.aiplatform.v1.CreateDatasetOperationMetadata.generic_metadata:type_name -> google.cloud.aiplatform.v1.GenericOperationMetadata + 26, // 2: google.cloud.aiplatform.v1.GetDatasetRequest.read_mask:type_name -> google.protobuf.FieldMask + 24, // 3: google.cloud.aiplatform.v1.UpdateDatasetRequest.dataset:type_name -> google.cloud.aiplatform.v1.Dataset + 26, // 4: google.cloud.aiplatform.v1.UpdateDatasetRequest.update_mask:type_name -> google.protobuf.FieldMask + 26, // 5: google.cloud.aiplatform.v1.ListDatasetsRequest.read_mask:type_name -> google.protobuf.FieldMask + 24, // 6: google.cloud.aiplatform.v1.ListDatasetsResponse.datasets:type_name -> google.cloud.aiplatform.v1.Dataset + 27, // 7: google.cloud.aiplatform.v1.ImportDataRequest.import_configs:type_name -> google.cloud.aiplatform.v1.ImportDataConfig + 25, // 8: google.cloud.aiplatform.v1.ImportDataOperationMetadata.generic_metadata:type_name -> google.cloud.aiplatform.v1.GenericOperationMetadata + 28, // 9: google.cloud.aiplatform.v1.ExportDataRequest.export_config:type_name -> google.cloud.aiplatform.v1.ExportDataConfig + 25, // 10: google.cloud.aiplatform.v1.ExportDataOperationMetadata.generic_metadata:type_name -> google.cloud.aiplatform.v1.GenericOperationMetadata + 26, // 11: google.cloud.aiplatform.v1.ListDataItemsRequest.read_mask:type_name -> google.protobuf.FieldMask + 29, // 12: google.cloud.aiplatform.v1.ListDataItemsResponse.data_items:type_name -> google.cloud.aiplatform.v1.DataItem + 23, // 13: google.cloud.aiplatform.v1.SearchDataItemsRequest.order_by_annotation:type_name -> google.cloud.aiplatform.v1.SearchDataItemsRequest.OrderByAnnotation + 26, // 14: google.cloud.aiplatform.v1.SearchDataItemsRequest.field_mask:type_name -> google.protobuf.FieldMask + 17, // 15: google.cloud.aiplatform.v1.SearchDataItemsResponse.data_item_views:type_name -> google.cloud.aiplatform.v1.DataItemView + 29, // 16: google.cloud.aiplatform.v1.DataItemView.data_item:type_name -> google.cloud.aiplatform.v1.DataItem + 30, // 17: google.cloud.aiplatform.v1.DataItemView.annotations:type_name -> google.cloud.aiplatform.v1.Annotation + 26, // 18: google.cloud.aiplatform.v1.ListSavedQueriesRequest.read_mask:type_name -> google.protobuf.FieldMask + 31, // 19: google.cloud.aiplatform.v1.ListSavedQueriesResponse.saved_queries:type_name -> google.cloud.aiplatform.v1.SavedQuery + 26, // 20: google.cloud.aiplatform.v1.GetAnnotationSpecRequest.read_mask:type_name -> google.protobuf.FieldMask + 26, // 21: google.cloud.aiplatform.v1.ListAnnotationsRequest.read_mask:type_name -> google.protobuf.FieldMask + 30, // 22: google.cloud.aiplatform.v1.ListAnnotationsResponse.annotations:type_name -> google.cloud.aiplatform.v1.Annotation + 0, // 23: google.cloud.aiplatform.v1.DatasetService.CreateDataset:input_type -> google.cloud.aiplatform.v1.CreateDatasetRequest + 2, // 24: google.cloud.aiplatform.v1.DatasetService.GetDataset:input_type -> google.cloud.aiplatform.v1.GetDatasetRequest + 3, // 25: google.cloud.aiplatform.v1.DatasetService.UpdateDataset:input_type -> google.cloud.aiplatform.v1.UpdateDatasetRequest + 4, // 26: google.cloud.aiplatform.v1.DatasetService.ListDatasets:input_type -> google.cloud.aiplatform.v1.ListDatasetsRequest + 6, // 27: google.cloud.aiplatform.v1.DatasetService.DeleteDataset:input_type -> google.cloud.aiplatform.v1.DeleteDatasetRequest + 7, // 28: google.cloud.aiplatform.v1.DatasetService.ImportData:input_type -> google.cloud.aiplatform.v1.ImportDataRequest + 10, // 29: google.cloud.aiplatform.v1.DatasetService.ExportData:input_type -> google.cloud.aiplatform.v1.ExportDataRequest + 13, // 30: google.cloud.aiplatform.v1.DatasetService.ListDataItems:input_type -> google.cloud.aiplatform.v1.ListDataItemsRequest + 15, // 31: google.cloud.aiplatform.v1.DatasetService.SearchDataItems:input_type -> google.cloud.aiplatform.v1.SearchDataItemsRequest + 18, // 32: google.cloud.aiplatform.v1.DatasetService.ListSavedQueries:input_type -> google.cloud.aiplatform.v1.ListSavedQueriesRequest + 20, // 33: google.cloud.aiplatform.v1.DatasetService.GetAnnotationSpec:input_type -> google.cloud.aiplatform.v1.GetAnnotationSpecRequest + 21, // 34: google.cloud.aiplatform.v1.DatasetService.ListAnnotations:input_type -> google.cloud.aiplatform.v1.ListAnnotationsRequest + 32, // 35: google.cloud.aiplatform.v1.DatasetService.CreateDataset:output_type -> google.longrunning.Operation + 24, // 36: google.cloud.aiplatform.v1.DatasetService.GetDataset:output_type -> google.cloud.aiplatform.v1.Dataset + 24, // 37: google.cloud.aiplatform.v1.DatasetService.UpdateDataset:output_type -> google.cloud.aiplatform.v1.Dataset + 5, // 38: google.cloud.aiplatform.v1.DatasetService.ListDatasets:output_type -> google.cloud.aiplatform.v1.ListDatasetsResponse + 32, // 39: google.cloud.aiplatform.v1.DatasetService.DeleteDataset:output_type -> google.longrunning.Operation + 32, // 40: google.cloud.aiplatform.v1.DatasetService.ImportData:output_type -> google.longrunning.Operation + 32, // 41: google.cloud.aiplatform.v1.DatasetService.ExportData:output_type -> google.longrunning.Operation + 14, // 42: google.cloud.aiplatform.v1.DatasetService.ListDataItems:output_type -> google.cloud.aiplatform.v1.ListDataItemsResponse + 16, // 43: google.cloud.aiplatform.v1.DatasetService.SearchDataItems:output_type -> google.cloud.aiplatform.v1.SearchDataItemsResponse + 19, // 44: google.cloud.aiplatform.v1.DatasetService.ListSavedQueries:output_type -> google.cloud.aiplatform.v1.ListSavedQueriesResponse + 33, // 45: google.cloud.aiplatform.v1.DatasetService.GetAnnotationSpec:output_type -> google.cloud.aiplatform.v1.AnnotationSpec + 22, // 46: google.cloud.aiplatform.v1.DatasetService.ListAnnotations:output_type -> google.cloud.aiplatform.v1.ListAnnotationsResponse + 35, // [35:47] is the sub-list for method output_type + 23, // [23:35] is the sub-list for method input_type + 23, // [23:23] is the sub-list for extension type_name + 23, // [23:23] is the sub-list for extension extendee + 0, // [0:23] is the sub-list for field type_name } func init() { file_google_cloud_aiplatform_v1_dataset_service_proto_init() } @@ -2021,7 +2537,7 @@ func file_google_cloud_aiplatform_v1_dataset_service_proto_init() { } } file_google_cloud_aiplatform_v1_dataset_service_proto_msgTypes[15].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ListSavedQueriesRequest); i { + switch v := v.(*SearchDataItemsRequest); i { case 0: return &v.state case 1: @@ -2033,7 +2549,7 @@ func file_google_cloud_aiplatform_v1_dataset_service_proto_init() { } } file_google_cloud_aiplatform_v1_dataset_service_proto_msgTypes[16].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ListSavedQueriesResponse); i { + switch v := v.(*SearchDataItemsResponse); i { case 0: return &v.state case 1: @@ -2045,7 +2561,7 @@ func file_google_cloud_aiplatform_v1_dataset_service_proto_init() { } } file_google_cloud_aiplatform_v1_dataset_service_proto_msgTypes[17].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*GetAnnotationSpecRequest); i { + switch v := v.(*DataItemView); i { case 0: return &v.state case 1: @@ -2057,7 +2573,7 @@ func file_google_cloud_aiplatform_v1_dataset_service_proto_init() { } } file_google_cloud_aiplatform_v1_dataset_service_proto_msgTypes[18].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ListAnnotationsRequest); i { + switch v := v.(*ListSavedQueriesRequest); i { case 0: return &v.state case 1: @@ -2069,6 +2585,42 @@ func file_google_cloud_aiplatform_v1_dataset_service_proto_init() { } } file_google_cloud_aiplatform_v1_dataset_service_proto_msgTypes[19].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*ListSavedQueriesResponse); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_google_cloud_aiplatform_v1_dataset_service_proto_msgTypes[20].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*GetAnnotationSpecRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_google_cloud_aiplatform_v1_dataset_service_proto_msgTypes[21].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*ListAnnotationsRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_google_cloud_aiplatform_v1_dataset_service_proto_msgTypes[22].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ListAnnotationsResponse); i { case 0: return &v.state @@ -2080,6 +2632,22 @@ func file_google_cloud_aiplatform_v1_dataset_service_proto_init() { return nil } } + file_google_cloud_aiplatform_v1_dataset_service_proto_msgTypes[23].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*SearchDataItemsRequest_OrderByAnnotation); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + file_google_cloud_aiplatform_v1_dataset_service_proto_msgTypes[15].OneofWrappers = []interface{}{ + (*SearchDataItemsRequest_OrderByDataItem)(nil), + (*SearchDataItemsRequest_OrderByAnnotation_)(nil), } type x struct{} out := protoimpl.TypeBuilder{ @@ -2087,7 +2655,7 @@ func file_google_cloud_aiplatform_v1_dataset_service_proto_init() { GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_google_cloud_aiplatform_v1_dataset_service_proto_rawDesc, NumEnums: 0, - NumMessages: 20, + NumMessages: 24, NumExtensions: 0, NumServices: 1, }, @@ -2129,6 +2697,8 @@ type DatasetServiceClient interface { ExportData(ctx context.Context, in *ExportDataRequest, opts ...grpc.CallOption) (*longrunning.Operation, error) // Lists DataItems in a Dataset. ListDataItems(ctx context.Context, in *ListDataItemsRequest, opts ...grpc.CallOption) (*ListDataItemsResponse, error) + // Searches DataItems in a Dataset. + SearchDataItems(ctx context.Context, in *SearchDataItemsRequest, opts ...grpc.CallOption) (*SearchDataItemsResponse, error) // Lists SavedQueries in a Dataset. ListSavedQueries(ctx context.Context, in *ListSavedQueriesRequest, opts ...grpc.CallOption) (*ListSavedQueriesResponse, error) // Gets an AnnotationSpec. @@ -2217,6 +2787,15 @@ func (c *datasetServiceClient) ListDataItems(ctx context.Context, in *ListDataIt return out, nil } +func (c *datasetServiceClient) SearchDataItems(ctx context.Context, in *SearchDataItemsRequest, opts ...grpc.CallOption) (*SearchDataItemsResponse, error) { + out := new(SearchDataItemsResponse) + err := c.cc.Invoke(ctx, "/google.cloud.aiplatform.v1.DatasetService/SearchDataItems", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + func (c *datasetServiceClient) ListSavedQueries(ctx context.Context, in *ListSavedQueriesRequest, opts ...grpc.CallOption) (*ListSavedQueriesResponse, error) { out := new(ListSavedQueriesResponse) err := c.cc.Invoke(ctx, "/google.cloud.aiplatform.v1.DatasetService/ListSavedQueries", in, out, opts...) @@ -2262,6 +2841,8 @@ type DatasetServiceServer interface { ExportData(context.Context, *ExportDataRequest) (*longrunning.Operation, error) // Lists DataItems in a Dataset. ListDataItems(context.Context, *ListDataItemsRequest) (*ListDataItemsResponse, error) + // Searches DataItems in a Dataset. + SearchDataItems(context.Context, *SearchDataItemsRequest) (*SearchDataItemsResponse, error) // Lists SavedQueries in a Dataset. ListSavedQueries(context.Context, *ListSavedQueriesRequest) (*ListSavedQueriesResponse, error) // Gets an AnnotationSpec. @@ -2298,6 +2879,9 @@ func (*UnimplementedDatasetServiceServer) ExportData(context.Context, *ExportDat func (*UnimplementedDatasetServiceServer) ListDataItems(context.Context, *ListDataItemsRequest) (*ListDataItemsResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method ListDataItems not implemented") } +func (*UnimplementedDatasetServiceServer) SearchDataItems(context.Context, *SearchDataItemsRequest) (*SearchDataItemsResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method SearchDataItems not implemented") +} func (*UnimplementedDatasetServiceServer) ListSavedQueries(context.Context, *ListSavedQueriesRequest) (*ListSavedQueriesResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method ListSavedQueries not implemented") } @@ -2456,6 +3040,24 @@ func _DatasetService_ListDataItems_Handler(srv interface{}, ctx context.Context, return interceptor(ctx, in, info, handler) } +func _DatasetService_SearchDataItems_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(SearchDataItemsRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(DatasetServiceServer).SearchDataItems(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/google.cloud.aiplatform.v1.DatasetService/SearchDataItems", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(DatasetServiceServer).SearchDataItems(ctx, req.(*SearchDataItemsRequest)) + } + return interceptor(ctx, in, info, handler) +} + func _DatasetService_ListSavedQueries_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(ListSavedQueriesRequest) if err := dec(in); err != nil { @@ -2546,6 +3148,10 @@ var _DatasetService_serviceDesc = grpc.ServiceDesc{ MethodName: "ListDataItems", Handler: _DatasetService_ListDataItems_Handler, }, + { + MethodName: "SearchDataItems", + Handler: _DatasetService_SearchDataItems_Handler, + }, { MethodName: "ListSavedQueries", Handler: _DatasetService_ListSavedQueries_Handler, diff --git a/aiplatform/apiv1/aiplatformpb/deployed_index_ref.pb.go b/aiplatform/apiv1/aiplatformpb/deployed_index_ref.pb.go index fa0d1ec1f8f2..5ec7d9f75b31 100644 --- a/aiplatform/apiv1/aiplatformpb/deployed_index_ref.pb.go +++ b/aiplatform/apiv1/aiplatformpb/deployed_index_ref.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/deployed_index_ref.proto package aiplatformpb diff --git a/aiplatform/apiv1/aiplatformpb/deployed_model_ref.pb.go b/aiplatform/apiv1/aiplatformpb/deployed_model_ref.pb.go index 86e88feb8913..afd0195a7d77 100644 --- a/aiplatform/apiv1/aiplatformpb/deployed_model_ref.pb.go +++ b/aiplatform/apiv1/aiplatformpb/deployed_model_ref.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/deployed_model_ref.proto package aiplatformpb diff --git a/aiplatform/apiv1/aiplatformpb/encryption_spec.pb.go b/aiplatform/apiv1/aiplatformpb/encryption_spec.pb.go index 9d86c3c6660b..003400fd29fa 100644 --- a/aiplatform/apiv1/aiplatformpb/encryption_spec.pb.go +++ b/aiplatform/apiv1/aiplatformpb/encryption_spec.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/encryption_spec.proto package aiplatformpb diff --git a/aiplatform/apiv1/aiplatformpb/endpoint.pb.go b/aiplatform/apiv1/aiplatformpb/endpoint.pb.go index 11c452c3857a..5f384e4e6dd6 100644 --- a/aiplatform/apiv1/aiplatformpb/endpoint.pb.go +++ b/aiplatform/apiv1/aiplatformpb/endpoint.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/endpoint.proto package aiplatformpb @@ -261,7 +261,6 @@ type DeployedModel struct { // [Model.supported_deployment_resources_types][google.cloud.aiplatform.v1.Model.supported_deployment_resources_types]. // // Types that are assignable to PredictionResources: - // // *DeployedModel_DedicatedResources // *DeployedModel_AutomaticResources PredictionResources isDeployedModel_PredictionResources `protobuf_oneof:"prediction_resources"` diff --git a/aiplatform/apiv1/aiplatformpb/endpoint_service.pb.go b/aiplatform/apiv1/aiplatformpb/endpoint_service.pb.go index 169c8e96b4fa..42f554940613 100644 --- a/aiplatform/apiv1/aiplatformpb/endpoint_service.pb.go +++ b/aiplatform/apiv1/aiplatformpb/endpoint_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/endpoint_service.proto package aiplatformpb @@ -229,18 +229,18 @@ type ListEndpointsRequest struct { // Optional. An expression for filtering the results of the request. For field names // both snake_case and camelCase are supported. // - // - `endpoint` supports = and !=. `endpoint` represents the Endpoint ID, + // * `endpoint` supports = and !=. `endpoint` represents the Endpoint ID, // i.e. the last segment of the Endpoint's [resource name][google.cloud.aiplatform.v1.Endpoint.name]. - // - `display_name` supports = and, != - // - `labels` supports general map functions that is: - // - `labels.key=value` - key:value equality - // - `labels.key:* or labels:key - key existence - // - A key including a space must be quoted. `labels."a key"`. + // * `display_name` supports = and, != + // * `labels` supports general map functions that is: + // * `labels.key=value` - key:value equality + // * `labels.key:* or labels:key - key existence + // * A key including a space must be quoted. `labels."a key"`. // // Some examples: - // - `endpoint=1` - // - `displayName="myDisplayName"` - // - `labels.myKey="myValue"` + // * `endpoint=1` + // * `displayName="myDisplayName"` + // * `labels.myKey="myValue"` Filter string `protobuf:"bytes,2,opt,name=filter,proto3" json:"filter,omitempty"` // Optional. The standard list page size. PageSize int32 `protobuf:"varint,3,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"` @@ -254,9 +254,9 @@ type ListEndpointsRequest struct { // A comma-separated list of fields to order by, sorted in ascending order. // Use "desc" after a field name for descending. // Supported fields: - // - `display_name` - // - `create_time` - // - `update_time` + // * `display_name` + // * `create_time` + // * `update_time` // // Example: `display_name, create_time desc`. OrderBy string `protobuf:"bytes,6,opt,name=order_by,json=orderBy,proto3" json:"order_by,omitempty"` diff --git a/aiplatform/apiv1/aiplatformpb/entity_type.pb.go b/aiplatform/apiv1/aiplatformpb/entity_type.pb.go index 09778dbbec15..ea80d24f79dd 100644 --- a/aiplatform/apiv1/aiplatformpb/entity_type.pb.go +++ b/aiplatform/apiv1/aiplatformpb/entity_type.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/entity_type.proto package aiplatformpb diff --git a/aiplatform/apiv1/aiplatformpb/env_var.pb.go b/aiplatform/apiv1/aiplatformpb/env_var.pb.go index b700fac2ab6a..54b340864ac9 100644 --- a/aiplatform/apiv1/aiplatformpb/env_var.pb.go +++ b/aiplatform/apiv1/aiplatformpb/env_var.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/env_var.proto package aiplatformpb diff --git a/aiplatform/apiv1/aiplatformpb/event.pb.go b/aiplatform/apiv1/aiplatformpb/event.pb.go index 41121573a75c..c687675a4730 100644 --- a/aiplatform/apiv1/aiplatformpb/event.pb.go +++ b/aiplatform/apiv1/aiplatformpb/event.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/event.proto package aiplatformpb diff --git a/aiplatform/apiv1/aiplatformpb/execution.pb.go b/aiplatform/apiv1/aiplatformpb/execution.pb.go index c4d50cd6ea7a..7b11daceacc0 100644 --- a/aiplatform/apiv1/aiplatformpb/execution.pb.go +++ b/aiplatform/apiv1/aiplatformpb/execution.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/execution.proto package aiplatformpb diff --git a/aiplatform/apiv1/aiplatformpb/explanation.pb.go b/aiplatform/apiv1/aiplatformpb/explanation.pb.go index 05a03a354974..b8252e6a7990 100644 --- a/aiplatform/apiv1/aiplatformpb/explanation.pb.go +++ b/aiplatform/apiv1/aiplatformpb/explanation.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/explanation.proto package aiplatformpb @@ -264,13 +264,13 @@ type Attribution struct { // // The format of the value is determined by the feature's input format: // - // - If the feature is a scalar value, the attribution value is a + // * If the feature is a scalar value, the attribution value is a // [floating number][google.protobuf.Value.number_value]. // - // - If the feature is an array of scalar values, the attribution value is + // * If the feature is an array of scalar values, the attribution value is // an [array][google.protobuf.Value.list_value]. // - // - If the feature is a struct, the attribution value is a + // * If the feature is a struct, the attribution value is a // [struct][google.protobuf.Value.struct_value]. The keys in the // attribution value struct are the same as the keys in the feature // struct. The formats of the values in the attribution struct are @@ -524,7 +524,6 @@ type ExplanationParameters struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Method: - // // *ExplanationParameters_SampledShapleyAttribution // *ExplanationParameters_IntegratedGradientsAttribution // *ExplanationParameters_XraiAttribution @@ -899,7 +898,6 @@ type SmoothGradConfig struct { // prior to computing gradients. // // Types that are assignable to GradientNoiseSigma: - // // *SmoothGradConfig_NoiseSigma // *SmoothGradConfig_FeatureNoiseSigma GradientNoiseSigma isSmoothGradConfig_GradientNoiseSigma `protobuf_oneof:"GradientNoiseSigma"` diff --git a/aiplatform/apiv1/aiplatformpb/explanation_metadata.pb.go b/aiplatform/apiv1/aiplatformpb/explanation_metadata.pb.go index b1d549d17f7a..c02d569db971 100644 --- a/aiplatform/apiv1/aiplatformpb/explanation_metadata.pb.go +++ b/aiplatform/apiv1/aiplatformpb/explanation_metadata.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/explanation_metadata.proto package aiplatformpb @@ -86,12 +86,10 @@ const ( // ``` // input = ["This", "is", "a", "test", "."] // encoded = [[0.1, 0.2, 0.3, 0.4, 0.5], - // - // [0.2, 0.1, 0.4, 0.3, 0.5], - // [0.5, 0.1, 0.3, 0.5, 0.4], - // [0.5, 0.3, 0.1, 0.2, 0.4], - // [0.4, 0.3, 0.2, 0.5, 0.1]] - // + // [0.2, 0.1, 0.4, 0.3, 0.5], + // [0.5, 0.1, 0.3, 0.5, 0.4], + // [0.5, 0.3, 0.1, 0.2, 0.4], + // [0.4, 0.3, 0.2, 0.5, 0.1]] // ``` ExplanationMetadata_InputMetadata_CONCAT_EMBEDDING ExplanationMetadata_InputMetadata_Encoding = 6 ) @@ -704,7 +702,6 @@ type ExplanationMetadata_OutputMetadata struct { // [Attribution.output_display_name][google.cloud.aiplatform.v1.Attribution.output_display_name] will not be populated. // // Types that are assignable to DisplayNameMapping: - // // *ExplanationMetadata_OutputMetadata_IndexDisplayNameMapping // *ExplanationMetadata_OutputMetadata_DisplayNameMappingKey DisplayNameMapping isExplanationMetadata_OutputMetadata_DisplayNameMapping `protobuf_oneof:"display_name_mapping"` diff --git a/aiplatform/apiv1/aiplatformpb/feature.pb.go b/aiplatform/apiv1/aiplatformpb/feature.pb.go index d8e065451407..22f417cf7307 100644 --- a/aiplatform/apiv1/aiplatformpb/feature.pb.go +++ b/aiplatform/apiv1/aiplatformpb/feature.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/feature.proto package aiplatformpb diff --git a/aiplatform/apiv1/aiplatformpb/feature_monitoring_stats.pb.go b/aiplatform/apiv1/aiplatformpb/feature_monitoring_stats.pb.go index cdff42b8d70a..37a41699af09 100644 --- a/aiplatform/apiv1/aiplatformpb/feature_monitoring_stats.pb.go +++ b/aiplatform/apiv1/aiplatformpb/feature_monitoring_stats.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/feature_monitoring_stats.proto package aiplatformpb @@ -72,10 +72,10 @@ type FeatureStatsAnomaly struct { // (https://github.com/tensorflow/metadata/blob/master/tensorflow_metadata/proto/v0/anomalies.proto). AnomalyUri string `protobuf:"bytes,4,opt,name=anomaly_uri,json=anomalyUri,proto3" json:"anomaly_uri,omitempty"` // Deviation from the current stats to baseline stats. - // 1. For categorical feature, the distribution distance is calculated by - // L-inifinity norm. - // 2. For numerical feature, the distribution distance is calculated by - // Jensen–Shannon divergence. + // 1. For categorical feature, the distribution distance is calculated by + // L-inifinity norm. + // 2. For numerical feature, the distribution distance is calculated by + // Jensen–Shannon divergence. DistributionDeviation float64 `protobuf:"fixed64,5,opt,name=distribution_deviation,json=distributionDeviation,proto3" json:"distribution_deviation,omitempty"` // This is the threshold used when detecting anomalies. // The threshold can be changed by user, so this one might be different from diff --git a/aiplatform/apiv1/aiplatformpb/feature_selector.pb.go b/aiplatform/apiv1/aiplatformpb/feature_selector.pb.go index 1bddd05a49e8..751efb780d39 100644 --- a/aiplatform/apiv1/aiplatformpb/feature_selector.pb.go +++ b/aiplatform/apiv1/aiplatformpb/feature_selector.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/feature_selector.proto package aiplatformpb @@ -44,10 +44,10 @@ type IdMatcher struct { // Required. The following are accepted as `ids`: // - // - A single-element list containing only `*`, which selects all Features - // in the target EntityType, or - // - A list containing only Feature IDs, which selects only Features with - // those IDs in the target EntityType. + // * A single-element list containing only `*`, which selects all Features + // in the target EntityType, or + // * A list containing only Feature IDs, which selects only Features with + // those IDs in the target EntityType. Ids []string `protobuf:"bytes,1,rep,name=ids,proto3" json:"ids,omitempty"` } diff --git a/aiplatform/apiv1/aiplatformpb/featurestore.pb.go b/aiplatform/apiv1/aiplatformpb/featurestore.pb.go index 04a3b3368450..abde174ffc1e 100644 --- a/aiplatform/apiv1/aiplatformpb/featurestore.pb.go +++ b/aiplatform/apiv1/aiplatformpb/featurestore.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/featurestore.proto package aiplatformpb diff --git a/aiplatform/apiv1/aiplatformpb/featurestore_monitoring.pb.go b/aiplatform/apiv1/aiplatformpb/featurestore_monitoring.pb.go index 3dce959a7a75..84edf83a3e12 100644 --- a/aiplatform/apiv1/aiplatformpb/featurestore_monitoring.pb.go +++ b/aiplatform/apiv1/aiplatformpb/featurestore_monitoring.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/featurestore_monitoring.proto package aiplatformpb @@ -254,18 +254,14 @@ type FeaturestoreMonitoringConfig_SnapshotAnalysis struct { // The monitoring schedule for snapshot analysis. // For EntityType-level config: - // - // unset / disabled = true indicates disabled by - // default for Features under it; otherwise by default enable snapshot - // analysis monitoring with monitoring_interval for Features under it. - // + // unset / disabled = true indicates disabled by + // default for Features under it; otherwise by default enable snapshot + // analysis monitoring with monitoring_interval for Features under it. // Feature-level config: - // - // disabled = true indicates disabled regardless of the EntityType-level - // config; unset monitoring_interval indicates going with EntityType-level - // config; otherwise run snapshot analysis monitoring with - // monitoring_interval regardless of the EntityType-level config. - // + // disabled = true indicates disabled regardless of the EntityType-level + // config; unset monitoring_interval indicates going with EntityType-level + // config; otherwise run snapshot analysis monitoring with + // monitoring_interval regardless of the EntityType-level config. // Explicitly Disable the snapshot analysis based monitoring. Disabled bool `protobuf:"varint,1,opt,name=disabled,proto3" json:"disabled,omitempty"` // Configuration of the snapshot analysis based monitoring pipeline @@ -405,7 +401,6 @@ type FeaturestoreMonitoringConfig_ThresholdConfig struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Threshold: - // // *FeaturestoreMonitoringConfig_ThresholdConfig_Value Threshold isFeaturestoreMonitoringConfig_ThresholdConfig_Threshold `protobuf_oneof:"threshold"` } diff --git a/aiplatform/apiv1/aiplatformpb/featurestore_online_service.pb.go b/aiplatform/apiv1/aiplatformpb/featurestore_online_service.pb.go index e5c6383f8ebd..ba6853dd18c2 100644 --- a/aiplatform/apiv1/aiplatformpb/featurestore_online_service.pb.go +++ b/aiplatform/apiv1/aiplatformpb/featurestore_online_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/featurestore_online_service.proto package aiplatformpb @@ -423,7 +423,6 @@ type FeatureValue struct { // Value for the feature. // // Types that are assignable to Value: - // // *FeatureValue_BoolValue // *FeatureValue_DoubleValue // *FeatureValue_Int64Value @@ -844,7 +843,6 @@ type ReadFeatureValuesResponse_EntityView_Data struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Data: - // // *ReadFeatureValuesResponse_EntityView_Data_Value // *ReadFeatureValuesResponse_EntityView_Data_Values Data isReadFeatureValuesResponse_EntityView_Data_Data `protobuf_oneof:"data"` diff --git a/aiplatform/apiv1/aiplatformpb/featurestore_service.pb.go b/aiplatform/apiv1/aiplatformpb/featurestore_service.pb.go index 939fefe43c2c..004a8835aa30 100644 --- a/aiplatform/apiv1/aiplatformpb/featurestore_service.pb.go +++ b/aiplatform/apiv1/aiplatformpb/featurestore_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/featurestore_service.proto package aiplatformpb @@ -182,24 +182,20 @@ type ListFeaturestoresRequest struct { // // * `create_time`: Supports `=`, `!=`, `<`, `>`, `<=`, and `>=` comparisons. // Values must be - // - // in RFC 3339 format. - // + // in RFC 3339 format. // * `update_time`: Supports `=`, `!=`, `<`, `>`, `<=`, and `>=` comparisons. // Values must be - // - // in RFC 3339 format. - // + // in RFC 3339 format. // * `online_serving_config.fixed_node_count`: Supports `=`, `!=`, `<`, `>`, // `<=`, and `>=` comparisons. // * `labels`: Supports key-value equality and key presence. // // Examples: // - // - `create_time > "2020-01-01" OR update_time > "2020-01-01"` - // Featurestores created or updated after 2020-01-01. - // - `labels.env = "prod"` - // Featurestores with label "env" set to "prod". + // * `create_time > "2020-01-01" OR update_time > "2020-01-01"` + // Featurestores created or updated after 2020-01-01. + // * `labels.env = "prod"` + // Featurestores with label "env" set to "prod". Filter string `protobuf:"bytes,2,opt,name=filter,proto3" json:"filter,omitempty"` // The maximum number of Featurestores to return. The service may return fewer // than this value. If unspecified, at most 100 Featurestores will be @@ -218,9 +214,9 @@ type ListFeaturestoresRequest struct { // Use "desc" after a field name for descending. // Supported Fields: // - // - `create_time` - // - `update_time` - // - `online_serving_config.fixed_node_count` + // * `create_time` + // * `update_time` + // * `online_serving_config.fixed_node_count` OrderBy string `protobuf:"bytes,5,opt,name=order_by,json=orderBy,proto3" json:"order_by,omitempty"` // Mask specifying which fields to read. ReadMask *fieldmaskpb.FieldMask `protobuf:"bytes,6,opt,name=read_mask,json=readMask,proto3" json:"read_mask,omitempty"` @@ -381,9 +377,9 @@ type UpdateFeaturestoreRequest struct { // // Updatable fields: // - // - `labels` - // - `online_serving_config.fixed_node_count` - // - `online_serving_config.scaling` + // * `labels` + // * `online_serving_config.fixed_node_count` + // * `online_serving_config.scaling` UpdateMask *fieldmaskpb.FieldMask `protobuf:"bytes,2,opt,name=update_mask,json=updateMask,proto3" json:"update_mask,omitempty"` } @@ -505,7 +501,6 @@ type ImportFeatureValuesRequest struct { // the format. // // Types that are assignable to Source: - // // *ImportFeatureValuesRequest_AvroSource // *ImportFeatureValuesRequest_BigquerySource // *ImportFeatureValuesRequest_CsvSource @@ -514,7 +509,6 @@ type ImportFeatureValuesRequest struct { // Timestamps must be millisecond-aligned. // // Types that are assignable to FeatureTimeSource: - // // *ImportFeatureValuesRequest_FeatureTimeField // *ImportFeatureValuesRequest_FeatureTime FeatureTimeSource isImportFeatureValuesRequest_FeatureTimeSource `protobuf_oneof:"feature_time_source"` @@ -798,7 +792,6 @@ type BatchReadFeatureValuesRequest struct { unknownFields protoimpl.UnknownFields // Types that are assignable to ReadOption: - // // *BatchReadFeatureValuesRequest_CsvReadInstances // *BatchReadFeatureValuesRequest_BigqueryReadInstances ReadOption isBatchReadFeatureValuesRequest_ReadOption `protobuf_oneof:"read_option"` @@ -939,8 +932,7 @@ type BatchReadFeatureValuesRequest_CsvReadInstances struct { // // `csv_read_instances` are read instances stored in a plain-text CSV file. // The header should be: - // - // [ENTITY_TYPE_ID1], [ENTITY_TYPE_ID2], ..., timestamp + // [ENTITY_TYPE_ID1], [ENTITY_TYPE_ID2], ..., timestamp // // The columns can be in any order. // @@ -968,7 +960,6 @@ type ExportFeatureValuesRequest struct { // Required. The mode in which Feature values are exported. // // Types that are assignable to Mode: - // // *ExportFeatureValuesRequest_SnapshotExport_ // *ExportFeatureValuesRequest_FullExport_ Mode isExportFeatureValuesRequest_Mode `protobuf_oneof:"mode"` @@ -1150,7 +1141,6 @@ type FeatureValueDestination struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Destination: - // // *FeatureValueDestination_BigqueryDestination // *FeatureValueDestination_TfrecordDestination // *FeatureValueDestination_CsvDestination @@ -1234,12 +1224,12 @@ type FeatureValueDestination_TfrecordDestination struct { // Below are the mapping from Feature value type // in Featurestore to Feature value type in TFRecord: // - // Value type in Featurestore | Value type in TFRecord - // DOUBLE, DOUBLE_ARRAY | FLOAT_LIST - // INT64, INT64_ARRAY | INT64_LIST - // STRING, STRING_ARRAY, BYTES | BYTES_LIST - // true -> byte_string("true"), false -> byte_string("false") - // BOOL, BOOL_ARRAY (true, false) | BYTES_LIST + // Value type in Featurestore | Value type in TFRecord + // DOUBLE, DOUBLE_ARRAY | FLOAT_LIST + // INT64, INT64_ARRAY | INT64_LIST + // STRING, STRING_ARRAY, BYTES | BYTES_LIST + // true -> byte_string("true"), false -> byte_string("false") + // BOOL, BOOL_ARRAY (true, false) | BYTES_LIST TfrecordDestination *TFRecordDestination `protobuf:"bytes,2,opt,name=tfrecord_destination,json=tfrecordDestination,proto3,oneof"` } @@ -1480,13 +1470,13 @@ type ListEntityTypesRequest struct { // // Examples: // - // - `create_time > \"2020-01-31T15:30:00.000000Z\" OR - // update_time > \"2020-01-31T15:30:00.000000Z\"` --> EntityTypes created - // or updated after 2020-01-31T15:30:00.000000Z. - // - `labels.active = yes AND labels.env = prod` --> EntityTypes having both + // * `create_time > \"2020-01-31T15:30:00.000000Z\" OR + // update_time > \"2020-01-31T15:30:00.000000Z\"` --> EntityTypes created + // or updated after 2020-01-31T15:30:00.000000Z. + // * `labels.active = yes AND labels.env = prod` --> EntityTypes having both // (active: yes) and (env: prod) labels. - // - `labels.env: *` --> Any EntityType which has a label with 'env' as the - // key. + // * `labels.env: *` --> Any EntityType which has a label with 'env' as the + // key. Filter string `protobuf:"bytes,2,opt,name=filter,proto3" json:"filter,omitempty"` // The maximum number of EntityTypes to return. The service may return fewer // than this value. If unspecified, at most 1000 EntityTypes will be returned. @@ -1506,9 +1496,9 @@ type ListEntityTypesRequest struct { // // Supported fields: // - // - `entity_type_id` - // - `create_time` - // - `update_time` + // * `entity_type_id` + // * `create_time` + // * `update_time` OrderBy string `protobuf:"bytes,5,opt,name=order_by,json=orderBy,proto3" json:"order_by,omitempty"` // Mask specifying which fields to read. ReadMask *fieldmaskpb.FieldMask `protobuf:"bytes,6,opt,name=read_mask,json=readMask,proto3" json:"read_mask,omitempty"` @@ -1669,15 +1659,15 @@ type UpdateEntityTypeRequest struct { // // Updatable fields: // - // - `description` - // - `labels` - // - `monitoring_config.snapshot_analysis.disabled` - // - `monitoring_config.snapshot_analysis.monitoring_interval_days` - // - `monitoring_config.snapshot_analysis.staleness_days` - // - `monitoring_config.import_features_analysis.state` - // - `monitoring_config.import_features_analysis.anomaly_detection_baseline` - // - `monitoring_config.numerical_threshold_config.value` - // - `monitoring_config.categorical_threshold_config.value` + // * `description` + // * `labels` + // * `monitoring_config.snapshot_analysis.disabled` + // * `monitoring_config.snapshot_analysis.monitoring_interval_days` + // * `monitoring_config.snapshot_analysis.staleness_days` + // * `monitoring_config.import_features_analysis.state` + // * `monitoring_config.import_features_analysis.anomaly_detection_baseline` + // * `monitoring_config.numerical_threshold_config.value` + // * `monitoring_config.categorical_threshold_config.value` UpdateMask *fieldmaskpb.FieldMask `protobuf:"bytes,2,opt,name=update_mask,json=updateMask,proto3" json:"update_mask,omitempty"` } @@ -2048,14 +2038,14 @@ type ListFeaturesRequest struct { // // Examples: // - // - `value_type = DOUBLE` --> Features whose type is DOUBLE. - // - `create_time > \"2020-01-31T15:30:00.000000Z\" OR - // update_time > \"2020-01-31T15:30:00.000000Z\"` --> EntityTypes created - // or updated after 2020-01-31T15:30:00.000000Z. - // - `labels.active = yes AND labels.env = prod` --> Features having both + // * `value_type = DOUBLE` --> Features whose type is DOUBLE. + // * `create_time > \"2020-01-31T15:30:00.000000Z\" OR + // update_time > \"2020-01-31T15:30:00.000000Z\"` --> EntityTypes created + // or updated after 2020-01-31T15:30:00.000000Z. + // * `labels.active = yes AND labels.env = prod` --> Features having both // (active: yes) and (env: prod) labels. - // - `labels.env: *` --> Any Feature which has a label with 'env' as the - // key. + // * `labels.env: *` --> Any Feature which has a label with 'env' as the + // key. Filter string `protobuf:"bytes,2,opt,name=filter,proto3" json:"filter,omitempty"` // The maximum number of Features to return. The service may return fewer // than this value. If unspecified, at most 1000 Features will be returned. @@ -2074,10 +2064,10 @@ type ListFeaturesRequest struct { // Use "desc" after a field name for descending. // Supported fields: // - // - `feature_id` - // - `value_type` - // - `create_time` - // - `update_time` + // * `feature_id` + // * `value_type` + // * `create_time` + // * `update_time` OrderBy string `protobuf:"bytes,5,opt,name=order_by,json=orderBy,proto3" json:"order_by,omitempty"` // Mask specifying which fields to read. ReadMask *fieldmaskpb.FieldMask `protobuf:"bytes,6,opt,name=read_mask,json=readMask,proto3" json:"read_mask,omitempty"` @@ -2248,13 +2238,13 @@ type SearchFeaturesRequest struct { // and the FIELD are converted to a sequence of words (i.e. tokens) for // comparison. This is done by: // - // - Removing leading/trailing whitespace and tokenizing the search value. - // Characters that are not one of alphanumeric `[a-zA-Z0-9]`, underscore - // `_`, or asterisk `*` are treated as delimiters for tokens. `*` is treated - // as a wildcard that matches characters within a token. - // - Ignoring case. - // - Prepending an asterisk to the first and appending an asterisk to the - // last token in QUERY. + // * Removing leading/trailing whitespace and tokenizing the search value. + // Characters that are not one of alphanumeric `[a-zA-Z0-9]`, underscore + // `_`, or asterisk `*` are treated as delimiters for tokens. `*` is treated + // as a wildcard that matches characters within a token. + // * Ignoring case. + // * Prepending an asterisk to the first and appending an asterisk to the + // last token in QUERY. // // A QUERY must be either a singular token or a phrase. A phrase is one or // multiple words enclosed in double quotation marks ("). With phrases, the @@ -2277,6 +2267,7 @@ type SearchFeaturesRequest struct { // containing the substring `foo` and description containing the substring // `bar`. // + // // Besides field queries, the following exact-match filters are // supported. The exact-match filters do not support wildcards. Unlike // field-restricted queries, exact-match filters are case-sensitive. @@ -2292,11 +2283,11 @@ type SearchFeaturesRequest struct { // Examples: // * `description = "foo bar"` --> Any Feature with description exactly equal // to `foo bar` - // - `value_type = DOUBLE` --> Features whose type is DOUBLE. - // - `labels.active = yes AND labels.env = prod` --> Features having both + // * `value_type = DOUBLE` --> Features whose type is DOUBLE. + // * `labels.active = yes AND labels.env = prod` --> Features having both // (active: yes) and (env: prod) labels. - // - `labels.env: *` --> Any Feature which has a label with `env` as the - // key. + // * `labels.env: *` --> Any Feature which has a label with `env` as the + // key. Query string `protobuf:"bytes,3,opt,name=query,proto3" json:"query,omitempty"` // The maximum number of Features to return. The service may return fewer // than this value. If unspecified, at most 100 Features will be returned. @@ -2383,11 +2374,11 @@ type SearchFeaturesResponse struct { // // Fields returned: // - // - `name` - // - `description` - // - `labels` - // - `create_time` - // - `update_time` + // * `name` + // * `description` + // * `labels` + // * `create_time` + // * `update_time` Features []*Feature `protobuf:"bytes,1,rep,name=features,proto3" json:"features,omitempty"` // A token, which can be sent as [SearchFeaturesRequest.page_token][google.cloud.aiplatform.v1.SearchFeaturesRequest.page_token] to // retrieve the next page. @@ -2462,9 +2453,9 @@ type UpdateFeatureRequest struct { // // Updatable fields: // - // - `description` - // - `labels` - // - `disable_monitoring` + // * `description` + // * `labels` + // * `disable_monitoring` UpdateMask *fieldmaskpb.FieldMask `protobuf:"bytes,2,opt,name=update_mask,json=updateMask,proto3" json:"update_mask,omitempty"` } @@ -5014,13 +5005,13 @@ type FeaturestoreServiceClient interface { // // There are also scenarios where the caller can cause inconsistency. // - // - Source data for import contains multiple distinct Feature values for - // the same entity ID and timestamp. - // - Source is modified during an import. This includes adding, updating, or - // removing source data and/or metadata. Examples of updating metadata - // include but are not limited to changing storage location, storage class, - // or retention policy. - // - Online serving cluster is under-provisioned. + // - Source data for import contains multiple distinct Feature values for + // the same entity ID and timestamp. + // - Source is modified during an import. This includes adding, updating, or + // removing source data and/or metadata. Examples of updating metadata + // include but are not limited to changing storage location, storage class, + // or retention policy. + // - Online serving cluster is under-provisioned. ImportFeatureValues(ctx context.Context, in *ImportFeatureValuesRequest, opts ...grpc.CallOption) (*longrunning.Operation, error) // Batch reads Feature values from a Featurestore. // @@ -5272,13 +5263,13 @@ type FeaturestoreServiceServer interface { // // There are also scenarios where the caller can cause inconsistency. // - // - Source data for import contains multiple distinct Feature values for - // the same entity ID and timestamp. - // - Source is modified during an import. This includes adding, updating, or - // removing source data and/or metadata. Examples of updating metadata - // include but are not limited to changing storage location, storage class, - // or retention policy. - // - Online serving cluster is under-provisioned. + // - Source data for import contains multiple distinct Feature values for + // the same entity ID and timestamp. + // - Source is modified during an import. This includes adding, updating, or + // removing source data and/or metadata. Examples of updating metadata + // include but are not limited to changing storage location, storage class, + // or retention policy. + // - Online serving cluster is under-provisioned. ImportFeatureValues(context.Context, *ImportFeatureValuesRequest) (*longrunning.Operation, error) // Batch reads Feature values from a Featurestore. // diff --git a/aiplatform/apiv1/aiplatformpb/hyperparameter_tuning_job.pb.go b/aiplatform/apiv1/aiplatformpb/hyperparameter_tuning_job.pb.go index 3190607dca82..9fe18980cb30 100644 --- a/aiplatform/apiv1/aiplatformpb/hyperparameter_tuning_job.pb.go +++ b/aiplatform/apiv1/aiplatformpb/hyperparameter_tuning_job.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/hyperparameter_tuning_job.proto package aiplatformpb diff --git a/aiplatform/apiv1/aiplatformpb/index.pb.go b/aiplatform/apiv1/aiplatformpb/index.pb.go index 01db3b24c346..7cf1c87afaa1 100644 --- a/aiplatform/apiv1/aiplatformpb/index.pb.go +++ b/aiplatform/apiv1/aiplatformpb/index.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/index.proto package aiplatformpb diff --git a/aiplatform/apiv1/aiplatformpb/index_endpoint.pb.go b/aiplatform/apiv1/aiplatformpb/index_endpoint.pb.go index c71811d6bbf3..9dbe6d6c54e7 100644 --- a/aiplatform/apiv1/aiplatformpb/index_endpoint.pb.go +++ b/aiplatform/apiv1/aiplatformpb/index_endpoint.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/index_endpoint.proto package aiplatformpb diff --git a/aiplatform/apiv1/aiplatformpb/index_endpoint_service.pb.go b/aiplatform/apiv1/aiplatformpb/index_endpoint_service.pb.go index 97225668c12c..8082229bd37f 100644 --- a/aiplatform/apiv1/aiplatformpb/index_endpoint_service.pb.go +++ b/aiplatform/apiv1/aiplatformpb/index_endpoint_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/index_endpoint_service.proto package aiplatformpb @@ -214,21 +214,21 @@ type ListIndexEndpointsRequest struct { // Optional. An expression for filtering the results of the request. For field names // both snake_case and camelCase are supported. // - // - `index_endpoint` supports = and !=. `index_endpoint` represents the - // IndexEndpoint ID, ie. the last segment of the IndexEndpoint's - // [resourcename][google.cloud.aiplatform.v1.IndexEndpoint.name]. - // - `display_name` supports =, != and regex() - // (uses [re2](https://github.com/google/re2/wiki/Syntax) syntax) - // - `labels` supports general map functions that is: - // `labels.key=value` - key:value equality - // `labels.key:* or labels:key - key existence - // A key including a space must be quoted. `labels."a key"`. + // * `index_endpoint` supports = and !=. `index_endpoint` represents the + // IndexEndpoint ID, ie. the last segment of the IndexEndpoint's + // [resourcename][google.cloud.aiplatform.v1.IndexEndpoint.name]. + // * `display_name` supports =, != and regex() + // (uses [re2](https://github.com/google/re2/wiki/Syntax) syntax) + // * `labels` supports general map functions that is: + // `labels.key=value` - key:value equality + // `labels.key:* or labels:key - key existence + // A key including a space must be quoted. `labels."a key"`. // // Some examples: - // - `index_endpoint="1"` - // - `display_name="myDisplayName"` - // - `regex(display_name, "^A") -> The display name starts with an A. - // - `labels.myKey="myValue"` + // * `index_endpoint="1"` + // * `display_name="myDisplayName"` + // * `regex(display_name, "^A") -> The display name starts with an A. + // * `labels.myKey="myValue"` Filter string `protobuf:"bytes,2,opt,name=filter,proto3" json:"filter,omitempty"` // Optional. The standard list page size. PageSize int32 `protobuf:"varint,3,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"` diff --git a/aiplatform/apiv1/aiplatformpb/index_service.pb.go b/aiplatform/apiv1/aiplatformpb/index_service.pb.go index b6c546a1d5a1..8198b01c8a68 100644 --- a/aiplatform/apiv1/aiplatformpb/index_service.pb.go +++ b/aiplatform/apiv1/aiplatformpb/index_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/index_service.proto package aiplatformpb diff --git a/aiplatform/apiv1/aiplatformpb/io.pb.go b/aiplatform/apiv1/aiplatformpb/io.pb.go index 3f5f0f812fad..1f3d1152dc3f 100644 --- a/aiplatform/apiv1/aiplatformpb/io.pb.go +++ b/aiplatform/apiv1/aiplatformpb/io.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/io.proto package aiplatformpb @@ -455,11 +455,11 @@ type ContainerRegistryDestination struct { // Only Google Container Registry and Artifact Registry are supported now. // Accepted forms: // - // - Google Container Registry path. For example: - // `gcr.io/projectId/imageName:tag`. + // * Google Container Registry path. For example: + // `gcr.io/projectId/imageName:tag`. // - // - Artifact Registry path. For example: - // `us-central1-docker.pkg.dev/projectId/repoName/imageName:tag`. + // * Artifact Registry path. For example: + // `us-central1-docker.pkg.dev/projectId/repoName/imageName:tag`. // // If a tag is not specified, "latest" will be used as the default tag. OutputUri string `protobuf:"bytes,1,opt,name=output_uri,json=outputUri,proto3" json:"output_uri,omitempty"` diff --git a/aiplatform/apiv1/aiplatformpb/job_service.pb.go b/aiplatform/apiv1/aiplatformpb/job_service.pb.go index 57b56dc8d208..2d700bdb809c 100644 --- a/aiplatform/apiv1/aiplatformpb/job_service.pb.go +++ b/aiplatform/apiv1/aiplatformpb/job_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/job_service.proto package aiplatformpb @@ -167,22 +167,22 @@ type ListCustomJobsRequest struct { // // Supported fields: // - // - `display_name` supports `=`, `!=` comparisons, and `:` wildcard. - // - `state` supports `=`, `!=` comparisons. - // - `create_time` supports `=`, `!=`,`<`, `<=`,`>`, `>=` comparisons. + // * `display_name` supports `=`, `!=` comparisons, and `:` wildcard. + // * `state` supports `=`, `!=` comparisons. + // * `create_time` supports `=`, `!=`,`<`, `<=`,`>`, `>=` comparisons. // `create_time` must be in RFC 3339 format. - // - `labels` supports general map functions that is: + // * `labels` supports general map functions that is: // `labels.key=value` - key:value equality // `labels.key:* - key existence // // Some examples of using the filter are: // - // - `state="JOB_STATE_SUCCEEDED" AND display_name:"my_job_*"` - // - `state!="JOB_STATE_FAILED" OR display_name="my_job"` - // - `NOT display_name="my_job"` - // - `create_time>"2021-05-18T00:00:00Z"` - // - `labels.keyA=valueA` - // - `labels.keyB:*` + // * `state="JOB_STATE_SUCCEEDED" AND display_name:"my_job_*"` + // * `state!="JOB_STATE_FAILED" OR display_name="my_job"` + // * `NOT display_name="my_job"` + // * `create_time>"2021-05-18T00:00:00Z"` + // * `labels.keyA=valueA` + // * `labels.keyB:*` Filter string `protobuf:"bytes,2,opt,name=filter,proto3" json:"filter,omitempty"` // The standard list page size. PageSize int32 `protobuf:"varint,3,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"` @@ -546,22 +546,22 @@ type ListDataLabelingJobsRequest struct { // // Supported fields: // - // - `display_name` supports `=`, `!=` comparisons, and `:` wildcard. - // - `state` supports `=`, `!=` comparisons. - // - `create_time` supports `=`, `!=`,`<`, `<=`,`>`, `>=` comparisons. + // * `display_name` supports `=`, `!=` comparisons, and `:` wildcard. + // * `state` supports `=`, `!=` comparisons. + // * `create_time` supports `=`, `!=`,`<`, `<=`,`>`, `>=` comparisons. // `create_time` must be in RFC 3339 format. - // - `labels` supports general map functions that is: + // * `labels` supports general map functions that is: // `labels.key=value` - key:value equality // `labels.key:* - key existence // // Some examples of using the filter are: // - // - `state="JOB_STATE_SUCCEEDED" AND display_name:"my_job_*"` - // - `state!="JOB_STATE_FAILED" OR display_name="my_job"` - // - `NOT display_name="my_job"` - // - `create_time>"2021-05-18T00:00:00Z"` - // - `labels.keyA=valueA` - // - `labels.keyB:*` + // * `state="JOB_STATE_SUCCEEDED" AND display_name:"my_job_*"` + // * `state!="JOB_STATE_FAILED" OR display_name="my_job"` + // * `NOT display_name="my_job"` + // * `create_time>"2021-05-18T00:00:00Z"` + // * `labels.keyA=valueA` + // * `labels.keyB:*` Filter string `protobuf:"bytes,2,opt,name=filter,proto3" json:"filter,omitempty"` // The standard list page size. PageSize int32 `protobuf:"varint,3,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"` @@ -936,22 +936,22 @@ type ListHyperparameterTuningJobsRequest struct { // // Supported fields: // - // - `display_name` supports `=`, `!=` comparisons, and `:` wildcard. - // - `state` supports `=`, `!=` comparisons. - // - `create_time` supports `=`, `!=`,`<`, `<=`,`>`, `>=` comparisons. + // * `display_name` supports `=`, `!=` comparisons, and `:` wildcard. + // * `state` supports `=`, `!=` comparisons. + // * `create_time` supports `=`, `!=`,`<`, `<=`,`>`, `>=` comparisons. // `create_time` must be in RFC 3339 format. - // - `labels` supports general map functions that is: + // * `labels` supports general map functions that is: // `labels.key=value` - key:value equality // `labels.key:* - key existence // // Some examples of using the filter are: // - // - `state="JOB_STATE_SUCCEEDED" AND display_name:"my_job_*"` - // - `state!="JOB_STATE_FAILED" OR display_name="my_job"` - // - `NOT display_name="my_job"` - // - `create_time>"2021-05-18T00:00:00Z"` - // - `labels.keyA=valueA` - // - `labels.keyB:*` + // * `state="JOB_STATE_SUCCEEDED" AND display_name:"my_job_*"` + // * `state!="JOB_STATE_FAILED" OR display_name="my_job"` + // * `NOT display_name="my_job"` + // * `create_time>"2021-05-18T00:00:00Z"` + // * `labels.keyA=valueA` + // * `labels.keyB:*` Filter string `protobuf:"bytes,2,opt,name=filter,proto3" json:"filter,omitempty"` // The standard list page size. PageSize int32 `protobuf:"varint,3,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"` @@ -1317,23 +1317,23 @@ type ListBatchPredictionJobsRequest struct { // // Supported fields: // - // - `display_name` supports `=`, `!=` comparisons, and `:` wildcard. - // - `model_display_name` supports `=`, `!=` comparisons. - // - `state` supports `=`, `!=` comparisons. - // - `create_time` supports `=`, `!=`,`<`, `<=`,`>`, `>=` comparisons. + // * `display_name` supports `=`, `!=` comparisons, and `:` wildcard. + // * `model_display_name` supports `=`, `!=` comparisons. + // * `state` supports `=`, `!=` comparisons. + // * `create_time` supports `=`, `!=`,`<`, `<=`,`>`, `>=` comparisons. // `create_time` must be in RFC 3339 format. - // - `labels` supports general map functions that is: + // * `labels` supports general map functions that is: // `labels.key=value` - key:value equality // `labels.key:* - key existence // // Some examples of using the filter are: // - // - `state="JOB_STATE_SUCCEEDED" AND display_name:"my_job_*"` - // - `state!="JOB_STATE_FAILED" OR display_name="my_job"` - // - `NOT display_name="my_job"` - // - `create_time>"2021-05-18T00:00:00Z"` - // - `labels.keyA=valueA` - // - `labels.keyB:*` + // * `state="JOB_STATE_SUCCEEDED" AND display_name:"my_job_*"` + // * `state!="JOB_STATE_FAILED" OR display_name="my_job"` + // * `NOT display_name="my_job"` + // * `create_time>"2021-05-18T00:00:00Z"` + // * `labels.keyA=valueA` + // * `labels.keyB:*` Filter string `protobuf:"bytes,2,opt,name=filter,proto3" json:"filter,omitempty"` // The standard list page size. PageSize int32 `protobuf:"varint,3,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"` @@ -1888,22 +1888,22 @@ type ListModelDeploymentMonitoringJobsRequest struct { // // Supported fields: // - // - `display_name` supports `=`, `!=` comparisons, and `:` wildcard. - // - `state` supports `=`, `!=` comparisons. - // - `create_time` supports `=`, `!=`,`<`, `<=`,`>`, `>=` comparisons. + // * `display_name` supports `=`, `!=` comparisons, and `:` wildcard. + // * `state` supports `=`, `!=` comparisons. + // * `create_time` supports `=`, `!=`,`<`, `<=`,`>`, `>=` comparisons. // `create_time` must be in RFC 3339 format. - // - `labels` supports general map functions that is: + // * `labels` supports general map functions that is: // `labels.key=value` - key:value equality // `labels.key:* - key existence // // Some examples of using the filter are: // - // - `state="JOB_STATE_SUCCEEDED" AND display_name:"my_job_*"` - // - `state!="JOB_STATE_FAILED" OR display_name="my_job"` - // - `NOT display_name="my_job"` - // - `create_time>"2021-05-18T00:00:00Z"` - // - `labels.keyA=valueA` - // - `labels.keyB:*` + // * `state="JOB_STATE_SUCCEEDED" AND display_name:"my_job_*"` + // * `state!="JOB_STATE_FAILED" OR display_name="my_job"` + // * `NOT display_name="my_job"` + // * `create_time>"2021-05-18T00:00:00Z"` + // * `labels.keyA=valueA` + // * `labels.keyB:*` Filter string `protobuf:"bytes,2,opt,name=filter,proto3" json:"filter,omitempty"` // The standard list page size. PageSize int32 `protobuf:"varint,3,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"` @@ -2064,21 +2064,19 @@ type UpdateModelDeploymentMonitoringJobRequest struct { // // Updatable fields: // - // - `display_name` - // - `model_deployment_monitoring_schedule_config` - // - `model_monitoring_alert_config` - // - `logging_sampling_strategy` - // - `labels` - // - `log_ttl` - // - `enable_monitoring_pipeline_logs` - // + // * `display_name` + // * `model_deployment_monitoring_schedule_config` + // * `model_monitoring_alert_config` + // * `logging_sampling_strategy` + // * `labels` + // * `log_ttl` + // * `enable_monitoring_pipeline_logs` // . and - // - `model_deployment_monitoring_objective_configs` - // + // * `model_deployment_monitoring_objective_configs` // . or - // - `model_deployment_monitoring_objective_configs.objective_config.training_dataset` - // - `model_deployment_monitoring_objective_configs.objective_config.training_prediction_skew_detection_config` - // - `model_deployment_monitoring_objective_configs.objective_config.prediction_drift_detection_config` + // * `model_deployment_monitoring_objective_configs.objective_config.training_dataset` + // * `model_deployment_monitoring_objective_configs.objective_config.training_prediction_skew_detection_config` + // * `model_deployment_monitoring_objective_configs.objective_config.prediction_drift_detection_config` UpdateMask *fieldmaskpb.FieldMask `protobuf:"bytes,2,opt,name=update_mask,json=updateMask,proto3" json:"update_mask,omitempty"` } diff --git a/aiplatform/apiv1/aiplatformpb/job_state.pb.go b/aiplatform/apiv1/aiplatformpb/job_state.pb.go index 6483f0dc55cd..942f9c4f9873 100644 --- a/aiplatform/apiv1/aiplatformpb/job_state.pb.go +++ b/aiplatform/apiv1/aiplatformpb/job_state.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/job_state.proto package aiplatformpb diff --git a/aiplatform/apiv1/aiplatformpb/lineage_subgraph.pb.go b/aiplatform/apiv1/aiplatformpb/lineage_subgraph.pb.go index 53e8bd8fc20a..2f14f9a60d87 100644 --- a/aiplatform/apiv1/aiplatformpb/lineage_subgraph.pb.go +++ b/aiplatform/apiv1/aiplatformpb/lineage_subgraph.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/lineage_subgraph.proto package aiplatformpb diff --git a/aiplatform/apiv1/aiplatformpb/machine_resources.pb.go b/aiplatform/apiv1/aiplatformpb/machine_resources.pb.go index 186dda766bc2..990f2181cef8 100644 --- a/aiplatform/apiv1/aiplatformpb/machine_resources.pb.go +++ b/aiplatform/apiv1/aiplatformpb/machine_resources.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/machine_resources.proto package aiplatformpb diff --git a/aiplatform/apiv1/aiplatformpb/manual_batch_tuning_parameters.pb.go b/aiplatform/apiv1/aiplatformpb/manual_batch_tuning_parameters.pb.go index 036e83026009..0b86fa7f67f2 100644 --- a/aiplatform/apiv1/aiplatformpb/manual_batch_tuning_parameters.pb.go +++ b/aiplatform/apiv1/aiplatformpb/manual_batch_tuning_parameters.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/manual_batch_tuning_parameters.proto package aiplatformpb diff --git a/aiplatform/apiv1/aiplatformpb/metadata_schema.pb.go b/aiplatform/apiv1/aiplatformpb/metadata_schema.pb.go index 2806d4a7036c..29694dfbb777 100644 --- a/aiplatform/apiv1/aiplatformpb/metadata_schema.pb.go +++ b/aiplatform/apiv1/aiplatformpb/metadata_schema.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/metadata_schema.proto package aiplatformpb diff --git a/aiplatform/apiv1/aiplatformpb/metadata_service.pb.go b/aiplatform/apiv1/aiplatformpb/metadata_service.pb.go index 493fbba0f487..ae23f6d24e5b 100644 --- a/aiplatform/apiv1/aiplatformpb/metadata_service.pb.go +++ b/aiplatform/apiv1/aiplatformpb/metadata_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/metadata_service.proto package aiplatformpb @@ -619,18 +619,18 @@ type ListArtifactsRequest struct { // The syntax to define filter query is based on https://google.aip.dev/160. // The supported set of filters include the following: // - // - **Attribute filtering**: + // * **Attribute filtering**: // For example: `display_name = "test"`. // Supported fields include: `name`, `display_name`, `uri`, `state`, // `schema_title`, `create_time`, and `update_time`. // Time fields, such as `create_time` and `update_time`, require values // specified in RFC-3339 format. // For example: `create_time = "2020-11-19T11:30:00-04:00"` - // - **Metadata field**: + // * **Metadata field**: // To filter on metadata fields use traversal operation as follows: // `metadata..`. // For example: `metadata.field_1.number_value = 10.0` - // - **Context based filtering**: + // * **Context based filtering**: // To filter Artifacts based on the contexts to which they belong, use the // function operator with the full resource name // `in_context()`. @@ -1248,29 +1248,27 @@ type ListContextsRequest struct { // The syntax to define filter query is based on https://google.aip.dev/160. // Following are the supported set of filters: // - // - **Attribute filtering**: - // For example: `display_name = "test"`. - // Supported fields include: `name`, `display_name`, `schema_title`, - // `create_time`, and `update_time`. - // Time fields, such as `create_time` and `update_time`, require values - // specified in RFC-3339 format. - // For example: `create_time = "2020-11-19T11:30:00-04:00"`. - // - // - **Metadata field**: - // To filter on metadata fields use traversal operation as follows: - // `metadata..`. - // For example: `metadata.field_1.number_value = 10.0`. + // * **Attribute filtering**: + // For example: `display_name = "test"`. + // Supported fields include: `name`, `display_name`, `schema_title`, + // `create_time`, and `update_time`. + // Time fields, such as `create_time` and `update_time`, require values + // specified in RFC-3339 format. + // For example: `create_time = "2020-11-19T11:30:00-04:00"`. + // * **Metadata field**: + // To filter on metadata fields use traversal operation as follows: + // `metadata..`. + // For example: `metadata.field_1.number_value = 10.0`. + // * **Parent Child filtering**: + // To filter Contexts based on parent-child relationship use the HAS + // operator as follows: // - // - **Parent Child filtering**: - // To filter Contexts based on parent-child relationship use the HAS - // operator as follows: - // - // ``` - // parent_contexts: - // "projects//locations//metadataStores//contexts/" - // child_contexts: - // "projects//locations//metadataStores//contexts/" - // ``` + // ``` + // parent_contexts: + // "projects//locations//metadataStores//contexts/" + // child_contexts: + // "projects//locations//metadataStores//contexts/" + // ``` // // Each of the above supported filters can be combined together using // logical operators (`AND` & `OR`). Maximum nested expression depth allowed @@ -2267,23 +2265,23 @@ type ListExecutionsRequest struct { // The syntax to define filter query is based on https://google.aip.dev/160. // Following are the supported set of filters: // - // - **Attribute filtering**: - // For example: `display_name = "test"`. - // Supported fields include: `name`, `display_name`, `state`, - // `schema_title`, `create_time`, and `update_time`. - // Time fields, such as `create_time` and `update_time`, require values - // specified in RFC-3339 format. - // For example: `create_time = "2020-11-19T11:30:00-04:00"`. - // - **Metadata field**: - // To filter on metadata fields use traversal operation as follows: - // `metadata..` - // For example: `metadata.field_1.number_value = 10.0` - // - **Context based filtering**: - // To filter Executions based on the contexts to which they belong use - // the function operator with the full resource name: - // `in_context()`. - // For example: - // `in_context("projects//locations//metadataStores//contexts/")` + // * **Attribute filtering**: + // For example: `display_name = "test"`. + // Supported fields include: `name`, `display_name`, `state`, + // `schema_title`, `create_time`, and `update_time`. + // Time fields, such as `create_time` and `update_time`, require values + // specified in RFC-3339 format. + // For example: `create_time = "2020-11-19T11:30:00-04:00"`. + // * **Metadata field**: + // To filter on metadata fields use traversal operation as follows: + // `metadata..` + // For example: `metadata.field_1.number_value = 10.0` + // * **Context based filtering**: + // To filter Executions based on the contexts to which they belong use + // the function operator with the full resource name: + // `in_context()`. + // For example: + // `in_context("projects//locations//metadataStores//contexts/")` // // Each of the above supported filters can be combined together using // logical operators (`AND` & `OR`). Maximum nested expression depth allowed @@ -3197,17 +3195,17 @@ type QueryArtifactLineageSubgraphRequest struct { // The syntax to define filter query is based on https://google.aip.dev/160. // The supported set of filters include the following: // - // - **Attribute filtering**: - // For example: `display_name = "test"` - // Supported fields include: `name`, `display_name`, `uri`, `state`, - // `schema_title`, `create_time`, and `update_time`. - // Time fields, such as `create_time` and `update_time`, require values - // specified in RFC-3339 format. - // For example: `create_time = "2020-11-19T11:30:00-04:00"` - // - **Metadata field**: - // To filter on metadata fields use traversal operation as follows: - // `metadata..`. - // For example: `metadata.field_1.number_value = 10.0` + // * **Attribute filtering**: + // For example: `display_name = "test"` + // Supported fields include: `name`, `display_name`, `uri`, `state`, + // `schema_title`, `create_time`, and `update_time`. + // Time fields, such as `create_time` and `update_time`, require values + // specified in RFC-3339 format. + // For example: `create_time = "2020-11-19T11:30:00-04:00"` + // * **Metadata field**: + // To filter on metadata fields use traversal operation as follows: + // `metadata..`. + // For example: `metadata.field_1.number_value = 10.0` // // Each of the above supported filter types can be combined together using // logical operators (`AND` & `OR`). Maximum nested expression depth allowed diff --git a/aiplatform/apiv1/aiplatformpb/metadata_store.pb.go b/aiplatform/apiv1/aiplatformpb/metadata_store.pb.go index 6eb4250705d7..fffbea7dbad0 100644 --- a/aiplatform/apiv1/aiplatformpb/metadata_store.pb.go +++ b/aiplatform/apiv1/aiplatformpb/metadata_store.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/metadata_store.proto package aiplatformpb diff --git a/aiplatform/apiv1/aiplatformpb/migratable_resource.pb.go b/aiplatform/apiv1/aiplatformpb/migratable_resource.pb.go index e8b24f078469..a79b41599cdb 100644 --- a/aiplatform/apiv1/aiplatformpb/migratable_resource.pb.go +++ b/aiplatform/apiv1/aiplatformpb/migratable_resource.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/migratable_resource.proto package aiplatformpb @@ -45,7 +45,6 @@ type MigratableResource struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Resource: - // // *MigratableResource_MlEngineModelVersion_ // *MigratableResource_AutomlModel_ // *MigratableResource_AutomlDataset_ diff --git a/aiplatform/apiv1/aiplatformpb/migration_service.pb.go b/aiplatform/apiv1/aiplatformpb/migration_service.pb.go index fa6ded41ad02..3a5b753239e9 100644 --- a/aiplatform/apiv1/aiplatformpb/migration_service.pb.go +++ b/aiplatform/apiv1/aiplatformpb/migration_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/migration_service.proto package aiplatformpb @@ -61,16 +61,16 @@ type SearchMigratableResourcesRequest struct { PageToken string `protobuf:"bytes,3,opt,name=page_token,json=pageToken,proto3" json:"page_token,omitempty"` // A filter for your search. You can use the following types of filters: // - // - Resource type filters. The following strings filter for a specific type + // * Resource type filters. The following strings filter for a specific type // of [MigratableResource][google.cloud.aiplatform.v1.MigratableResource]: - // - `ml_engine_model_version:*` - // - `automl_model:*` - // - `automl_dataset:*` - // - `data_labeling_dataset:*` - // - "Migrated or not" filters. The following strings filter for resources + // * `ml_engine_model_version:*` + // * `automl_model:*` + // * `automl_dataset:*` + // * `data_labeling_dataset:*` + // * "Migrated or not" filters. The following strings filter for resources // that either have or have not already been migrated: - // - `last_migrate_time:*` filters for migrated resources. - // - `NOT last_migrate_time:*` filters for not yet migrated resources. + // * `last_migrate_time:*` filters for migrated resources. + // * `NOT last_migrate_time:*` filters for not yet migrated resources. Filter string `protobuf:"bytes,4,opt,name=filter,proto3" json:"filter,omitempty"` } @@ -264,7 +264,6 @@ type MigrateResourceRequest struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Request: - // // *MigrateResourceRequest_MigrateMlEngineModelVersionConfig_ // *MigrateResourceRequest_MigrateAutomlModelConfig_ // *MigrateResourceRequest_MigrateAutomlDatasetConfig_ @@ -433,7 +432,6 @@ type MigrateResourceResponse struct { // After migration, the resource name in Vertex AI. // // Types that are assignable to MigratedResource: - // // *MigrateResourceResponse_Dataset // *MigrateResourceResponse_Model MigratedResource isMigrateResourceResponse_MigratedResource `protobuf_oneof:"migrated_resource"` @@ -918,7 +916,6 @@ type BatchMigrateResourcesOperationMetadata_PartialResult struct { // migrated resource name will be filled. // // Types that are assignable to Result: - // // *BatchMigrateResourcesOperationMetadata_PartialResult_Error // *BatchMigrateResourcesOperationMetadata_PartialResult_Model // *BatchMigrateResourcesOperationMetadata_PartialResult_Dataset diff --git a/aiplatform/apiv1/aiplatformpb/model.pb.go b/aiplatform/apiv1/aiplatformpb/model.pb.go index d6a3e982ee16..8c392c370ea6 100644 --- a/aiplatform/apiv1/aiplatformpb/model.pb.go +++ b/aiplatform/apiv1/aiplatformpb/model.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/model.proto package aiplatformpb @@ -327,6 +327,7 @@ type Model struct { // `gcs_source` field of the // [InputConfig][google.cloud.aiplatform.v1.BatchPredictionJob.InputConfig] object. // + // // If this Model doesn't support any of these formats it means it cannot be // used with a [BatchPredictionJob][google.cloud.aiplatform.v1.BatchPredictionJob]. However, if it has // [supported_deployment_resources_types][google.cloud.aiplatform.v1.Model.supported_deployment_resources_types], it could serve online @@ -358,6 +359,7 @@ type Model struct { // [BigQueryDestination][google.cloud.aiplatform.v1.BatchPredictionJob.OutputConfig.bigquery_destination] // . // + // // If this Model doesn't support any of these formats it means it cannot be // used with a [BatchPredictionJob][google.cloud.aiplatform.v1.BatchPredictionJob]. However, if it has // [supported_deployment_resources_types][google.cloud.aiplatform.v1.Model.supported_deployment_resources_types], it could serve online @@ -845,16 +847,14 @@ type ModelContainerSpec struct { // // ```json // [ - // - // { - // "name": "VAR_1", - // "value": "foo" - // }, - // { - // "name": "VAR_2", - // "value": "$(VAR_1) bar" - // } - // + // { + // "name": "VAR_1", + // "value": "foo" + // }, + // { + // "name": "VAR_2", + // "value": "$(VAR_1) bar" + // } // ] // ``` // @@ -876,11 +876,9 @@ type ModelContainerSpec struct { // // ```json // [ - // - // { - // "containerPort": 8080 - // } - // + // { + // "containerPort": 8080 + // } // ] // ``` // @@ -906,16 +904,16 @@ type ModelContainerSpec struct { // /v1/endpoints/ENDPOINT/deployedModels/DEPLOYED_MODEL:predict // The placeholders in this value are replaced as follows: // - // - ENDPOINT: The last segment (following `endpoints/`)of the - // Endpoint.name][] field of the Endpoint where this Model has been - // deployed. (Vertex AI makes this value available to your container code - // as the [`AIP_ENDPOINT_ID` environment - // variable](https://cloud.google.com/vertex-ai/docs/predictions/custom-container-requirements#aip-variables).) + // * ENDPOINT: The last segment (following `endpoints/`)of the + // Endpoint.name][] field of the Endpoint where this Model has been + // deployed. (Vertex AI makes this value available to your container code + // as the [`AIP_ENDPOINT_ID` environment + // variable](https://cloud.google.com/vertex-ai/docs/predictions/custom-container-requirements#aip-variables).) // - // - DEPLOYED_MODEL: [DeployedModel.id][google.cloud.aiplatform.v1.DeployedModel.id] of the `DeployedModel`. - // (Vertex AI makes this value available to your container code - // as the [`AIP_DEPLOYED_MODEL_ID` environment - // variable](https://cloud.google.com/vertex-ai/docs/predictions/custom-container-requirements#aip-variables).) + // * DEPLOYED_MODEL: [DeployedModel.id][google.cloud.aiplatform.v1.DeployedModel.id] of the `DeployedModel`. + // (Vertex AI makes this value available to your container code + // as the [`AIP_DEPLOYED_MODEL_ID` environment + // variable](https://cloud.google.com/vertex-ai/docs/predictions/custom-container-requirements#aip-variables).) PredictRoute string `protobuf:"bytes,6,opt,name=predict_route,json=predictRoute,proto3" json:"predict_route,omitempty"` // Immutable. HTTP path on the container to send health checks to. Vertex AI // intermittently sends GET requests to this path on the container's IP @@ -933,16 +931,16 @@ type ModelContainerSpec struct { // /v1/endpoints/ENDPOINT/deployedModels/DEPLOYED_MODEL:predict // The placeholders in this value are replaced as follows: // - // - ENDPOINT: The last segment (following `endpoints/`)of the - // Endpoint.name][] field of the Endpoint where this Model has been - // deployed. (Vertex AI makes this value available to your container code - // as the [`AIP_ENDPOINT_ID` environment - // variable](https://cloud.google.com/vertex-ai/docs/predictions/custom-container-requirements#aip-variables).) + // * ENDPOINT: The last segment (following `endpoints/`)of the + // Endpoint.name][] field of the Endpoint where this Model has been + // deployed. (Vertex AI makes this value available to your container code + // as the [`AIP_ENDPOINT_ID` environment + // variable](https://cloud.google.com/vertex-ai/docs/predictions/custom-container-requirements#aip-variables).) // - // - DEPLOYED_MODEL: [DeployedModel.id][google.cloud.aiplatform.v1.DeployedModel.id] of the `DeployedModel`. - // (Vertex AI makes this value available to your container code as the - // [`AIP_DEPLOYED_MODEL_ID` environment - // variable](https://cloud.google.com/vertex-ai/docs/predictions/custom-container-requirements#aip-variables).) + // * DEPLOYED_MODEL: [DeployedModel.id][google.cloud.aiplatform.v1.DeployedModel.id] of the `DeployedModel`. + // (Vertex AI makes this value available to your container code as the + // [`AIP_DEPLOYED_MODEL_ID` environment + // variable](https://cloud.google.com/vertex-ai/docs/predictions/custom-container-requirements#aip-variables).) HealthRoute string `protobuf:"bytes,7,opt,name=health_route,json=healthRoute,proto3" json:"health_route,omitempty"` } diff --git a/aiplatform/apiv1/aiplatformpb/model_deployment_monitoring_job.pb.go b/aiplatform/apiv1/aiplatformpb/model_deployment_monitoring_job.pb.go index 2e7bf044816f..0d9c74eb747d 100644 --- a/aiplatform/apiv1/aiplatformpb/model_deployment_monitoring_job.pb.go +++ b/aiplatform/apiv1/aiplatformpb/model_deployment_monitoring_job.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/model_deployment_monitoring_job.proto package aiplatformpb diff --git a/aiplatform/apiv1/aiplatformpb/model_evaluation.pb.go b/aiplatform/apiv1/aiplatformpb/model_evaluation.pb.go index 4730e3438f67..afc39febdb72 100644 --- a/aiplatform/apiv1/aiplatformpb/model_evaluation.pb.go +++ b/aiplatform/apiv1/aiplatformpb/model_evaluation.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/model_evaluation.proto package aiplatformpb @@ -87,6 +87,7 @@ type ModelEvaluation struct { // Aggregated explanation metrics for the Model's prediction output over the // data this ModelEvaluation uses. This field is populated only if the Model // is evaluated with explanations, and only for AutoML tabular Models. + // ModelExplanation *ModelExplanation `protobuf:"bytes,8,opt,name=model_explanation,json=modelExplanation,proto3" json:"model_explanation,omitempty"` // Describes the values of [ExplanationSpec][google.cloud.aiplatform.v1.ExplanationSpec] that are used for explaining // the predicted values on the evaluated data. @@ -216,8 +217,8 @@ type ModelEvaluation_ModelEvaluationExplanationSpec struct { // // For AutoML Image Classification models, possible values are: // - // - `image-integrated-gradients` - // - `image-xrai` + // * `image-integrated-gradients` + // * `image-xrai` ExplanationType string `protobuf:"bytes,1,opt,name=explanation_type,json=explanationType,proto3" json:"explanation_type,omitempty"` // Explanation spec details. ExplanationSpec *ExplanationSpec `protobuf:"bytes,2,opt,name=explanation_spec,json=explanationSpec,proto3" json:"explanation_spec,omitempty"` diff --git a/aiplatform/apiv1/aiplatformpb/model_evaluation_slice.pb.go b/aiplatform/apiv1/aiplatformpb/model_evaluation_slice.pb.go index 463e61b47394..29fd90a778aa 100644 --- a/aiplatform/apiv1/aiplatformpb/model_evaluation_slice.pb.go +++ b/aiplatform/apiv1/aiplatformpb/model_evaluation_slice.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/model_evaluation_slice.proto package aiplatformpb @@ -136,7 +136,7 @@ type ModelEvaluationSlice_Slice struct { // Output only. The dimension of the slice. // Well-known dimensions are: - // - `annotationSpec`: This slice is on the test data that has either + // * `annotationSpec`: This slice is on the test data that has either // ground truth or prediction with [AnnotationSpec.display_name][google.cloud.aiplatform.v1.AnnotationSpec.display_name] // equals to [value][google.cloud.aiplatform.v1.ModelEvaluationSlice.Slice.value]. Dimension string `protobuf:"bytes,1,opt,name=dimension,proto3" json:"dimension,omitempty"` diff --git a/aiplatform/apiv1/aiplatformpb/model_monitoring.pb.go b/aiplatform/apiv1/aiplatformpb/model_monitoring.pb.go index 3b3719339b4e..910189dc8a97 100644 --- a/aiplatform/apiv1/aiplatformpb/model_monitoring.pb.go +++ b/aiplatform/apiv1/aiplatformpb/model_monitoring.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/model_monitoring.proto package aiplatformpb @@ -173,7 +173,6 @@ type ModelMonitoringAlertConfig struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Alert: - // // *ModelMonitoringAlertConfig_EmailAlertConfig_ Alert isModelMonitoringAlertConfig_Alert `protobuf_oneof:"alert"` // Dump the anomalies to Cloud Logging. The anomalies will be put to json @@ -255,7 +254,6 @@ type ThresholdConfig struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Threshold: - // // *ThresholdConfig_Value Threshold isThresholdConfig_Threshold `protobuf_oneof:"threshold"` } @@ -313,11 +311,10 @@ type isThresholdConfig_Threshold interface { type ThresholdConfig_Value struct { // Specify a threshold value that can trigger the alert. // If this threshold config is for feature distribution distance: - // 1. For categorical feature, the distribution distance is calculated by - // L-inifinity norm. - // 2. For numerical feature, the distribution distance is calculated by - // Jensen–Shannon divergence. - // + // 1. For categorical feature, the distribution distance is calculated by + // L-inifinity norm. + // 2. For numerical feature, the distribution distance is calculated by + // Jensen–Shannon divergence. // Each feature must have a non-zero threshold if they need to be monitored. // Otherwise no alert will be triggered for that feature. Value float64 `protobuf:"fixed64,1,opt,name=value,proto3,oneof"` @@ -382,7 +379,6 @@ type ModelMonitoringObjectiveConfig_TrainingDataset struct { unknownFields protoimpl.UnknownFields // Types that are assignable to DataSource: - // // *ModelMonitoringObjectiveConfig_TrainingDataset_Dataset // *ModelMonitoringObjectiveConfig_TrainingDataset_GcsSource // *ModelMonitoringObjectiveConfig_TrainingDataset_BigquerySource @@ -739,7 +735,6 @@ type ModelMonitoringObjectiveConfig_ExplanationConfig_ExplanationBaseline struct // used to generate the baseline of feature attribution scores. // // Types that are assignable to Destination: - // // *ModelMonitoringObjectiveConfig_ExplanationConfig_ExplanationBaseline_Gcs // *ModelMonitoringObjectiveConfig_ExplanationConfig_ExplanationBaseline_Bigquery Destination isModelMonitoringObjectiveConfig_ExplanationConfig_ExplanationBaseline_Destination `protobuf_oneof:"destination"` diff --git a/aiplatform/apiv1/aiplatformpb/model_service.pb.go b/aiplatform/apiv1/aiplatformpb/model_service.pb.go index da5ba3e44d3d..9d8efd9d6cc7 100644 --- a/aiplatform/apiv1/aiplatformpb/model_service.pb.go +++ b/aiplatform/apiv1/aiplatformpb/model_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/model_service.proto package aiplatformpb @@ -243,11 +243,9 @@ type GetModelRequest struct { // // In order to retrieve a specific version of the model, also provide // the version ID or version alias. - // - // Example: `projects/{project}/locations/{location}/models/{model}@2` - // or - // `projects/{project}/locations/{location}/models/{model}@golden` - // + // Example: `projects/{project}/locations/{location}/models/{model}@2` + // or + // `projects/{project}/locations/{location}/models/{model}@golden` // If no version ID or alias is specified, the "default" version will be // returned. The "default" version alias is created for the first version of // the model, and can be moved to other versions later on. There will be @@ -306,19 +304,19 @@ type ListModelsRequest struct { // An expression for filtering the results of the request. For field names // both snake_case and camelCase are supported. // - // - `model` supports = and !=. `model` represents the Model ID, + // * `model` supports = and !=. `model` represents the Model ID, // i.e. the last segment of the Model's [resource name][google.cloud.aiplatform.v1.Model.name]. - // - `display_name` supports = and != - // - `labels` supports general map functions that is: - // - `labels.key=value` - key:value equality - // - `labels.key:* or labels:key - key existence - // - A key including a space must be quoted. `labels."a key"`. + // * `display_name` supports = and != + // * `labels` supports general map functions that is: + // * `labels.key=value` - key:value equality + // * `labels.key:* or labels:key - key existence + // * A key including a space must be quoted. `labels."a key"`. // // Some examples: // - // - `model=1234` - // - `displayName="myDisplayName"` - // - `labels.myKey="myValue"` + // * `model=1234` + // * `displayName="myDisplayName"` + // * `labels.myKey="myValue"` Filter string `protobuf:"bytes,2,opt,name=filter,proto3" json:"filter,omitempty"` // The standard list page size. PageSize int32 `protobuf:"varint,3,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"` @@ -333,9 +331,9 @@ type ListModelsRequest struct { // Use "desc" after a field name for descending. // Supported fields: // - // - `display_name` - // - `create_time` - // - `update_time` + // * `display_name` + // * `create_time` + // * `update_time` // // Example: `display_name, create_time desc`. OrderBy string `protobuf:"bytes,6,opt,name=order_by,json=orderBy,proto3" json:"order_by,omitempty"` @@ -492,14 +490,14 @@ type ListModelVersionsRequest struct { // An expression for filtering the results of the request. For field names // both snake_case and camelCase are supported. // - // - `labels` supports general map functions that is: - // - `labels.key=value` - key:value equality - // - `labels.key:* or labels:key - key existence - // - A key including a space must be quoted. `labels."a key"`. + // * `labels` supports general map functions that is: + // * `labels.key=value` - key:value equality + // * `labels.key:* or labels:key - key existence + // * A key including a space must be quoted. `labels."a key"`. // // Some examples: // - // - `labels.myKey="myValue"` + // * `labels.myKey="myValue"` Filter string `protobuf:"bytes,4,opt,name=filter,proto3" json:"filter,omitempty"` // Mask specifying which fields to read. ReadMask *fieldmaskpb.FieldMask `protobuf:"bytes,5,opt,name=read_mask,json=readMask,proto3" json:"read_mask,omitempty"` @@ -1470,7 +1468,7 @@ type ListModelEvaluationSlicesRequest struct { Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // The standard list filter. // - // - `slice.dimension` - for =. + // * `slice.dimension` - for =. Filter string `protobuf:"bytes,2,opt,name=filter,proto3" json:"filter,omitempty"` // The standard list page size. PageSize int32 `protobuf:"varint,3,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"` diff --git a/aiplatform/apiv1/aiplatformpb/operation.pb.go b/aiplatform/apiv1/aiplatformpb/operation.pb.go index 7ff11184d67b..a50d645f8b1d 100644 --- a/aiplatform/apiv1/aiplatformpb/operation.pb.go +++ b/aiplatform/apiv1/aiplatformpb/operation.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/operation.proto package aiplatformpb diff --git a/aiplatform/apiv1/aiplatformpb/pipeline_failure_policy.pb.go b/aiplatform/apiv1/aiplatformpb/pipeline_failure_policy.pb.go index 138f4a5947bf..6301ca67e34b 100644 --- a/aiplatform/apiv1/aiplatformpb/pipeline_failure_policy.pb.go +++ b/aiplatform/apiv1/aiplatformpb/pipeline_failure_policy.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/pipeline_failure_policy.proto package aiplatformpb diff --git a/aiplatform/apiv1/aiplatformpb/pipeline_job.pb.go b/aiplatform/apiv1/aiplatformpb/pipeline_job.pb.go index f83ce0c62a0c..3a95f9ce95d4 100644 --- a/aiplatform/apiv1/aiplatformpb/pipeline_job.pb.go +++ b/aiplatform/apiv1/aiplatformpb/pipeline_job.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/pipeline_job.proto package aiplatformpb @@ -638,7 +638,6 @@ type PipelineTaskExecutorDetail struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Details: - // // *PipelineTaskExecutorDetail_ContainerDetail_ // *PipelineTaskExecutorDetail_CustomJobDetail_ Details isPipelineTaskExecutorDetail_Details `protobuf_oneof:"details"` @@ -834,7 +833,6 @@ type PipelineJob_RuntimeConfig_InputArtifact struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Kind: - // // *PipelineJob_RuntimeConfig_InputArtifact_ArtifactId Kind isPipelineJob_RuntimeConfig_InputArtifact_Kind `protobuf_oneof:"kind"` } diff --git a/aiplatform/apiv1/aiplatformpb/pipeline_service.pb.go b/aiplatform/apiv1/aiplatformpb/pipeline_service.pb.go index 28ed56b7eb24..cec9c5b5bd90 100644 --- a/aiplatform/apiv1/aiplatformpb/pipeline_service.pb.go +++ b/aiplatform/apiv1/aiplatformpb/pipeline_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/pipeline_service.proto package aiplatformpb @@ -166,22 +166,22 @@ type ListTrainingPipelinesRequest struct { // // Supported fields: // - // - `display_name` supports `=`, `!=` comparisons, and `:` wildcard. - // - `state` supports `=`, `!=` comparisons. - // - `training_task_definition` `=`, `!=` comparisons, and `:` wildcard. - // - `create_time` supports `=`, `!=`,`<`, `<=`,`>`, `>=` comparisons. + // * `display_name` supports `=`, `!=` comparisons, and `:` wildcard. + // * `state` supports `=`, `!=` comparisons. + // * `training_task_definition` `=`, `!=` comparisons, and `:` wildcard. + // * `create_time` supports `=`, `!=`,`<`, `<=`,`>`, `>=` comparisons. // `create_time` must be in RFC 3339 format. - // - `labels` supports general map functions that is: + // * `labels` supports general map functions that is: // `labels.key=value` - key:value equality // `labels.key:* - key existence // // Some examples of using the filter are: // - // - `state="PIPELINE_STATE_SUCCEEDED" AND display_name:"my_pipeline_*"` - // - `state!="PIPELINE_STATE_FAILED" OR display_name="my_pipeline"` - // - `NOT display_name="my_pipeline"` - // - `create_time>"2021-05-18T00:00:00Z"` - // - `training_task_definition:"*automl_text_classification*"` + // * `state="PIPELINE_STATE_SUCCEEDED" AND display_name:"my_pipeline_*"` + // * `state!="PIPELINE_STATE_FAILED" OR display_name="my_pipeline"` + // * `NOT display_name="my_pipeline"` + // * `create_time>"2021-05-18T00:00:00Z"` + // * `training_task_definition:"*automl_text_classification*"` Filter string `protobuf:"bytes,2,opt,name=filter,proto3" json:"filter,omitempty"` // The standard list page size. PageSize int32 `protobuf:"varint,3,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"` @@ -558,22 +558,22 @@ type ListPipelineJobsRequest struct { // Lists the PipelineJobs that match the filter expression. The following // fields are supported: // - // - `pipeline_name`: Supports `=` and `!=` comparisons. - // - `display_name`: Supports `=`, `!=` comparisons, and `:` wildcard. - // - `pipeline_job_user_id`: Supports `=`, `!=` comparisons, and `:` wildcard. - // for example, can check if pipeline's display_name contains *step* by - // doing display_name:\"*step*\" - // - `state`: Supports `=` and `!=` comparisons. - // - `create_time`: Supports `=`, `!=`, `<`, `>`, `<=`, and `>=` comparisons. - // Values must be in RFC 3339 format. - // - `update_time`: Supports `=`, `!=`, `<`, `>`, `<=`, and `>=` comparisons. - // Values must be in RFC 3339 format. - // - `end_time`: Supports `=`, `!=`, `<`, `>`, `<=`, and `>=` comparisons. - // Values must be in RFC 3339 format. - // - `labels`: Supports key-value equality and key presence. - // - `template_uri`: Supports `=`, `!=` comparisons, and `:` wildcard. - // - `template_metadata.version`: Supports `=`, `!=` comparisons, and `:` - // wildcard. + // * `pipeline_name`: Supports `=` and `!=` comparisons. + // * `display_name`: Supports `=`, `!=` comparisons, and `:` wildcard. + // * `pipeline_job_user_id`: Supports `=`, `!=` comparisons, and `:` wildcard. + // for example, can check if pipeline's display_name contains *step* by + // doing display_name:\"*step*\" + // * `state`: Supports `=` and `!=` comparisons. + // * `create_time`: Supports `=`, `!=`, `<`, `>`, `<=`, and `>=` comparisons. + // Values must be in RFC 3339 format. + // * `update_time`: Supports `=`, `!=`, `<`, `>`, `<=`, and `>=` comparisons. + // Values must be in RFC 3339 format. + // * `end_time`: Supports `=`, `!=`, `<`, `>`, `<=`, and `>=` comparisons. + // Values must be in RFC 3339 format. + // * `labels`: Supports key-value equality and key presence. + // * `template_uri`: Supports `=`, `!=` comparisons, and `:` wildcard. + // * `template_metadata.version`: Supports `=`, `!=` comparisons, and `:` + // wildcard. // // Filter expressions can be combined together using logical operators // (`AND` & `OR`). @@ -584,11 +584,11 @@ type ListPipelineJobsRequest struct { // // Examples: // - // - `create_time>"2021-05-18T00:00:00Z" OR - // update_time>"2020-05-18T00:00:00Z"` PipelineJobs created or updated - // after 2020-05-18 00:00:00 UTC. - // - `labels.env = "prod"` - // PipelineJobs with label "env" set to "prod". + // * `create_time>"2021-05-18T00:00:00Z" OR + // update_time>"2020-05-18T00:00:00Z"` PipelineJobs created or updated + // after 2020-05-18 00:00:00 UTC. + // * `labels.env = "prod"` + // PipelineJobs with label "env" set to "prod". Filter string `protobuf:"bytes,2,opt,name=filter,proto3" json:"filter,omitempty"` // The standard list page size. PageSize int32 `protobuf:"varint,3,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"` @@ -606,10 +606,10 @@ type ListPipelineJobsRequest struct { // time in ascending order. if order_by is not specified, it will order by // default order is create time in descending order. Supported fields: // - // - `create_time` - // - `update_time` - // - `end_time` - // - `start_time` + // * `create_time` + // * `update_time` + // * `end_time` + // * `start_time` OrderBy string `protobuf:"bytes,6,opt,name=order_by,json=orderBy,proto3" json:"order_by,omitempty"` // Mask specifying which fields to read. ReadMask *fieldmaskpb.FieldMask `protobuf:"bytes,7,opt,name=read_mask,json=readMask,proto3" json:"read_mask,omitempty"` diff --git a/aiplatform/apiv1/aiplatformpb/pipeline_state.pb.go b/aiplatform/apiv1/aiplatformpb/pipeline_state.pb.go index 6e2dca335ea2..dc9078589e83 100644 --- a/aiplatform/apiv1/aiplatformpb/pipeline_state.pb.go +++ b/aiplatform/apiv1/aiplatformpb/pipeline_state.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/pipeline_state.proto package aiplatformpb diff --git a/aiplatform/apiv1/aiplatformpb/prediction_service.pb.go b/aiplatform/apiv1/aiplatformpb/prediction_service.pb.go index 2a25cc25fa77..a99681fe99ef 100644 --- a/aiplatform/apiv1/aiplatformpb/prediction_service.pb.go +++ b/aiplatform/apiv1/aiplatformpb/prediction_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/prediction_service.proto package aiplatformpb @@ -315,10 +315,10 @@ type ExplainRequest struct { // [explanation_spec][google.cloud.aiplatform.v1.DeployedModel.explanation_spec] of the DeployedModel. // Can be used for explaining prediction results with different // configurations, such as: - // - Explaining top-5 predictions results as opposed to top-1; - // - Increasing path count or step count of the attribution methods to reduce - // approximate errors; - // - Using different baselines for explaining the prediction results. + // - Explaining top-5 predictions results as opposed to top-1; + // - Increasing path count or step count of the attribution methods to reduce + // approximate errors; + // - Using different baselines for explaining the prediction results. ExplanationSpecOverride *ExplanationSpecOverride `protobuf:"bytes,5,opt,name=explanation_spec_override,json=explanationSpecOverride,proto3" json:"explanation_spec_override,omitempty"` // If specified, this ExplainRequest will be served by the chosen // DeployedModel, overriding [Endpoint.traffic_split][google.cloud.aiplatform.v1.Endpoint.traffic_split]. diff --git a/aiplatform/apiv1/aiplatformpb/saved_query.pb.go b/aiplatform/apiv1/aiplatformpb/saved_query.pb.go index 227ddf3e76d6..400dae6d7596 100644 --- a/aiplatform/apiv1/aiplatformpb/saved_query.pb.go +++ b/aiplatform/apiv1/aiplatformpb/saved_query.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/saved_query.proto package aiplatformpb diff --git a/aiplatform/apiv1/aiplatformpb/specialist_pool.pb.go b/aiplatform/apiv1/aiplatformpb/specialist_pool.pb.go index b867ad18698e..5d370599dbe8 100644 --- a/aiplatform/apiv1/aiplatformpb/specialist_pool.pb.go +++ b/aiplatform/apiv1/aiplatformpb/specialist_pool.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/specialist_pool.proto package aiplatformpb diff --git a/aiplatform/apiv1/aiplatformpb/specialist_pool_service.pb.go b/aiplatform/apiv1/aiplatformpb/specialist_pool_service.pb.go index 1fc3c70ad5c1..fa7e325e3d90 100644 --- a/aiplatform/apiv1/aiplatformpb/specialist_pool_service.pb.go +++ b/aiplatform/apiv1/aiplatformpb/specialist_pool_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/specialist_pool_service.proto package aiplatformpb diff --git a/aiplatform/apiv1/aiplatformpb/study.pb.go b/aiplatform/apiv1/aiplatformpb/study.pb.go index 2d4682dc5eb2..1f9eeacd0212 100644 --- a/aiplatform/apiv1/aiplatformpb/study.pb.go +++ b/aiplatform/apiv1/aiplatformpb/study.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/study.proto package aiplatformpb @@ -736,7 +736,6 @@ type StudySpec struct { unknownFields protoimpl.UnknownFields // Types that are assignable to AutomatedStoppingSpec: - // // *StudySpec_DecayCurveStoppingSpec // *StudySpec_MedianAutomatedStoppingSpec_ // *StudySpec_ConvexAutomatedStoppingSpec_ @@ -1075,7 +1074,6 @@ type StudySpec_ParameterSpec struct { unknownFields protoimpl.UnknownFields // Types that are assignable to ParameterValueSpec: - // // *StudySpec_ParameterSpec_DoubleValueSpec_ // *StudySpec_ParameterSpec_IntegerValueSpec_ // *StudySpec_ParameterSpec_CategoricalValueSpec_ @@ -1726,7 +1724,6 @@ type StudySpec_ParameterSpec_ConditionalParameterSpec struct { // space. // // Types that are assignable to ParentValueCondition: - // // *StudySpec_ParameterSpec_ConditionalParameterSpec_ParentDiscreteValues // *StudySpec_ParameterSpec_ConditionalParameterSpec_ParentIntValues // *StudySpec_ParameterSpec_ConditionalParameterSpec_ParentCategoricalValues diff --git a/aiplatform/apiv1/aiplatformpb/tensorboard.pb.go b/aiplatform/apiv1/aiplatformpb/tensorboard.pb.go index 37b5961bdb1e..f5e0e0f2e979 100644 --- a/aiplatform/apiv1/aiplatformpb/tensorboard.pb.go +++ b/aiplatform/apiv1/aiplatformpb/tensorboard.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/tensorboard.proto package aiplatformpb diff --git a/aiplatform/apiv1/aiplatformpb/tensorboard_data.pb.go b/aiplatform/apiv1/aiplatformpb/tensorboard_data.pb.go index 1f874ddbfc0a..d5b99290c8e3 100644 --- a/aiplatform/apiv1/aiplatformpb/tensorboard_data.pb.go +++ b/aiplatform/apiv1/aiplatformpb/tensorboard_data.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/tensorboard_data.proto package aiplatformpb @@ -115,7 +115,6 @@ type TimeSeriesDataPoint struct { // Value of this time series data point. // // Types that are assignable to Value: - // // *TimeSeriesDataPoint_Scalar // *TimeSeriesDataPoint_Tensor // *TimeSeriesDataPoint_Blobs diff --git a/aiplatform/apiv1/aiplatformpb/tensorboard_experiment.pb.go b/aiplatform/apiv1/aiplatformpb/tensorboard_experiment.pb.go index 07672e44bc18..c72c98f2a47b 100644 --- a/aiplatform/apiv1/aiplatformpb/tensorboard_experiment.pb.go +++ b/aiplatform/apiv1/aiplatformpb/tensorboard_experiment.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/tensorboard_experiment.proto package aiplatformpb @@ -69,7 +69,7 @@ type TensorboardExperiment struct { // and are immutable. Following system labels exist for each Dataset: // * "aiplatform.googleapis.com/dataset_metadata_schema": // - output only, its value is the - // [metadata_schema's][metadata_schema_uri] title. + // [metadata_schema's][metadata_schema_uri] title. Labels map[string]string `protobuf:"bytes,6,rep,name=labels,proto3" json:"labels,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` // Used to perform consistent read-modify-write updates. If not set, a blind // "overwrite" update happens. diff --git a/aiplatform/apiv1/aiplatformpb/tensorboard_run.pb.go b/aiplatform/apiv1/aiplatformpb/tensorboard_run.pb.go index 667d02d9eae3..f2e8512127ad 100644 --- a/aiplatform/apiv1/aiplatformpb/tensorboard_run.pb.go +++ b/aiplatform/apiv1/aiplatformpb/tensorboard_run.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/tensorboard_run.proto package aiplatformpb diff --git a/aiplatform/apiv1/aiplatformpb/tensorboard_service.pb.go b/aiplatform/apiv1/aiplatformpb/tensorboard_service.pb.go index 7ce448bb60b0..36b08574351e 100644 --- a/aiplatform/apiv1/aiplatformpb/tensorboard_service.pb.go +++ b/aiplatform/apiv1/aiplatformpb/tensorboard_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/tensorboard_service.proto package aiplatformpb diff --git a/aiplatform/apiv1/aiplatformpb/tensorboard_time_series.pb.go b/aiplatform/apiv1/aiplatformpb/tensorboard_time_series.pb.go index 8089c654e9d2..9a73893f9aec 100644 --- a/aiplatform/apiv1/aiplatformpb/tensorboard_time_series.pb.go +++ b/aiplatform/apiv1/aiplatformpb/tensorboard_time_series.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/tensorboard_time_series.proto package aiplatformpb diff --git a/aiplatform/apiv1/aiplatformpb/training_pipeline.pb.go b/aiplatform/apiv1/aiplatformpb/training_pipeline.pb.go index f20b0f43a61b..feb4bbd2018a 100644 --- a/aiplatform/apiv1/aiplatformpb/training_pipeline.pb.go +++ b/aiplatform/apiv1/aiplatformpb/training_pipeline.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/training_pipeline.proto package aiplatformpb @@ -297,7 +297,6 @@ type InputDataConfig struct { // If no split type is provided, the [fraction_split][google.cloud.aiplatform.v1.InputDataConfig.fraction_split] is used by default. // // Types that are assignable to Split: - // // *InputDataConfig_FractionSplit // *InputDataConfig_FilterSplit // *InputDataConfig_PredefinedSplit @@ -309,8 +308,8 @@ type InputDataConfig struct { // The destination of the training data to be written to. // // Supported destination file formats: - // - For non-tabular data: "jsonl". - // - For tabular data: "csv" and "bigquery". + // * For non-tabular data: "jsonl". + // * For tabular data: "csv" and "bigquery". // // The following Vertex AI environment variables are passed to containers // or python modules of the training task when this field is set: @@ -321,7 +320,6 @@ type InputDataConfig struct { // * AIP_TEST_DATA_URI : Sharded exported test data uris. // // Types that are assignable to Destination: - // // *InputDataConfig_GcsDestination // *InputDataConfig_BigqueryDestination Destination isInputDataConfig_Destination `protobuf_oneof:"destination"` diff --git a/aiplatform/apiv1/aiplatformpb/types.pb.go b/aiplatform/apiv1/aiplatformpb/types.pb.go index 1bfedb8957ff..c3fa4bc7f902 100644 --- a/aiplatform/apiv1/aiplatformpb/types.pb.go +++ b/aiplatform/apiv1/aiplatformpb/types.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/types.proto package aiplatformpb diff --git a/aiplatform/apiv1/aiplatformpb/unmanaged_container_model.pb.go b/aiplatform/apiv1/aiplatformpb/unmanaged_container_model.pb.go index cc8ca3913afb..e891f5879d38 100644 --- a/aiplatform/apiv1/aiplatformpb/unmanaged_container_model.pb.go +++ b/aiplatform/apiv1/aiplatformpb/unmanaged_container_model.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/unmanaged_container_model.proto package aiplatformpb diff --git a/aiplatform/apiv1/aiplatformpb/user_action_reference.pb.go b/aiplatform/apiv1/aiplatformpb/user_action_reference.pb.go index 1cff59de2f35..2079a97a4f11 100644 --- a/aiplatform/apiv1/aiplatformpb/user_action_reference.pb.go +++ b/aiplatform/apiv1/aiplatformpb/user_action_reference.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/user_action_reference.proto package aiplatformpb @@ -43,7 +43,6 @@ type UserActionReference struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Reference: - // // *UserActionReference_Operation // *UserActionReference_DataLabelingJob Reference isUserActionReference_Reference `protobuf_oneof:"reference"` diff --git a/aiplatform/apiv1/aiplatformpb/value.pb.go b/aiplatform/apiv1/aiplatformpb/value.pb.go index 97c056ac83cc..9abad33ce804 100644 --- a/aiplatform/apiv1/aiplatformpb/value.pb.go +++ b/aiplatform/apiv1/aiplatformpb/value.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/value.proto package aiplatformpb @@ -42,7 +42,6 @@ type Value struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Value: - // // *Value_IntValue // *Value_DoubleValue // *Value_StringValue diff --git a/aiplatform/apiv1/aiplatformpb/vizier_service.pb.go b/aiplatform/apiv1/aiplatformpb/vizier_service.pb.go index 7fb9d13ff2f8..10497d276f95 100644 --- a/aiplatform/apiv1/aiplatformpb/vizier_service.pb.go +++ b/aiplatform/apiv1/aiplatformpb/vizier_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1/vizier_service.proto package aiplatformpb diff --git a/aiplatform/apiv1/dataset_client.go b/aiplatform/apiv1/dataset_client.go index 96e435fe1b06..ae7199095dda 100644 --- a/aiplatform/apiv1/dataset_client.go +++ b/aiplatform/apiv1/dataset_client.go @@ -51,6 +51,7 @@ type DatasetCallOptions struct { ImportData []gax.CallOption ExportData []gax.CallOption ListDataItems []gax.CallOption + SearchDataItems []gax.CallOption ListSavedQueries []gax.CallOption GetAnnotationSpec []gax.CallOption ListAnnotations []gax.CallOption @@ -88,6 +89,7 @@ func defaultDatasetCallOptions() *DatasetCallOptions { ImportData: []gax.CallOption{}, ExportData: []gax.CallOption{}, ListDataItems: []gax.CallOption{}, + SearchDataItems: []gax.CallOption{}, ListSavedQueries: []gax.CallOption{}, GetAnnotationSpec: []gax.CallOption{}, ListAnnotations: []gax.CallOption{}, @@ -121,6 +123,7 @@ type internalDatasetClient interface { ExportData(context.Context, *aiplatformpb.ExportDataRequest, ...gax.CallOption) (*ExportDataOperation, error) ExportDataOperation(name string) *ExportDataOperation ListDataItems(context.Context, *aiplatformpb.ListDataItemsRequest, ...gax.CallOption) *DataItemIterator + SearchDataItems(context.Context, *aiplatformpb.SearchDataItemsRequest, ...gax.CallOption) *DataItemViewIterator ListSavedQueries(context.Context, *aiplatformpb.ListSavedQueriesRequest, ...gax.CallOption) *SavedQueryIterator GetAnnotationSpec(context.Context, *aiplatformpb.GetAnnotationSpecRequest, ...gax.CallOption) (*aiplatformpb.AnnotationSpec, error) ListAnnotations(context.Context, *aiplatformpb.ListAnnotationsRequest, ...gax.CallOption) *AnnotationIterator @@ -241,6 +244,11 @@ func (c *DatasetClient) ListDataItems(ctx context.Context, req *aiplatformpb.Lis return c.internalClient.ListDataItems(ctx, req, opts...) } +// SearchDataItems searches DataItems in a Dataset. +func (c *DatasetClient) SearchDataItems(ctx context.Context, req *aiplatformpb.SearchDataItemsRequest, opts ...gax.CallOption) *DataItemViewIterator { + return c.internalClient.SearchDataItems(ctx, req, opts...) +} + // ListSavedQueries lists SavedQueries in a Dataset. func (c *DatasetClient) ListSavedQueries(ctx context.Context, req *aiplatformpb.ListSavedQueriesRequest, opts ...gax.CallOption) *SavedQueryIterator { return c.internalClient.ListSavedQueries(ctx, req, opts...) @@ -624,6 +632,51 @@ func (c *datasetGRPCClient) ListDataItems(ctx context.Context, req *aiplatformpb return it } +func (c *datasetGRPCClient) SearchDataItems(ctx context.Context, req *aiplatformpb.SearchDataItemsRequest, opts ...gax.CallOption) *DataItemViewIterator { + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "dataset", url.QueryEscape(req.GetDataset()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).SearchDataItems[0:len((*c.CallOptions).SearchDataItems):len((*c.CallOptions).SearchDataItems)], opts...) + it := &DataItemViewIterator{} + req = proto.Clone(req).(*aiplatformpb.SearchDataItemsRequest) + it.InternalFetch = func(pageSize int, pageToken string) ([]*aiplatformpb.DataItemView, string, error) { + resp := &aiplatformpb.SearchDataItemsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.datasetClient.SearchDataItems(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, "", err + } + + it.Response = resp + return resp.GetDataItemViews(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + func (c *datasetGRPCClient) ListSavedQueries(ctx context.Context, req *aiplatformpb.ListSavedQueriesRequest, opts ...gax.CallOption) *SavedQueryIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1308,6 +1361,53 @@ func (it *DataItemIterator) takeBuf() interface{} { return b } +// DataItemViewIterator manages a stream of *aiplatformpb.DataItemView. +type DataItemViewIterator struct { + items []*aiplatformpb.DataItemView + pageInfo *iterator.PageInfo + nextFunc func() error + + // Response is the raw response for the current page. + // It must be cast to the RPC response type. + // Calling Next() or InternalFetch() updates this value. + Response interface{} + + // 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 []*aiplatformpb.DataItemView, nextPageToken string, err error) +} + +// PageInfo supports pagination. See the google.golang.org/api/iterator package for details. +func (it *DataItemViewIterator) 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 *DataItemViewIterator) Next() (*aiplatformpb.DataItemView, error) { + var item *aiplatformpb.DataItemView + if err := it.nextFunc(); err != nil { + return item, err + } + item = it.items[0] + it.items = it.items[1:] + return item, nil +} + +func (it *DataItemViewIterator) bufLen() int { + return len(it.items) +} + +func (it *DataItemViewIterator) takeBuf() interface{} { + b := it.items + it.items = nil + return b +} + // DatasetIterator manages a stream of *aiplatformpb.Dataset. type DatasetIterator struct { items []*aiplatformpb.Dataset diff --git a/aiplatform/apiv1/dataset_client_example_test.go b/aiplatform/apiv1/dataset_client_example_test.go index bbc910d3c478..da70d814c3b0 100644 --- a/aiplatform/apiv1/dataset_client_example_test.go +++ b/aiplatform/apiv1/dataset_client_example_test.go @@ -274,6 +274,37 @@ func ExampleDatasetClient_ListDataItems() { } } +func ExampleDatasetClient_SearchDataItems() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := aiplatform.NewDatasetClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + req := &aiplatformpb.SearchDataItemsRequest{ + // TODO: Fill request struct fields. + // See https://pkg.go.dev/cloud.google.com/go/aiplatform/apiv1/aiplatformpb#SearchDataItemsRequest. + } + it := c.SearchDataItems(ctx, req) + for { + resp, err := it.Next() + if err == iterator.Done { + break + } + if err != nil { + // TODO: Handle error. + } + // TODO: Use resp. + _ = resp + } +} + func ExampleDatasetClient_ListSavedQueries() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/aiplatform/apiv1/gapic_metadata.json b/aiplatform/apiv1/gapic_metadata.json index 6a336ac41501..5763a94e8a92 100644 --- a/aiplatform/apiv1/gapic_metadata.json +++ b/aiplatform/apiv1/gapic_metadata.json @@ -95,6 +95,11 @@ "ListSavedQueries" ] }, + "SearchDataItems": { + "methods": [ + "SearchDataItems" + ] + }, "SetIamPolicy": { "methods": [ "SetIamPolicy" diff --git a/aiplatform/apiv1beta1/aiplatformpb/accelerator_type.pb.go b/aiplatform/apiv1beta1/aiplatformpb/accelerator_type.pb.go index 8d97ecc3dfee..87f80413eb95 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/accelerator_type.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/accelerator_type.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/accelerator_type.proto package aiplatformpb diff --git a/aiplatform/apiv1beta1/aiplatformpb/annotation.pb.go b/aiplatform/apiv1beta1/aiplatformpb/annotation.pb.go index d336ac2946a8..c36b434fd174 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/annotation.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/annotation.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/annotation.proto package aiplatformpb @@ -79,13 +79,13 @@ type Annotation struct { // System reserved label keys are prefixed with "aiplatform.googleapis.com/" // and are immutable. Following system labels exist for each Annotation: // - // - "aiplatform.googleapis.com/annotation_set_name": - // optional, name of the UI's annotation set this Annotation belongs to. - // If not set, the Annotation is not visible in the UI. + // * "aiplatform.googleapis.com/annotation_set_name": + // optional, name of the UI's annotation set this Annotation belongs to. + // If not set, the Annotation is not visible in the UI. // - // - "aiplatform.googleapis.com/payload_schema": - // output only, its value is the [payload_schema's][google.cloud.aiplatform.v1beta1.Annotation.payload_schema_uri] - // title. + // * "aiplatform.googleapis.com/payload_schema": + // output only, its value is the [payload_schema's][google.cloud.aiplatform.v1beta1.Annotation.payload_schema_uri] + // title. Labels map[string]string `protobuf:"bytes,6,rep,name=labels,proto3" json:"labels,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` } diff --git a/aiplatform/apiv1beta1/aiplatformpb/annotation_spec.pb.go b/aiplatform/apiv1beta1/aiplatformpb/annotation_spec.pb.go index 132081748dfe..54ccb6a37f55 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/annotation_spec.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/annotation_spec.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/annotation_spec.proto package aiplatformpb diff --git a/aiplatform/apiv1beta1/aiplatformpb/artifact.pb.go b/aiplatform/apiv1beta1/aiplatformpb/artifact.pb.go index 13c1dbe52780..968f383403a9 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/artifact.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/artifact.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/artifact.proto package aiplatformpb diff --git a/aiplatform/apiv1beta1/aiplatformpb/batch_prediction_job.pb.go b/aiplatform/apiv1beta1/aiplatformpb/batch_prediction_job.pb.go index 7e906f4a7152..15221a93e9c3 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/batch_prediction_job.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/batch_prediction_job.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/batch_prediction_job.proto package aiplatformpb @@ -114,12 +114,12 @@ type BatchPredictionJob struct { // `predictions_format` field of the // [BatchPredictionJob.output_config][google.cloud.aiplatform.v1beta1.BatchPredictionJob.output_config] object: // - // - `bigquery`: output includes a column named `explanation`. The value - // is a struct that conforms to the [Explanation][google.cloud.aiplatform.v1beta1.Explanation] object. - // - `jsonl`: The JSON objects on each line include an additional entry - // keyed `explanation`. The value of the entry is a JSON object that - // conforms to the [Explanation][google.cloud.aiplatform.v1beta1.Explanation] object. - // - `csv`: Generating explanations for CSV format is not supported. + // * `bigquery`: output includes a column named `explanation`. The value + // is a struct that conforms to the [Explanation][google.cloud.aiplatform.v1beta1.Explanation] object. + // * `jsonl`: The JSON objects on each line include an additional entry + // keyed `explanation`. The value of the entry is a JSON object that + // conforms to the [Explanation][google.cloud.aiplatform.v1beta1.Explanation] object. + // * `csv`: Generating explanations for CSV format is not supported. // // If this field is set to true, either the [Model.explanation_spec][google.cloud.aiplatform.v1beta1.Model.explanation_spec] or // [explanation_spec][google.cloud.aiplatform.v1beta1.BatchPredictionJob.explanation_spec] must be populated. @@ -431,7 +431,6 @@ type BatchPredictionJob_InputConfig struct { // Required. The source of the input. // // Types that are assignable to Source: - // // *BatchPredictionJob_InputConfig_GcsSource // *BatchPredictionJob_InputConfig_BigquerySource Source isBatchPredictionJob_InputConfig_Source `protobuf_oneof:"source"` @@ -538,35 +537,35 @@ type BatchPredictionJob_InstanceConfig struct { // Supported values are: // // * `object`: Each input is converted to JSON object format. - // - For `bigquery`, each row is converted to an object. - // - For `jsonl`, each line of the JSONL input must be an object. - // - Does not apply to `csv`, `file-list`, `tf-record`, or - // `tf-record-gzip`. + // * For `bigquery`, each row is converted to an object. + // * For `jsonl`, each line of the JSONL input must be an object. + // * Does not apply to `csv`, `file-list`, `tf-record`, or + // `tf-record-gzip`. // // * `array`: Each input is converted to JSON array format. - // - For `bigquery`, each row is converted to an array. The order - // of columns is determined by the BigQuery column order, unless - // [included_fields][google.cloud.aiplatform.v1beta1.BatchPredictionJob.InstanceConfig.included_fields] is populated. - // [included_fields][google.cloud.aiplatform.v1beta1.BatchPredictionJob.InstanceConfig.included_fields] must be populated for specifying field orders. - // - For `jsonl`, if each line of the JSONL input is an object, - // [included_fields][google.cloud.aiplatform.v1beta1.BatchPredictionJob.InstanceConfig.included_fields] must be populated for specifying field orders. - // - Does not apply to `csv`, `file-list`, `tf-record`, or - // `tf-record-gzip`. + // * For `bigquery`, each row is converted to an array. The order + // of columns is determined by the BigQuery column order, unless + // [included_fields][google.cloud.aiplatform.v1beta1.BatchPredictionJob.InstanceConfig.included_fields] is populated. + // [included_fields][google.cloud.aiplatform.v1beta1.BatchPredictionJob.InstanceConfig.included_fields] must be populated for specifying field orders. + // * For `jsonl`, if each line of the JSONL input is an object, + // [included_fields][google.cloud.aiplatform.v1beta1.BatchPredictionJob.InstanceConfig.included_fields] must be populated for specifying field orders. + // * Does not apply to `csv`, `file-list`, `tf-record`, or + // `tf-record-gzip`. // // If not specified, Vertex AI converts the batch prediction input as // follows: // - // - For `bigquery` and `csv`, the behavior is the same as `array`. The - // order of columns is the same as defined in the file or table, unless - // [included_fields][google.cloud.aiplatform.v1beta1.BatchPredictionJob.InstanceConfig.included_fields] is populated. - // - For `jsonl`, the prediction instance format is determined by - // each line of the input. - // - For `tf-record`/`tf-record-gzip`, each record will be converted to - // an object in the format of `{"b64": }`, where `` is - // the Base64-encoded string of the content of the record. - // - For `file-list`, each file in the list will be converted to an - // object in the format of `{"b64": }`, where `` is - // the Base64-encoded string of the content of the file. + // * For `bigquery` and `csv`, the behavior is the same as `array`. The + // order of columns is the same as defined in the file or table, unless + // [included_fields][google.cloud.aiplatform.v1beta1.BatchPredictionJob.InstanceConfig.included_fields] is populated. + // * For `jsonl`, the prediction instance format is determined by + // each line of the input. + // * For `tf-record`/`tf-record-gzip`, each record will be converted to + // an object in the format of `{"b64": }`, where `` is + // the Base64-encoded string of the content of the record. + // * For `file-list`, each file in the list will be converted to an + // object in the format of `{"b64": }`, where `` is + // the Base64-encoded string of the content of the file. InstanceType string `protobuf:"bytes,1,opt,name=instance_type,json=instanceType,proto3" json:"instance_type,omitempty"` // The name of the field that is considered as a key. // @@ -577,10 +576,10 @@ type BatchPredictionJob_InstanceConfig struct { // output will only include the value of the key field, in a field named // `key` in the output: // - // - For `jsonl` output format, the output will have a `key` field - // instead of the `instance` field. - // - For `csv`/`bigquery` output format, the output will have have a `key` - // column instead of the instance feature columns. + // * For `jsonl` output format, the output will have a `key` field + // instead of the `instance` field. + // * For `csv`/`bigquery` output format, the output will have have a `key` + // column instead of the instance feature columns. // // The input must be JSONL with objects at each line, CSV, BigQuery // or TfRecord. @@ -680,7 +679,6 @@ type BatchPredictionJob_OutputConfig struct { // Required. The destination of the output. // // Types that are assignable to Destination: - // // *BatchPredictionJob_OutputConfig_GcsDestination // *BatchPredictionJob_OutputConfig_BigqueryDestination Destination isBatchPredictionJob_OutputConfig_Destination `protobuf_oneof:"destination"` @@ -816,7 +814,6 @@ type BatchPredictionJob_OutputInfo struct { // The output location into which prediction output is written. // // Types that are assignable to OutputLocation: - // // *BatchPredictionJob_OutputInfo_GcsOutputDirectory // *BatchPredictionJob_OutputInfo_BigqueryOutputDataset OutputLocation isBatchPredictionJob_OutputInfo_OutputLocation `protobuf_oneof:"output_location"` diff --git a/aiplatform/apiv1beta1/aiplatformpb/completion_stats.pb.go b/aiplatform/apiv1beta1/aiplatformpb/completion_stats.pb.go index 89c3fda3c643..8b9aba6b292b 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/completion_stats.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/completion_stats.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/completion_stats.proto package aiplatformpb diff --git a/aiplatform/apiv1beta1/aiplatformpb/context.pb.go b/aiplatform/apiv1beta1/aiplatformpb/context.pb.go index 03fecab6c32a..0ff32b8b1ea1 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/context.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/context.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/context.proto package aiplatformpb diff --git a/aiplatform/apiv1beta1/aiplatformpb/custom_job.pb.go b/aiplatform/apiv1beta1/aiplatformpb/custom_job.pb.go index 6bffb527c8b1..3fe56873c0c5 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/custom_job.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/custom_job.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/custom_job.proto package aiplatformpb @@ -264,17 +264,17 @@ type CustomJobSpec struct { // The following Vertex AI environment variables will be passed to // containers or python modules when this field is set: // - // For CustomJob: + // For CustomJob: // - // * AIP_MODEL_DIR = `/model/` - // * AIP_CHECKPOINT_DIR = `/checkpoints/` - // * AIP_TENSORBOARD_LOG_DIR = `/logs/` + // * AIP_MODEL_DIR = `/model/` + // * AIP_CHECKPOINT_DIR = `/checkpoints/` + // * AIP_TENSORBOARD_LOG_DIR = `/logs/` // - // For CustomJob backing a Trial of HyperparameterTuningJob: + // For CustomJob backing a Trial of HyperparameterTuningJob: // - // * AIP_MODEL_DIR = `//model/` - // * AIP_CHECKPOINT_DIR = `//checkpoints/` - // * AIP_TENSORBOARD_LOG_DIR = `//logs/` + // * AIP_MODEL_DIR = `//model/` + // * AIP_CHECKPOINT_DIR = `//checkpoints/` + // * AIP_TENSORBOARD_LOG_DIR = `//logs/` BaseOutputDirectory *GcsDestination `protobuf:"bytes,6,opt,name=base_output_directory,json=baseOutputDirectory,proto3" json:"base_output_directory,omitempty"` // Optional. The name of a Vertex AI [Tensorboard][google.cloud.aiplatform.v1beta1.Tensorboard] resource to which this CustomJob // will upload Tensorboard logs. @@ -388,7 +388,6 @@ type WorkerPoolSpec struct { // The custom task to be executed in this worker pool. // // Types that are assignable to Task: - // // *WorkerPoolSpec_ContainerSpec // *WorkerPoolSpec_PythonPackageSpec Task isWorkerPoolSpec_Task `protobuf_oneof:"task"` diff --git a/aiplatform/apiv1beta1/aiplatformpb/data_item.pb.go b/aiplatform/apiv1beta1/aiplatformpb/data_item.pb.go index 300eda761895..5ae5343288f2 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/data_item.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/data_item.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/data_item.proto package aiplatformpb diff --git a/aiplatform/apiv1beta1/aiplatformpb/data_labeling_job.pb.go b/aiplatform/apiv1beta1/aiplatformpb/data_labeling_job.pb.go index 4d3ac4f6e0e2..40e572e26d73 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/data_labeling_job.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/data_labeling_job.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/data_labeling_job.proto package aiplatformpb @@ -157,8 +157,8 @@ type DataLabelingJob struct { // System reserved label keys are prefixed with "aiplatform.googleapis.com/" // and are immutable. Following system labels exist for each DataLabelingJob: // - // - "aiplatform.googleapis.com/schema": output only, its value is the - // [inputs_schema][google.cloud.aiplatform.v1beta1.DataLabelingJob.inputs_schema_uri]'s title. + // * "aiplatform.googleapis.com/schema": output only, its value is the + // [inputs_schema][google.cloud.aiplatform.v1beta1.DataLabelingJob.inputs_schema_uri]'s title. Labels map[string]string `protobuf:"bytes,11,rep,name=labels,proto3" json:"labels,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` // The SpecialistPools' resource names associated with this job. SpecialistPools []string `protobuf:"bytes,16,rep,name=specialist_pools,json=specialistPools,proto3" json:"specialist_pools,omitempty"` @@ -345,7 +345,6 @@ type ActiveLearningConfig struct { // machine. // // Types that are assignable to HumanLabelingBudget: - // // *ActiveLearningConfig_MaxDataItemCount // *ActiveLearningConfig_MaxDataItemPercentage HumanLabelingBudget isActiveLearningConfig_HumanLabelingBudget `protobuf_oneof:"human_labeling_budget"` @@ -454,14 +453,12 @@ type SampleConfig struct { // is used by default. // // Types that are assignable to InitialBatchSampleSize: - // // *SampleConfig_InitialBatchSamplePercentage InitialBatchSampleSize isSampleConfig_InitialBatchSampleSize `protobuf_oneof:"initial_batch_sample_size"` // Decides sample size for the following batches. // following_batch_sample_percentage is used by default. // // Types that are assignable to FollowingBatchSampleSize: - // // *SampleConfig_FollowingBatchSamplePercentage FollowingBatchSampleSize isSampleConfig_FollowingBatchSampleSize `protobuf_oneof:"following_batch_sample_size"` // Field to choose sampling strategy. Sampling strategy will decide which data diff --git a/aiplatform/apiv1beta1/aiplatformpb/dataset.pb.go b/aiplatform/apiv1beta1/aiplatformpb/dataset.pb.go index 28b518a6c024..c7d11cb72619 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/dataset.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/dataset.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/dataset.proto package aiplatformpb @@ -79,8 +79,8 @@ type Dataset struct { // System reserved label keys are prefixed with "aiplatform.googleapis.com/" // and are immutable. Following system labels exist for each Dataset: // - // - "aiplatform.googleapis.com/dataset_metadata_schema": output only, its - // value is the [metadata_schema's][google.cloud.aiplatform.v1beta1.Dataset.metadata_schema_uri] title. + // * "aiplatform.googleapis.com/dataset_metadata_schema": output only, its + // value is the [metadata_schema's][google.cloud.aiplatform.v1beta1.Dataset.metadata_schema_uri] title. Labels map[string]string `protobuf:"bytes,7,rep,name=labels,proto3" json:"labels,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` // Customer-managed encryption key spec for a Dataset. If set, this Dataset // and all sub-resources of this Dataset will be secured by this key. @@ -210,7 +210,6 @@ type ImportDataConfig struct { // The source of the input. // // Types that are assignable to Source: - // // *ImportDataConfig_GcsSource Source isImportDataConfig_Source `protobuf_oneof:"source"` // Labels that will be applied to newly imported DataItems. If an identical @@ -328,7 +327,6 @@ type ExportDataConfig struct { // The destination of the output. // // Types that are assignable to Destination: - // // *ExportDataConfig_GcsDestination Destination isExportDataConfig_Destination `protobuf_oneof:"destination"` // A filter on Annotations of the Dataset. Only Annotations on to-be-exported diff --git a/aiplatform/apiv1beta1/aiplatformpb/dataset_service.pb.go b/aiplatform/apiv1beta1/aiplatformpb/dataset_service.pb.go index 3e86aba4264f..c02392af5449 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/dataset_service.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/dataset_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/dataset_service.proto package aiplatformpb @@ -220,9 +220,9 @@ type UpdateDatasetRequest struct { // For the `FieldMask` definition, see [google.protobuf.FieldMask][google.protobuf.FieldMask]. // Updatable fields: // - // - `display_name` - // - `description` - // - `labels` + // * `display_name` + // * `description` + // * `labels` UpdateMask *fieldmaskpb.FieldMask `protobuf:"bytes,2,opt,name=update_mask,json=updateMask,proto3" json:"update_mask,omitempty"` } @@ -284,17 +284,17 @@ type ListDatasetsRequest struct { // An expression for filtering the results of the request. For field names // both snake_case and camelCase are supported. // - // - `display_name`: supports = and != - // - `metadata_schema_uri`: supports = and != - // - `labels` supports general map functions that is: - // - `labels.key=value` - key:value equality - // - `labels.key:* or labels:key - key existence - // - A key including a space must be quoted. `labels."a key"`. + // * `display_name`: supports = and != + // * `metadata_schema_uri`: supports = and != + // * `labels` supports general map functions that is: + // * `labels.key=value` - key:value equality + // * `labels.key:* or labels:key - key existence + // * A key including a space must be quoted. `labels."a key"`. // // Some examples: // - // - `displayName="myDisplayName"` - // - `labels.myKey="myValue"` + // * `displayName="myDisplayName"` + // * `labels.myKey="myValue"` Filter string `protobuf:"bytes,2,opt,name=filter,proto3" json:"filter,omitempty"` // The standard list page size. PageSize int32 `protobuf:"varint,3,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"` @@ -306,9 +306,9 @@ type ListDatasetsRequest struct { // Use "desc" after a field name for descending. // Supported fields: // - // - `display_name` - // - `create_time` - // - `update_time` + // * `display_name` + // * `create_time` + // * `update_time` OrderBy string `protobuf:"bytes,6,opt,name=order_by,json=orderBy,proto3" json:"order_by,omitempty"` } @@ -967,6 +967,364 @@ func (x *ListDataItemsResponse) GetNextPageToken() string { return "" } +// Request message for [DatasetService.SearchDataItems][google.cloud.aiplatform.v1beta1.DatasetService.SearchDataItems]. +type SearchDataItemsRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // Types that are assignable to Order: + // *SearchDataItemsRequest_OrderByDataItem + // *SearchDataItemsRequest_OrderByAnnotation_ + Order isSearchDataItemsRequest_Order `protobuf_oneof:"order"` + // Required. The resource name of the Dataset from which to search DataItems. + // Format: + // `projects/{project}/locations/{location}/datasets/{dataset}` + Dataset string `protobuf:"bytes,1,opt,name=dataset,proto3" json:"dataset,omitempty"` + // The resource name of a SavedQuery(annotation set in UI). + // Format: + // `projects/{project}/locations/{location}/datasets/{dataset}/savedQueries/{saved_query}` + // All of the search will be done in the context of this SavedQuery. + // + // Deprecated: Do not use. + SavedQuery string `protobuf:"bytes,2,opt,name=saved_query,json=savedQuery,proto3" json:"saved_query,omitempty"` + // The resource name of a DataLabelingJob. + // Format: + // `projects/{project}/locations/{location}/dataLabelingJobs/{data_labeling_job}` + // If this field is set, all of the search will be done in the context of + // this DataLabelingJob. + DataLabelingJob string `protobuf:"bytes,3,opt,name=data_labeling_job,json=dataLabelingJob,proto3" json:"data_labeling_job,omitempty"` + // An expression for filtering the DataItem that will be returned. + // + // * `data_item_id` - for = or !=. + // * `labeled` - for = or !=. + // * `has_annotation(ANNOTATION_SPEC_ID)` - true only for DataItem that + // have at least one annotation with annotation_spec_id = + // `ANNOTATION_SPEC_ID` in the context of SavedQuery or DataLabelingJob. + // + // For example: + // + // * `data_item=1` + // * `has_annotation(5)` + DataItemFilter string `protobuf:"bytes,4,opt,name=data_item_filter,json=dataItemFilter,proto3" json:"data_item_filter,omitempty"` + // An expression for filtering the Annotations that will be returned per + // DataItem. + // * `annotation_spec_id` - for = or !=. + // + // Deprecated: Do not use. + AnnotationsFilter string `protobuf:"bytes,5,opt,name=annotations_filter,json=annotationsFilter,proto3" json:"annotations_filter,omitempty"` + // An expression that specifies what Annotations will be returned per + // DataItem. Annotations satisfied either of the conditions will be returned. + // * `annotation_spec_id` - for = or !=. + // Must specify `saved_query_id=` - saved query id that annotations should + // belong to. + AnnotationFilters []string `protobuf:"bytes,11,rep,name=annotation_filters,json=annotationFilters,proto3" json:"annotation_filters,omitempty"` + // Mask specifying which fields of [DataItemView][google.cloud.aiplatform.v1beta1.DataItemView] to read. + FieldMask *fieldmaskpb.FieldMask `protobuf:"bytes,6,opt,name=field_mask,json=fieldMask,proto3" json:"field_mask,omitempty"` + // If set, only up to this many of Annotations will be returned per + // DataItemView. The maximum value is 1000. If not set, the maximum value will + // be used. + AnnotationsLimit int32 `protobuf:"varint,7,opt,name=annotations_limit,json=annotationsLimit,proto3" json:"annotations_limit,omitempty"` + // Requested page size. Server may return fewer results than requested. + // Default and maximum page size is 100. + PageSize int32 `protobuf:"varint,8,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"` + // A comma-separated list of fields to order by, sorted in ascending order. + // Use "desc" after a field name for descending. + // + // Deprecated: Do not use. + OrderBy string `protobuf:"bytes,9,opt,name=order_by,json=orderBy,proto3" json:"order_by,omitempty"` + // A token identifying a page of results for the server to return + // Typically obtained via + // [SearchDataItemsResponse.next_page_token][google.cloud.aiplatform.v1beta1.SearchDataItemsResponse.next_page_token] of the previous + // [DatasetService.SearchDataItems][google.cloud.aiplatform.v1beta1.DatasetService.SearchDataItems] call. + PageToken string `protobuf:"bytes,10,opt,name=page_token,json=pageToken,proto3" json:"page_token,omitempty"` +} + +func (x *SearchDataItemsRequest) Reset() { + *x = SearchDataItemsRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_google_cloud_aiplatform_v1beta1_dataset_service_proto_msgTypes[15] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *SearchDataItemsRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SearchDataItemsRequest) ProtoMessage() {} + +func (x *SearchDataItemsRequest) ProtoReflect() protoreflect.Message { + mi := &file_google_cloud_aiplatform_v1beta1_dataset_service_proto_msgTypes[15] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SearchDataItemsRequest.ProtoReflect.Descriptor instead. +func (*SearchDataItemsRequest) Descriptor() ([]byte, []int) { + return file_google_cloud_aiplatform_v1beta1_dataset_service_proto_rawDescGZIP(), []int{15} +} + +func (m *SearchDataItemsRequest) GetOrder() isSearchDataItemsRequest_Order { + if m != nil { + return m.Order + } + return nil +} + +func (x *SearchDataItemsRequest) GetOrderByDataItem() string { + if x, ok := x.GetOrder().(*SearchDataItemsRequest_OrderByDataItem); ok { + return x.OrderByDataItem + } + return "" +} + +func (x *SearchDataItemsRequest) GetOrderByAnnotation() *SearchDataItemsRequest_OrderByAnnotation { + if x, ok := x.GetOrder().(*SearchDataItemsRequest_OrderByAnnotation_); ok { + return x.OrderByAnnotation + } + return nil +} + +func (x *SearchDataItemsRequest) GetDataset() string { + if x != nil { + return x.Dataset + } + return "" +} + +// Deprecated: Do not use. +func (x *SearchDataItemsRequest) GetSavedQuery() string { + if x != nil { + return x.SavedQuery + } + return "" +} + +func (x *SearchDataItemsRequest) GetDataLabelingJob() string { + if x != nil { + return x.DataLabelingJob + } + return "" +} + +func (x *SearchDataItemsRequest) GetDataItemFilter() string { + if x != nil { + return x.DataItemFilter + } + return "" +} + +// Deprecated: Do not use. +func (x *SearchDataItemsRequest) GetAnnotationsFilter() string { + if x != nil { + return x.AnnotationsFilter + } + return "" +} + +func (x *SearchDataItemsRequest) GetAnnotationFilters() []string { + if x != nil { + return x.AnnotationFilters + } + return nil +} + +func (x *SearchDataItemsRequest) GetFieldMask() *fieldmaskpb.FieldMask { + if x != nil { + return x.FieldMask + } + return nil +} + +func (x *SearchDataItemsRequest) GetAnnotationsLimit() int32 { + if x != nil { + return x.AnnotationsLimit + } + return 0 +} + +func (x *SearchDataItemsRequest) GetPageSize() int32 { + if x != nil { + return x.PageSize + } + return 0 +} + +// Deprecated: Do not use. +func (x *SearchDataItemsRequest) GetOrderBy() string { + if x != nil { + return x.OrderBy + } + return "" +} + +func (x *SearchDataItemsRequest) GetPageToken() string { + if x != nil { + return x.PageToken + } + return "" +} + +type isSearchDataItemsRequest_Order interface { + isSearchDataItemsRequest_Order() +} + +type SearchDataItemsRequest_OrderByDataItem struct { + // A comma-separated list of data item fields to order by, sorted in + // ascending order. Use "desc" after a field name for descending. + OrderByDataItem string `protobuf:"bytes,12,opt,name=order_by_data_item,json=orderByDataItem,proto3,oneof"` +} + +type SearchDataItemsRequest_OrderByAnnotation_ struct { + // Expression that allows ranking results based on annotation's property. + OrderByAnnotation *SearchDataItemsRequest_OrderByAnnotation `protobuf:"bytes,13,opt,name=order_by_annotation,json=orderByAnnotation,proto3,oneof"` +} + +func (*SearchDataItemsRequest_OrderByDataItem) isSearchDataItemsRequest_Order() {} + +func (*SearchDataItemsRequest_OrderByAnnotation_) isSearchDataItemsRequest_Order() {} + +// Response message for [DatasetService.SearchDataItems][google.cloud.aiplatform.v1beta1.DatasetService.SearchDataItems]. +type SearchDataItemsResponse struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // The DataItemViews read. + DataItemViews []*DataItemView `protobuf:"bytes,1,rep,name=data_item_views,json=dataItemViews,proto3" json:"data_item_views,omitempty"` + // A token to retrieve next page of results. + // Pass to [SearchDataItemsRequest.page_token][google.cloud.aiplatform.v1beta1.SearchDataItemsRequest.page_token] to obtain that page. + NextPageToken string `protobuf:"bytes,2,opt,name=next_page_token,json=nextPageToken,proto3" json:"next_page_token,omitempty"` +} + +func (x *SearchDataItemsResponse) Reset() { + *x = SearchDataItemsResponse{} + if protoimpl.UnsafeEnabled { + mi := &file_google_cloud_aiplatform_v1beta1_dataset_service_proto_msgTypes[16] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *SearchDataItemsResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SearchDataItemsResponse) ProtoMessage() {} + +func (x *SearchDataItemsResponse) ProtoReflect() protoreflect.Message { + mi := &file_google_cloud_aiplatform_v1beta1_dataset_service_proto_msgTypes[16] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SearchDataItemsResponse.ProtoReflect.Descriptor instead. +func (*SearchDataItemsResponse) Descriptor() ([]byte, []int) { + return file_google_cloud_aiplatform_v1beta1_dataset_service_proto_rawDescGZIP(), []int{16} +} + +func (x *SearchDataItemsResponse) GetDataItemViews() []*DataItemView { + if x != nil { + return x.DataItemViews + } + return nil +} + +func (x *SearchDataItemsResponse) GetNextPageToken() string { + if x != nil { + return x.NextPageToken + } + return "" +} + +// A container for a single DataItem and Annotations on it. +type DataItemView struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // The DataItem. + DataItem *DataItem `protobuf:"bytes,1,opt,name=data_item,json=dataItem,proto3" json:"data_item,omitempty"` + // The Annotations on the DataItem. If too many Annotations should be returned + // for the DataItem, this field will be truncated per annotations_limit in + // request. If it was, then the has_truncated_annotations will be set to true. + Annotations []*Annotation `protobuf:"bytes,2,rep,name=annotations,proto3" json:"annotations,omitempty"` + // True if and only if the Annotations field has been truncated. It happens if + // more Annotations for this DataItem met the request's annotation_filter than + // are allowed to be returned by annotations_limit. + // Note that if Annotations field is not being returned due to field mask, + // then this field will not be set to true no matter how many Annotations are + // there. + HasTruncatedAnnotations bool `protobuf:"varint,3,opt,name=has_truncated_annotations,json=hasTruncatedAnnotations,proto3" json:"has_truncated_annotations,omitempty"` +} + +func (x *DataItemView) Reset() { + *x = DataItemView{} + if protoimpl.UnsafeEnabled { + mi := &file_google_cloud_aiplatform_v1beta1_dataset_service_proto_msgTypes[17] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *DataItemView) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*DataItemView) ProtoMessage() {} + +func (x *DataItemView) ProtoReflect() protoreflect.Message { + mi := &file_google_cloud_aiplatform_v1beta1_dataset_service_proto_msgTypes[17] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use DataItemView.ProtoReflect.Descriptor instead. +func (*DataItemView) Descriptor() ([]byte, []int) { + return file_google_cloud_aiplatform_v1beta1_dataset_service_proto_rawDescGZIP(), []int{17} +} + +func (x *DataItemView) GetDataItem() *DataItem { + if x != nil { + return x.DataItem + } + return nil +} + +func (x *DataItemView) GetAnnotations() []*Annotation { + if x != nil { + return x.Annotations + } + return nil +} + +func (x *DataItemView) GetHasTruncatedAnnotations() bool { + if x != nil { + return x.HasTruncatedAnnotations + } + return false +} + // Request message for [DatasetService.ListSavedQueries][google.cloud.aiplatform.v1beta1.DatasetService.ListSavedQueries]. type ListSavedQueriesRequest struct { state protoimpl.MessageState @@ -993,7 +1351,7 @@ type ListSavedQueriesRequest struct { func (x *ListSavedQueriesRequest) Reset() { *x = ListSavedQueriesRequest{} if protoimpl.UnsafeEnabled { - mi := &file_google_cloud_aiplatform_v1beta1_dataset_service_proto_msgTypes[15] + mi := &file_google_cloud_aiplatform_v1beta1_dataset_service_proto_msgTypes[18] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1006,7 +1364,7 @@ func (x *ListSavedQueriesRequest) String() string { func (*ListSavedQueriesRequest) ProtoMessage() {} func (x *ListSavedQueriesRequest) ProtoReflect() protoreflect.Message { - mi := &file_google_cloud_aiplatform_v1beta1_dataset_service_proto_msgTypes[15] + mi := &file_google_cloud_aiplatform_v1beta1_dataset_service_proto_msgTypes[18] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1019,7 +1377,7 @@ func (x *ListSavedQueriesRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ListSavedQueriesRequest.ProtoReflect.Descriptor instead. func (*ListSavedQueriesRequest) Descriptor() ([]byte, []int) { - return file_google_cloud_aiplatform_v1beta1_dataset_service_proto_rawDescGZIP(), []int{15} + return file_google_cloud_aiplatform_v1beta1_dataset_service_proto_rawDescGZIP(), []int{18} } func (x *ListSavedQueriesRequest) GetParent() string { @@ -1079,7 +1437,7 @@ type ListSavedQueriesResponse struct { func (x *ListSavedQueriesResponse) Reset() { *x = ListSavedQueriesResponse{} if protoimpl.UnsafeEnabled { - mi := &file_google_cloud_aiplatform_v1beta1_dataset_service_proto_msgTypes[16] + mi := &file_google_cloud_aiplatform_v1beta1_dataset_service_proto_msgTypes[19] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1092,7 +1450,7 @@ func (x *ListSavedQueriesResponse) String() string { func (*ListSavedQueriesResponse) ProtoMessage() {} func (x *ListSavedQueriesResponse) ProtoReflect() protoreflect.Message { - mi := &file_google_cloud_aiplatform_v1beta1_dataset_service_proto_msgTypes[16] + mi := &file_google_cloud_aiplatform_v1beta1_dataset_service_proto_msgTypes[19] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1105,7 +1463,7 @@ func (x *ListSavedQueriesResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ListSavedQueriesResponse.ProtoReflect.Descriptor instead. func (*ListSavedQueriesResponse) Descriptor() ([]byte, []int) { - return file_google_cloud_aiplatform_v1beta1_dataset_service_proto_rawDescGZIP(), []int{16} + return file_google_cloud_aiplatform_v1beta1_dataset_service_proto_rawDescGZIP(), []int{19} } func (x *ListSavedQueriesResponse) GetSavedQueries() []*SavedQuery { @@ -1139,7 +1497,7 @@ type GetAnnotationSpecRequest struct { func (x *GetAnnotationSpecRequest) Reset() { *x = GetAnnotationSpecRequest{} if protoimpl.UnsafeEnabled { - mi := &file_google_cloud_aiplatform_v1beta1_dataset_service_proto_msgTypes[17] + mi := &file_google_cloud_aiplatform_v1beta1_dataset_service_proto_msgTypes[20] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1152,7 +1510,7 @@ func (x *GetAnnotationSpecRequest) String() string { func (*GetAnnotationSpecRequest) ProtoMessage() {} func (x *GetAnnotationSpecRequest) ProtoReflect() protoreflect.Message { - mi := &file_google_cloud_aiplatform_v1beta1_dataset_service_proto_msgTypes[17] + mi := &file_google_cloud_aiplatform_v1beta1_dataset_service_proto_msgTypes[20] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1165,7 +1523,7 @@ func (x *GetAnnotationSpecRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use GetAnnotationSpecRequest.ProtoReflect.Descriptor instead. func (*GetAnnotationSpecRequest) Descriptor() ([]byte, []int) { - return file_google_cloud_aiplatform_v1beta1_dataset_service_proto_rawDescGZIP(), []int{17} + return file_google_cloud_aiplatform_v1beta1_dataset_service_proto_rawDescGZIP(), []int{20} } func (x *GetAnnotationSpecRequest) GetName() string { @@ -1208,7 +1566,7 @@ type ListAnnotationsRequest struct { func (x *ListAnnotationsRequest) Reset() { *x = ListAnnotationsRequest{} if protoimpl.UnsafeEnabled { - mi := &file_google_cloud_aiplatform_v1beta1_dataset_service_proto_msgTypes[18] + mi := &file_google_cloud_aiplatform_v1beta1_dataset_service_proto_msgTypes[21] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1221,7 +1579,7 @@ func (x *ListAnnotationsRequest) String() string { func (*ListAnnotationsRequest) ProtoMessage() {} func (x *ListAnnotationsRequest) ProtoReflect() protoreflect.Message { - mi := &file_google_cloud_aiplatform_v1beta1_dataset_service_proto_msgTypes[18] + mi := &file_google_cloud_aiplatform_v1beta1_dataset_service_proto_msgTypes[21] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1234,7 +1592,7 @@ func (x *ListAnnotationsRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ListAnnotationsRequest.ProtoReflect.Descriptor instead. func (*ListAnnotationsRequest) Descriptor() ([]byte, []int) { - return file_google_cloud_aiplatform_v1beta1_dataset_service_proto_rawDescGZIP(), []int{18} + return file_google_cloud_aiplatform_v1beta1_dataset_service_proto_rawDescGZIP(), []int{21} } func (x *ListAnnotationsRequest) GetParent() string { @@ -1294,7 +1652,7 @@ type ListAnnotationsResponse struct { func (x *ListAnnotationsResponse) Reset() { *x = ListAnnotationsResponse{} if protoimpl.UnsafeEnabled { - mi := &file_google_cloud_aiplatform_v1beta1_dataset_service_proto_msgTypes[19] + mi := &file_google_cloud_aiplatform_v1beta1_dataset_service_proto_msgTypes[22] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1307,7 +1665,7 @@ func (x *ListAnnotationsResponse) String() string { func (*ListAnnotationsResponse) ProtoMessage() {} func (x *ListAnnotationsResponse) ProtoReflect() protoreflect.Message { - mi := &file_google_cloud_aiplatform_v1beta1_dataset_service_proto_msgTypes[19] + mi := &file_google_cloud_aiplatform_v1beta1_dataset_service_proto_msgTypes[22] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1320,7 +1678,7 @@ func (x *ListAnnotationsResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ListAnnotationsResponse.ProtoReflect.Descriptor instead. func (*ListAnnotationsResponse) Descriptor() ([]byte, []int) { - return file_google_cloud_aiplatform_v1beta1_dataset_service_proto_rawDescGZIP(), []int{19} + return file_google_cloud_aiplatform_v1beta1_dataset_service_proto_rawDescGZIP(), []int{22} } func (x *ListAnnotationsResponse) GetAnnotations() []*Annotation { @@ -1337,6 +1695,67 @@ func (x *ListAnnotationsResponse) GetNextPageToken() string { return "" } +// Expression that allows ranking results based on annotation's property. +type SearchDataItemsRequest_OrderByAnnotation struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // Required. Saved query of the Annotation. Only Annotations belong to this saved + // query will be considered for ordering. + SavedQuery string `protobuf:"bytes,1,opt,name=saved_query,json=savedQuery,proto3" json:"saved_query,omitempty"` + // A comma-separated list of annotation fields to order by, sorted in + // ascending order. Use "desc" after a field name for descending. Must also + // specify saved_query. + OrderBy string `protobuf:"bytes,2,opt,name=order_by,json=orderBy,proto3" json:"order_by,omitempty"` +} + +func (x *SearchDataItemsRequest_OrderByAnnotation) Reset() { + *x = SearchDataItemsRequest_OrderByAnnotation{} + if protoimpl.UnsafeEnabled { + mi := &file_google_cloud_aiplatform_v1beta1_dataset_service_proto_msgTypes[23] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *SearchDataItemsRequest_OrderByAnnotation) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SearchDataItemsRequest_OrderByAnnotation) ProtoMessage() {} + +func (x *SearchDataItemsRequest_OrderByAnnotation) ProtoReflect() protoreflect.Message { + mi := &file_google_cloud_aiplatform_v1beta1_dataset_service_proto_msgTypes[23] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SearchDataItemsRequest_OrderByAnnotation.ProtoReflect.Descriptor instead. +func (*SearchDataItemsRequest_OrderByAnnotation) Descriptor() ([]byte, []int) { + return file_google_cloud_aiplatform_v1beta1_dataset_service_proto_rawDescGZIP(), []int{15, 0} +} + +func (x *SearchDataItemsRequest_OrderByAnnotation) GetSavedQuery() string { + if x != nil { + return x.SavedQuery + } + return "" +} + +func (x *SearchDataItemsRequest_OrderByAnnotation) GetOrderBy() string { + if x != nil { + return x.OrderBy + } + return "" +} + var File_google_cloud_aiplatform_v1beta1_dataset_service_proto protoreflect.FileDescriptor var file_google_cloud_aiplatform_v1beta1_dataset_service_proto_rawDesc = []byte{ @@ -1516,239 +1935,328 @@ var file_google_cloud_aiplatform_v1beta1_dataset_service_proto_rawDesc = []byte{ 0x49, 0x74, 0x65, 0x6d, 0x52, 0x09, 0x64, 0x61, 0x74, 0x61, 0x49, 0x74, 0x65, 0x6d, 0x73, 0x12, 0x26, 0x0a, 0x0f, 0x6e, 0x65, 0x78, 0x74, 0x5f, 0x70, 0x61, 0x67, 0x65, 0x5f, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0d, 0x6e, 0x65, 0x78, 0x74, 0x50, 0x61, - 0x67, 0x65, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x22, 0x84, 0x02, 0x0a, 0x17, 0x4c, 0x69, 0x73, 0x74, - 0x53, 0x61, 0x76, 0x65, 0x64, 0x51, 0x75, 0x65, 0x72, 0x69, 0x65, 0x73, 0x52, 0x65, 0x71, 0x75, - 0x65, 0x73, 0x74, 0x12, 0x41, 0x0a, 0x06, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x18, 0x01, 0x20, - 0x01, 0x28, 0x09, 0x42, 0x29, 0xe0, 0x41, 0x02, 0xfa, 0x41, 0x23, 0x0a, 0x21, 0x61, 0x69, 0x70, - 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, - 0x69, 0x73, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x44, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x52, 0x06, - 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x12, 0x16, 0x0a, 0x06, 0x66, 0x69, 0x6c, 0x74, 0x65, 0x72, - 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x66, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x12, 0x1b, - 0x0a, 0x09, 0x70, 0x61, 0x67, 0x65, 0x5f, 0x73, 0x69, 0x7a, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, - 0x05, 0x52, 0x08, 0x70, 0x61, 0x67, 0x65, 0x53, 0x69, 0x7a, 0x65, 0x12, 0x1d, 0x0a, 0x0a, 0x70, - 0x61, 0x67, 0x65, 0x5f, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, - 0x09, 0x70, 0x61, 0x67, 0x65, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x12, 0x37, 0x0a, 0x09, 0x72, 0x65, - 0x61, 0x64, 0x5f, 0x6d, 0x61, 0x73, 0x6b, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, + 0x67, 0x65, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x22, 0xb1, 0x06, 0x0a, 0x16, 0x53, 0x65, 0x61, 0x72, + 0x63, 0x68, 0x44, 0x61, 0x74, 0x61, 0x49, 0x74, 0x65, 0x6d, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, + 0x73, 0x74, 0x12, 0x2d, 0x0a, 0x12, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x5f, 0x62, 0x79, 0x5f, 0x64, + 0x61, 0x74, 0x61, 0x5f, 0x69, 0x74, 0x65, 0x6d, 0x18, 0x0c, 0x20, 0x01, 0x28, 0x09, 0x48, 0x00, + 0x52, 0x0f, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x42, 0x79, 0x44, 0x61, 0x74, 0x61, 0x49, 0x74, 0x65, + 0x6d, 0x12, 0x7b, 0x0a, 0x13, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x5f, 0x62, 0x79, 0x5f, 0x61, 0x6e, + 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x0d, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x49, + 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, 0x69, + 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, + 0x2e, 0x53, 0x65, 0x61, 0x72, 0x63, 0x68, 0x44, 0x61, 0x74, 0x61, 0x49, 0x74, 0x65, 0x6d, 0x73, + 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x2e, 0x4f, 0x72, 0x64, 0x65, 0x72, 0x42, 0x79, 0x41, + 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x48, 0x00, 0x52, 0x11, 0x6f, 0x72, 0x64, + 0x65, 0x72, 0x42, 0x79, 0x41, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x43, + 0x0a, 0x07, 0x64, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x42, + 0x29, 0xe0, 0x41, 0x02, 0xfa, 0x41, 0x23, 0x0a, 0x21, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, + 0x6f, 0x72, 0x6d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2e, 0x63, + 0x6f, 0x6d, 0x2f, 0x44, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x52, 0x07, 0x64, 0x61, 0x74, 0x61, + 0x73, 0x65, 0x74, 0x12, 0x4c, 0x0a, 0x0b, 0x73, 0x61, 0x76, 0x65, 0x64, 0x5f, 0x71, 0x75, 0x65, + 0x72, 0x79, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x42, 0x2b, 0x18, 0x01, 0xfa, 0x41, 0x26, 0x0a, + 0x24, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, + 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x53, 0x61, 0x76, 0x65, 0x64, + 0x51, 0x75, 0x65, 0x72, 0x79, 0x52, 0x0a, 0x73, 0x61, 0x76, 0x65, 0x64, 0x51, 0x75, 0x65, 0x72, + 0x79, 0x12, 0x2a, 0x0a, 0x11, 0x64, 0x61, 0x74, 0x61, 0x5f, 0x6c, 0x61, 0x62, 0x65, 0x6c, 0x69, + 0x6e, 0x67, 0x5f, 0x6a, 0x6f, 0x62, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0f, 0x64, 0x61, + 0x74, 0x61, 0x4c, 0x61, 0x62, 0x65, 0x6c, 0x69, 0x6e, 0x67, 0x4a, 0x6f, 0x62, 0x12, 0x28, 0x0a, + 0x10, 0x64, 0x61, 0x74, 0x61, 0x5f, 0x69, 0x74, 0x65, 0x6d, 0x5f, 0x66, 0x69, 0x6c, 0x74, 0x65, + 0x72, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0e, 0x64, 0x61, 0x74, 0x61, 0x49, 0x74, 0x65, + 0x6d, 0x46, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x12, 0x31, 0x0a, 0x12, 0x61, 0x6e, 0x6e, 0x6f, 0x74, + 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x5f, 0x66, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x18, 0x05, 0x20, + 0x01, 0x28, 0x09, 0x42, 0x02, 0x18, 0x01, 0x52, 0x11, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, + 0x69, 0x6f, 0x6e, 0x73, 0x46, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x12, 0x2d, 0x0a, 0x12, 0x61, 0x6e, + 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x66, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x73, + 0x18, 0x0b, 0x20, 0x03, 0x28, 0x09, 0x52, 0x11, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, + 0x6f, 0x6e, 0x46, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x73, 0x12, 0x39, 0x0a, 0x0a, 0x66, 0x69, 0x65, + 0x6c, 0x64, 0x5f, 0x6d, 0x61, 0x73, 0x6b, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, - 0x46, 0x69, 0x65, 0x6c, 0x64, 0x4d, 0x61, 0x73, 0x6b, 0x52, 0x08, 0x72, 0x65, 0x61, 0x64, 0x4d, - 0x61, 0x73, 0x6b, 0x12, 0x19, 0x0a, 0x08, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x5f, 0x62, 0x79, 0x18, - 0x06, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x42, 0x79, 0x22, 0x94, - 0x01, 0x0a, 0x18, 0x4c, 0x69, 0x73, 0x74, 0x53, 0x61, 0x76, 0x65, 0x64, 0x51, 0x75, 0x65, 0x72, - 0x69, 0x65, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x50, 0x0a, 0x0d, 0x73, - 0x61, 0x76, 0x65, 0x64, 0x5f, 0x71, 0x75, 0x65, 0x72, 0x69, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, - 0x28, 0x0b, 0x32, 0x2b, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, - 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x62, - 0x65, 0x74, 0x61, 0x31, 0x2e, 0x53, 0x61, 0x76, 0x65, 0x64, 0x51, 0x75, 0x65, 0x72, 0x79, 0x52, - 0x0c, 0x73, 0x61, 0x76, 0x65, 0x64, 0x51, 0x75, 0x65, 0x72, 0x69, 0x65, 0x73, 0x12, 0x26, 0x0a, - 0x0f, 0x6e, 0x65, 0x78, 0x74, 0x5f, 0x70, 0x61, 0x67, 0x65, 0x5f, 0x74, 0x6f, 0x6b, 0x65, 0x6e, - 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0d, 0x6e, 0x65, 0x78, 0x74, 0x50, 0x61, 0x67, 0x65, - 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x22, 0x99, 0x01, 0x0a, 0x18, 0x47, 0x65, 0x74, 0x41, 0x6e, 0x6e, - 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x53, 0x70, 0x65, 0x63, 0x52, 0x65, 0x71, 0x75, 0x65, - 0x73, 0x74, 0x12, 0x44, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, - 0x42, 0x30, 0xe0, 0x41, 0x02, 0xfa, 0x41, 0x2a, 0x0a, 0x28, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, - 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2e, - 0x63, 0x6f, 0x6d, 0x2f, 0x41, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x53, 0x70, - 0x65, 0x63, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x37, 0x0a, 0x09, 0x72, 0x65, 0x61, 0x64, - 0x5f, 0x6d, 0x61, 0x73, 0x6b, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, - 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x46, 0x69, - 0x65, 0x6c, 0x64, 0x4d, 0x61, 0x73, 0x6b, 0x52, 0x08, 0x72, 0x65, 0x61, 0x64, 0x4d, 0x61, 0x73, - 0x6b, 0x22, 0x84, 0x02, 0x0a, 0x16, 0x4c, 0x69, 0x73, 0x74, 0x41, 0x6e, 0x6e, 0x6f, 0x74, 0x61, - 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x42, 0x0a, 0x06, - 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x42, 0x2a, 0xe0, 0x41, - 0x02, 0xfa, 0x41, 0x24, 0x0a, 0x22, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, - 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, - 0x44, 0x61, 0x74, 0x61, 0x49, 0x74, 0x65, 0x6d, 0x52, 0x06, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, - 0x12, 0x16, 0x0a, 0x06, 0x66, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, - 0x52, 0x06, 0x66, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x12, 0x1b, 0x0a, 0x09, 0x70, 0x61, 0x67, 0x65, - 0x5f, 0x73, 0x69, 0x7a, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x05, 0x52, 0x08, 0x70, 0x61, 0x67, - 0x65, 0x53, 0x69, 0x7a, 0x65, 0x12, 0x1d, 0x0a, 0x0a, 0x70, 0x61, 0x67, 0x65, 0x5f, 0x74, 0x6f, - 0x6b, 0x65, 0x6e, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x70, 0x61, 0x67, 0x65, 0x54, - 0x6f, 0x6b, 0x65, 0x6e, 0x12, 0x37, 0x0a, 0x09, 0x72, 0x65, 0x61, 0x64, 0x5f, 0x6d, 0x61, 0x73, - 0x6b, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, - 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x4d, - 0x61, 0x73, 0x6b, 0x52, 0x08, 0x72, 0x65, 0x61, 0x64, 0x4d, 0x61, 0x73, 0x6b, 0x12, 0x19, 0x0a, - 0x08, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x5f, 0x62, 0x79, 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, 0x52, - 0x07, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x42, 0x79, 0x22, 0x90, 0x01, 0x0a, 0x17, 0x4c, 0x69, 0x73, - 0x74, 0x41, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x52, 0x65, 0x73, 0x70, - 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x4d, 0x0a, 0x0b, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, - 0x6f, 0x6e, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2b, 0x2e, 0x67, 0x6f, 0x6f, 0x67, - 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, - 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x41, 0x6e, 0x6e, 0x6f, - 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0b, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, - 0x6f, 0x6e, 0x73, 0x12, 0x26, 0x0a, 0x0f, 0x6e, 0x65, 0x78, 0x74, 0x5f, 0x70, 0x61, 0x67, 0x65, - 0x5f, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0d, 0x6e, 0x65, - 0x78, 0x74, 0x50, 0x61, 0x67, 0x65, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x32, 0xb7, 0x13, 0x0a, 0x0e, - 0x44, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0xe6, - 0x01, 0x0a, 0x0d, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x44, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, - 0x12, 0x35, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, + 0x46, 0x69, 0x65, 0x6c, 0x64, 0x4d, 0x61, 0x73, 0x6b, 0x52, 0x09, 0x66, 0x69, 0x65, 0x6c, 0x64, + 0x4d, 0x61, 0x73, 0x6b, 0x12, 0x2b, 0x0a, 0x11, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, + 0x6f, 0x6e, 0x73, 0x5f, 0x6c, 0x69, 0x6d, 0x69, 0x74, 0x18, 0x07, 0x20, 0x01, 0x28, 0x05, 0x52, + 0x10, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x4c, 0x69, 0x6d, 0x69, + 0x74, 0x12, 0x1b, 0x0a, 0x09, 0x70, 0x61, 0x67, 0x65, 0x5f, 0x73, 0x69, 0x7a, 0x65, 0x18, 0x08, + 0x20, 0x01, 0x28, 0x05, 0x52, 0x08, 0x70, 0x61, 0x67, 0x65, 0x53, 0x69, 0x7a, 0x65, 0x12, 0x1d, + 0x0a, 0x08, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x5f, 0x62, 0x79, 0x18, 0x09, 0x20, 0x01, 0x28, 0x09, + 0x42, 0x02, 0x18, 0x01, 0x52, 0x07, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x42, 0x79, 0x12, 0x1d, 0x0a, + 0x0a, 0x70, 0x61, 0x67, 0x65, 0x5f, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x18, 0x0a, 0x20, 0x01, 0x28, + 0x09, 0x52, 0x09, 0x70, 0x61, 0x67, 0x65, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x1a, 0x54, 0x0a, 0x11, + 0x4f, 0x72, 0x64, 0x65, 0x72, 0x42, 0x79, 0x41, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, + 0x6e, 0x12, 0x24, 0x0a, 0x0b, 0x73, 0x61, 0x76, 0x65, 0x64, 0x5f, 0x71, 0x75, 0x65, 0x72, 0x79, + 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x42, 0x03, 0xe0, 0x41, 0x02, 0x52, 0x0a, 0x73, 0x61, 0x76, + 0x65, 0x64, 0x51, 0x75, 0x65, 0x72, 0x79, 0x12, 0x19, 0x0a, 0x08, 0x6f, 0x72, 0x64, 0x65, 0x72, + 0x5f, 0x62, 0x79, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x6f, 0x72, 0x64, 0x65, 0x72, + 0x42, 0x79, 0x42, 0x07, 0x0a, 0x05, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x22, 0x98, 0x01, 0x0a, 0x17, + 0x53, 0x65, 0x61, 0x72, 0x63, 0x68, 0x44, 0x61, 0x74, 0x61, 0x49, 0x74, 0x65, 0x6d, 0x73, 0x52, + 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x55, 0x0a, 0x0f, 0x64, 0x61, 0x74, 0x61, 0x5f, + 0x69, 0x74, 0x65, 0x6d, 0x5f, 0x76, 0x69, 0x65, 0x77, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, + 0x32, 0x2d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x62, 0x65, 0x74, - 0x61, 0x31, 0x2e, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x44, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, - 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x1d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, - 0x2e, 0x6c, 0x6f, 0x6e, 0x67, 0x72, 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x2e, 0x4f, 0x70, 0x65, - 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x22, 0x7f, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x3c, 0x22, 0x31, - 0x2f, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2f, 0x7b, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, - 0x3d, 0x70, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x2f, 0x2a, 0x2f, 0x6c, 0x6f, 0x63, 0x61, - 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x2a, 0x7d, 0x2f, 0x64, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, - 0x73, 0x3a, 0x07, 0x64, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0xda, 0x41, 0x0e, 0x70, 0x61, 0x72, - 0x65, 0x6e, 0x74, 0x2c, 0x64, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0xca, 0x41, 0x29, 0x0a, 0x07, - 0x44, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x12, 0x1e, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x44, - 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x4f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x4d, - 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x12, 0xac, 0x01, 0x0a, 0x0a, 0x47, 0x65, 0x74, 0x44, - 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x12, 0x32, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, - 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, - 0x2e, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x47, 0x65, 0x74, 0x44, 0x61, 0x74, 0x61, - 0x73, 0x65, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x28, 0x2e, 0x67, 0x6f, 0x6f, + 0x61, 0x31, 0x2e, 0x44, 0x61, 0x74, 0x61, 0x49, 0x74, 0x65, 0x6d, 0x56, 0x69, 0x65, 0x77, 0x52, + 0x0d, 0x64, 0x61, 0x74, 0x61, 0x49, 0x74, 0x65, 0x6d, 0x56, 0x69, 0x65, 0x77, 0x73, 0x12, 0x26, + 0x0a, 0x0f, 0x6e, 0x65, 0x78, 0x74, 0x5f, 0x70, 0x61, 0x67, 0x65, 0x5f, 0x74, 0x6f, 0x6b, 0x65, + 0x6e, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0d, 0x6e, 0x65, 0x78, 0x74, 0x50, 0x61, 0x67, + 0x65, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x22, 0xe1, 0x01, 0x0a, 0x0c, 0x44, 0x61, 0x74, 0x61, 0x49, + 0x74, 0x65, 0x6d, 0x56, 0x69, 0x65, 0x77, 0x12, 0x46, 0x0a, 0x09, 0x64, 0x61, 0x74, 0x61, 0x5f, + 0x69, 0x74, 0x65, 0x6d, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x29, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x44, 0x61, 0x74, - 0x61, 0x73, 0x65, 0x74, 0x22, 0x40, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x33, 0x12, 0x31, 0x2f, 0x76, - 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2f, 0x7b, 0x6e, 0x61, 0x6d, 0x65, 0x3d, 0x70, 0x72, 0x6f, - 0x6a, 0x65, 0x63, 0x74, 0x73, 0x2f, 0x2a, 0x2f, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, - 0x73, 0x2f, 0x2a, 0x2f, 0x64, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x73, 0x2f, 0x2a, 0x7d, 0xda, - 0x41, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0xd2, 0x01, 0x0a, 0x0d, 0x55, 0x70, 0x64, 0x61, 0x74, - 0x65, 0x44, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x12, 0x35, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, - 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, - 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x55, 0x70, 0x64, 0x61, 0x74, - 0x65, 0x44, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, - 0x28, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, - 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, - 0x31, 0x2e, 0x44, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x22, 0x60, 0x82, 0xd3, 0xe4, 0x93, 0x02, - 0x44, 0x32, 0x39, 0x2f, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2f, 0x7b, 0x64, 0x61, 0x74, - 0x61, 0x73, 0x65, 0x74, 0x2e, 0x6e, 0x61, 0x6d, 0x65, 0x3d, 0x70, 0x72, 0x6f, 0x6a, 0x65, 0x63, - 0x74, 0x73, 0x2f, 0x2a, 0x2f, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x2a, - 0x2f, 0x64, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x73, 0x2f, 0x2a, 0x7d, 0x3a, 0x07, 0x64, 0x61, - 0x74, 0x61, 0x73, 0x65, 0x74, 0xda, 0x41, 0x13, 0x64, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x2c, - 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x5f, 0x6d, 0x61, 0x73, 0x6b, 0x12, 0xbf, 0x01, 0x0a, 0x0c, - 0x4c, 0x69, 0x73, 0x74, 0x44, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x73, 0x12, 0x34, 0x2e, 0x67, + 0x61, 0x49, 0x74, 0x65, 0x6d, 0x52, 0x08, 0x64, 0x61, 0x74, 0x61, 0x49, 0x74, 0x65, 0x6d, 0x12, + 0x4d, 0x0a, 0x0b, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x02, + 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2b, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, + 0x6f, 0x75, 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, + 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x41, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, + 0x6e, 0x52, 0x0b, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x3a, + 0x0a, 0x19, 0x68, 0x61, 0x73, 0x5f, 0x74, 0x72, 0x75, 0x6e, 0x63, 0x61, 0x74, 0x65, 0x64, 0x5f, + 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x03, 0x20, 0x01, 0x28, + 0x08, 0x52, 0x17, 0x68, 0x61, 0x73, 0x54, 0x72, 0x75, 0x6e, 0x63, 0x61, 0x74, 0x65, 0x64, 0x41, + 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x22, 0x84, 0x02, 0x0a, 0x17, 0x4c, + 0x69, 0x73, 0x74, 0x53, 0x61, 0x76, 0x65, 0x64, 0x51, 0x75, 0x65, 0x72, 0x69, 0x65, 0x73, 0x52, + 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x41, 0x0a, 0x06, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, + 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x42, 0x29, 0xe0, 0x41, 0x02, 0xfa, 0x41, 0x23, 0x0a, 0x21, + 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, + 0x65, 0x61, 0x70, 0x69, 0x73, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x44, 0x61, 0x74, 0x61, 0x73, 0x65, + 0x74, 0x52, 0x06, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x12, 0x16, 0x0a, 0x06, 0x66, 0x69, 0x6c, + 0x74, 0x65, 0x72, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x66, 0x69, 0x6c, 0x74, 0x65, + 0x72, 0x12, 0x1b, 0x0a, 0x09, 0x70, 0x61, 0x67, 0x65, 0x5f, 0x73, 0x69, 0x7a, 0x65, 0x18, 0x03, + 0x20, 0x01, 0x28, 0x05, 0x52, 0x08, 0x70, 0x61, 0x67, 0x65, 0x53, 0x69, 0x7a, 0x65, 0x12, 0x1d, + 0x0a, 0x0a, 0x70, 0x61, 0x67, 0x65, 0x5f, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x18, 0x04, 0x20, 0x01, + 0x28, 0x09, 0x52, 0x09, 0x70, 0x61, 0x67, 0x65, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x12, 0x37, 0x0a, + 0x09, 0x72, 0x65, 0x61, 0x64, 0x5f, 0x6d, 0x61, 0x73, 0x6b, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0b, + 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, + 0x75, 0x66, 0x2e, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x4d, 0x61, 0x73, 0x6b, 0x52, 0x08, 0x72, 0x65, + 0x61, 0x64, 0x4d, 0x61, 0x73, 0x6b, 0x12, 0x19, 0x0a, 0x08, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x5f, + 0x62, 0x79, 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x42, + 0x79, 0x22, 0x94, 0x01, 0x0a, 0x18, 0x4c, 0x69, 0x73, 0x74, 0x53, 0x61, 0x76, 0x65, 0x64, 0x51, + 0x75, 0x65, 0x72, 0x69, 0x65, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x50, + 0x0a, 0x0d, 0x73, 0x61, 0x76, 0x65, 0x64, 0x5f, 0x71, 0x75, 0x65, 0x72, 0x69, 0x65, 0x73, 0x18, + 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2b, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, + 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, + 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x53, 0x61, 0x76, 0x65, 0x64, 0x51, 0x75, 0x65, + 0x72, 0x79, 0x52, 0x0c, 0x73, 0x61, 0x76, 0x65, 0x64, 0x51, 0x75, 0x65, 0x72, 0x69, 0x65, 0x73, + 0x12, 0x26, 0x0a, 0x0f, 0x6e, 0x65, 0x78, 0x74, 0x5f, 0x70, 0x61, 0x67, 0x65, 0x5f, 0x74, 0x6f, + 0x6b, 0x65, 0x6e, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0d, 0x6e, 0x65, 0x78, 0x74, 0x50, + 0x61, 0x67, 0x65, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x22, 0x99, 0x01, 0x0a, 0x18, 0x47, 0x65, 0x74, + 0x41, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x53, 0x70, 0x65, 0x63, 0x52, 0x65, + 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x44, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, + 0x01, 0x28, 0x09, 0x42, 0x30, 0xe0, 0x41, 0x02, 0xfa, 0x41, 0x2a, 0x0a, 0x28, 0x61, 0x69, 0x70, + 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, + 0x69, 0x73, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x41, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, + 0x6e, 0x53, 0x70, 0x65, 0x63, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x37, 0x0a, 0x09, 0x72, + 0x65, 0x61, 0x64, 0x5f, 0x6d, 0x61, 0x73, 0x6b, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, + 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, + 0x2e, 0x46, 0x69, 0x65, 0x6c, 0x64, 0x4d, 0x61, 0x73, 0x6b, 0x52, 0x08, 0x72, 0x65, 0x61, 0x64, + 0x4d, 0x61, 0x73, 0x6b, 0x22, 0x84, 0x02, 0x0a, 0x16, 0x4c, 0x69, 0x73, 0x74, 0x41, 0x6e, 0x6e, + 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, + 0x42, 0x0a, 0x06, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x42, + 0x2a, 0xe0, 0x41, 0x02, 0xfa, 0x41, 0x24, 0x0a, 0x22, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, + 0x6f, 0x72, 0x6d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2e, 0x63, + 0x6f, 0x6d, 0x2f, 0x44, 0x61, 0x74, 0x61, 0x49, 0x74, 0x65, 0x6d, 0x52, 0x06, 0x70, 0x61, 0x72, + 0x65, 0x6e, 0x74, 0x12, 0x16, 0x0a, 0x06, 0x66, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x18, 0x02, 0x20, + 0x01, 0x28, 0x09, 0x52, 0x06, 0x66, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x12, 0x1b, 0x0a, 0x09, 0x70, + 0x61, 0x67, 0x65, 0x5f, 0x73, 0x69, 0x7a, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x05, 0x52, 0x08, + 0x70, 0x61, 0x67, 0x65, 0x53, 0x69, 0x7a, 0x65, 0x12, 0x1d, 0x0a, 0x0a, 0x70, 0x61, 0x67, 0x65, + 0x5f, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x70, 0x61, + 0x67, 0x65, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x12, 0x37, 0x0a, 0x09, 0x72, 0x65, 0x61, 0x64, 0x5f, + 0x6d, 0x61, 0x73, 0x6b, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, + 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x46, 0x69, 0x65, + 0x6c, 0x64, 0x4d, 0x61, 0x73, 0x6b, 0x52, 0x08, 0x72, 0x65, 0x61, 0x64, 0x4d, 0x61, 0x73, 0x6b, + 0x12, 0x19, 0x0a, 0x08, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x5f, 0x62, 0x79, 0x18, 0x06, 0x20, 0x01, + 0x28, 0x09, 0x52, 0x07, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x42, 0x79, 0x22, 0x90, 0x01, 0x0a, 0x17, + 0x4c, 0x69, 0x73, 0x74, 0x41, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x52, + 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x4d, 0x0a, 0x0b, 0x61, 0x6e, 0x6e, 0x6f, 0x74, + 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2b, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, - 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x4c, - 0x69, 0x73, 0x74, 0x44, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, - 0x73, 0x74, 0x1a, 0x35, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, - 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x62, - 0x65, 0x74, 0x61, 0x31, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x44, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, - 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x42, 0x82, 0xd3, 0xe4, 0x93, 0x02, - 0x33, 0x12, 0x31, 0x2f, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2f, 0x7b, 0x70, 0x61, 0x72, + 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x41, + 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0b, 0x61, 0x6e, 0x6e, 0x6f, 0x74, + 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x26, 0x0a, 0x0f, 0x6e, 0x65, 0x78, 0x74, 0x5f, 0x70, + 0x61, 0x67, 0x65, 0x5f, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, + 0x0d, 0x6e, 0x65, 0x78, 0x74, 0x50, 0x61, 0x67, 0x65, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x32, 0x8c, + 0x15, 0x0a, 0x0e, 0x44, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, + 0x65, 0x12, 0xe6, 0x01, 0x0a, 0x0d, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x44, 0x61, 0x74, 0x61, + 0x73, 0x65, 0x74, 0x12, 0x35, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, + 0x75, 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, + 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x44, 0x61, 0x74, 0x61, + 0x73, 0x65, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x1d, 0x2e, 0x67, 0x6f, 0x6f, + 0x67, 0x6c, 0x65, 0x2e, 0x6c, 0x6f, 0x6e, 0x67, 0x72, 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x2e, + 0x4f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x22, 0x7f, 0x82, 0xd3, 0xe4, 0x93, 0x02, + 0x3c, 0x22, 0x31, 0x2f, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2f, 0x7b, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x3d, 0x70, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x2f, 0x2a, 0x2f, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x2a, 0x7d, 0x2f, 0x64, 0x61, 0x74, 0x61, - 0x73, 0x65, 0x74, 0x73, 0xda, 0x41, 0x06, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x12, 0xda, 0x01, - 0x0a, 0x0d, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x44, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x12, - 0x35, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, - 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, - 0x31, 0x2e, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x44, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x52, - 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x1d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, - 0x6c, 0x6f, 0x6e, 0x67, 0x72, 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x2e, 0x4f, 0x70, 0x65, 0x72, - 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x22, 0x73, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x33, 0x2a, 0x31, 0x2f, - 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2f, 0x7b, 0x6e, 0x61, 0x6d, 0x65, 0x3d, 0x70, 0x72, - 0x6f, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x2f, 0x2a, 0x2f, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, - 0x6e, 0x73, 0x2f, 0x2a, 0x2f, 0x64, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x73, 0x2f, 0x2a, 0x7d, - 0xda, 0x41, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0xca, 0x41, 0x30, 0x0a, 0x15, 0x67, 0x6f, 0x6f, 0x67, - 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, - 0x79, 0x12, 0x17, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x4f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, - 0x6f, 0x6e, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x12, 0xef, 0x01, 0x0a, 0x0a, 0x49, - 0x6d, 0x70, 0x6f, 0x72, 0x74, 0x44, 0x61, 0x74, 0x61, 0x12, 0x32, 0x2e, 0x67, 0x6f, 0x6f, 0x67, + 0x73, 0x65, 0x74, 0x73, 0x3a, 0x07, 0x64, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0xda, 0x41, 0x0e, + 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x2c, 0x64, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0xca, 0x41, + 0x29, 0x0a, 0x07, 0x44, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x12, 0x1e, 0x43, 0x72, 0x65, 0x61, + 0x74, 0x65, 0x44, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x4f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, + 0x6f, 0x6e, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x12, 0xac, 0x01, 0x0a, 0x0a, 0x47, + 0x65, 0x74, 0x44, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x12, 0x32, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, - 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x49, 0x6d, 0x70, 0x6f, - 0x72, 0x74, 0x44, 0x61, 0x74, 0x61, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x1d, 0x2e, - 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x6c, 0x6f, 0x6e, 0x67, 0x72, 0x75, 0x6e, 0x6e, 0x69, - 0x6e, 0x67, 0x2e, 0x4f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x22, 0x8d, 0x01, 0x82, - 0xd3, 0xe4, 0x93, 0x02, 0x3d, 0x22, 0x38, 0x2f, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2f, - 0x7b, 0x6e, 0x61, 0x6d, 0x65, 0x3d, 0x70, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x2f, 0x2a, - 0x2f, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x2a, 0x2f, 0x64, 0x61, 0x74, - 0x61, 0x73, 0x65, 0x74, 0x73, 0x2f, 0x2a, 0x7d, 0x3a, 0x69, 0x6d, 0x70, 0x6f, 0x72, 0x74, 0x3a, - 0x01, 0x2a, 0xda, 0x41, 0x13, 0x6e, 0x61, 0x6d, 0x65, 0x2c, 0x69, 0x6d, 0x70, 0x6f, 0x72, 0x74, - 0x5f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x73, 0xca, 0x41, 0x31, 0x0a, 0x12, 0x49, 0x6d, 0x70, - 0x6f, 0x72, 0x74, 0x44, 0x61, 0x74, 0x61, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, - 0x1b, 0x49, 0x6d, 0x70, 0x6f, 0x72, 0x74, 0x44, 0x61, 0x74, 0x61, 0x4f, 0x70, 0x65, 0x72, 0x61, - 0x74, 0x69, 0x6f, 0x6e, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x12, 0xee, 0x01, 0x0a, - 0x0a, 0x45, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x44, 0x61, 0x74, 0x61, 0x12, 0x32, 0x2e, 0x67, 0x6f, - 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, 0x61, - 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x45, 0x78, - 0x70, 0x6f, 0x72, 0x74, 0x44, 0x61, 0x74, 0x61, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, - 0x1d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x6c, 0x6f, 0x6e, 0x67, 0x72, 0x75, 0x6e, - 0x6e, 0x69, 0x6e, 0x67, 0x2e, 0x4f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x22, 0x8c, - 0x01, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x3d, 0x22, 0x38, 0x2f, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, - 0x31, 0x2f, 0x7b, 0x6e, 0x61, 0x6d, 0x65, 0x3d, 0x70, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74, 0x73, - 0x2f, 0x2a, 0x2f, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x2a, 0x2f, 0x64, - 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x73, 0x2f, 0x2a, 0x7d, 0x3a, 0x65, 0x78, 0x70, 0x6f, 0x72, - 0x74, 0x3a, 0x01, 0x2a, 0xda, 0x41, 0x12, 0x6e, 0x61, 0x6d, 0x65, 0x2c, 0x65, 0x78, 0x70, 0x6f, - 0x72, 0x74, 0x5f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0xca, 0x41, 0x31, 0x0a, 0x12, 0x45, 0x78, - 0x70, 0x6f, 0x72, 0x74, 0x44, 0x61, 0x74, 0x61, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, - 0x12, 0x1b, 0x45, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x44, 0x61, 0x74, 0x61, 0x4f, 0x70, 0x65, 0x72, - 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x12, 0xce, 0x01, - 0x0a, 0x0d, 0x4c, 0x69, 0x73, 0x74, 0x44, 0x61, 0x74, 0x61, 0x49, 0x74, 0x65, 0x6d, 0x73, 0x12, - 0x35, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, - 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, - 0x31, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x44, 0x61, 0x74, 0x61, 0x49, 0x74, 0x65, 0x6d, 0x73, 0x52, - 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x36, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, - 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, - 0x2e, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x44, 0x61, 0x74, - 0x61, 0x49, 0x74, 0x65, 0x6d, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x4e, - 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x3f, 0x12, 0x3d, 0x2f, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, - 0x2f, 0x7b, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x3d, 0x70, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74, - 0x73, 0x2f, 0x2a, 0x2f, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x2a, 0x2f, - 0x64, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x73, 0x2f, 0x2a, 0x7d, 0x2f, 0x64, 0x61, 0x74, 0x61, - 0x49, 0x74, 0x65, 0x6d, 0x73, 0xda, 0x41, 0x06, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x12, 0xda, - 0x01, 0x0a, 0x10, 0x4c, 0x69, 0x73, 0x74, 0x53, 0x61, 0x76, 0x65, 0x64, 0x51, 0x75, 0x65, 0x72, - 0x69, 0x65, 0x73, 0x12, 0x38, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, - 0x75, 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, - 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x53, 0x61, 0x76, 0x65, 0x64, 0x51, - 0x75, 0x65, 0x72, 0x69, 0x65, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x39, 0x2e, + 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x47, 0x65, 0x74, 0x44, + 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x28, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, - 0x4c, 0x69, 0x73, 0x74, 0x53, 0x61, 0x76, 0x65, 0x64, 0x51, 0x75, 0x65, 0x72, 0x69, 0x65, 0x73, - 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x51, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x42, - 0x12, 0x40, 0x2f, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2f, 0x7b, 0x70, 0x61, 0x72, 0x65, - 0x6e, 0x74, 0x3d, 0x70, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x2f, 0x2a, 0x2f, 0x6c, 0x6f, - 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x2a, 0x2f, 0x64, 0x61, 0x74, 0x61, 0x73, 0x65, - 0x74, 0x73, 0x2f, 0x2a, 0x7d, 0x2f, 0x73, 0x61, 0x76, 0x65, 0x64, 0x51, 0x75, 0x65, 0x72, 0x69, - 0x65, 0x73, 0xda, 0x41, 0x06, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x12, 0xd3, 0x01, 0x0a, 0x11, - 0x47, 0x65, 0x74, 0x41, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x53, 0x70, 0x65, - 0x63, 0x12, 0x39, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, - 0x2e, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x62, 0x65, - 0x74, 0x61, 0x31, 0x2e, 0x47, 0x65, 0x74, 0x41, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, - 0x6e, 0x53, 0x70, 0x65, 0x63, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x2f, 0x2e, 0x67, + 0x44, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x22, 0x40, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x33, 0x12, + 0x31, 0x2f, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2f, 0x7b, 0x6e, 0x61, 0x6d, 0x65, 0x3d, + 0x70, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x2f, 0x2a, 0x2f, 0x6c, 0x6f, 0x63, 0x61, 0x74, + 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x2a, 0x2f, 0x64, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x73, 0x2f, + 0x2a, 0x7d, 0xda, 0x41, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0xd2, 0x01, 0x0a, 0x0d, 0x55, 0x70, + 0x64, 0x61, 0x74, 0x65, 0x44, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x12, 0x35, 0x2e, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, 0x61, + 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x55, 0x70, + 0x64, 0x61, 0x74, 0x65, 0x44, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, + 0x73, 0x74, 0x1a, 0x28, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, + 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x62, + 0x65, 0x74, 0x61, 0x31, 0x2e, 0x44, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x22, 0x60, 0x82, 0xd3, + 0xe4, 0x93, 0x02, 0x44, 0x32, 0x39, 0x2f, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2f, 0x7b, + 0x64, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x2e, 0x6e, 0x61, 0x6d, 0x65, 0x3d, 0x70, 0x72, 0x6f, + 0x6a, 0x65, 0x63, 0x74, 0x73, 0x2f, 0x2a, 0x2f, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, + 0x73, 0x2f, 0x2a, 0x2f, 0x64, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x73, 0x2f, 0x2a, 0x7d, 0x3a, + 0x07, 0x64, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0xda, 0x41, 0x13, 0x64, 0x61, 0x74, 0x61, 0x73, + 0x65, 0x74, 0x2c, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x5f, 0x6d, 0x61, 0x73, 0x6b, 0x12, 0xbf, + 0x01, 0x0a, 0x0c, 0x4c, 0x69, 0x73, 0x74, 0x44, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x73, 0x12, + 0x34, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, + 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, + 0x31, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x44, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x73, 0x52, 0x65, + 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x35, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, + 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, + 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x44, 0x61, 0x74, 0x61, + 0x73, 0x65, 0x74, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x42, 0x82, 0xd3, + 0xe4, 0x93, 0x02, 0x33, 0x12, 0x31, 0x2f, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2f, 0x7b, + 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x3d, 0x70, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x2f, + 0x2a, 0x2f, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x2a, 0x7d, 0x2f, 0x64, + 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x73, 0xda, 0x41, 0x06, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, + 0x12, 0xda, 0x01, 0x0a, 0x0d, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x44, 0x61, 0x74, 0x61, 0x73, + 0x65, 0x74, 0x12, 0x35, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, + 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x62, + 0x65, 0x74, 0x61, 0x31, 0x2e, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x44, 0x61, 0x74, 0x61, 0x73, + 0x65, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x1d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, + 0x6c, 0x65, 0x2e, 0x6c, 0x6f, 0x6e, 0x67, 0x72, 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x2e, 0x4f, + 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x22, 0x73, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x33, + 0x2a, 0x31, 0x2f, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2f, 0x7b, 0x6e, 0x61, 0x6d, 0x65, + 0x3d, 0x70, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x2f, 0x2a, 0x2f, 0x6c, 0x6f, 0x63, 0x61, + 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x2a, 0x2f, 0x64, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x73, + 0x2f, 0x2a, 0x7d, 0xda, 0x41, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0xca, 0x41, 0x30, 0x0a, 0x15, 0x67, + 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, + 0x6d, 0x70, 0x74, 0x79, 0x12, 0x17, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x4f, 0x70, 0x65, 0x72, + 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x12, 0xef, 0x01, + 0x0a, 0x0a, 0x49, 0x6d, 0x70, 0x6f, 0x72, 0x74, 0x44, 0x61, 0x74, 0x61, 0x12, 0x32, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, - 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x41, - 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x53, 0x70, 0x65, 0x63, 0x22, 0x52, 0x82, - 0xd3, 0xe4, 0x93, 0x02, 0x45, 0x12, 0x43, 0x2f, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2f, - 0x7b, 0x6e, 0x61, 0x6d, 0x65, 0x3d, 0x70, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x2f, 0x2a, - 0x2f, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x2a, 0x2f, 0x64, 0x61, 0x74, - 0x61, 0x73, 0x65, 0x74, 0x73, 0x2f, 0x2a, 0x2f, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, - 0x6f, 0x6e, 0x53, 0x70, 0x65, 0x63, 0x73, 0x2f, 0x2a, 0x7d, 0xda, 0x41, 0x04, 0x6e, 0x61, 0x6d, - 0x65, 0x12, 0xe2, 0x01, 0x0a, 0x0f, 0x4c, 0x69, 0x73, 0x74, 0x41, 0x6e, 0x6e, 0x6f, 0x74, 0x61, - 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x37, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, + 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x49, + 0x6d, 0x70, 0x6f, 0x72, 0x74, 0x44, 0x61, 0x74, 0x61, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, + 0x1a, 0x1d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x6c, 0x6f, 0x6e, 0x67, 0x72, 0x75, + 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x2e, 0x4f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x22, + 0x8d, 0x01, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x3d, 0x22, 0x38, 0x2f, 0x76, 0x31, 0x62, 0x65, 0x74, + 0x61, 0x31, 0x2f, 0x7b, 0x6e, 0x61, 0x6d, 0x65, 0x3d, 0x70, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74, + 0x73, 0x2f, 0x2a, 0x2f, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x2a, 0x2f, + 0x64, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x73, 0x2f, 0x2a, 0x7d, 0x3a, 0x69, 0x6d, 0x70, 0x6f, + 0x72, 0x74, 0x3a, 0x01, 0x2a, 0xda, 0x41, 0x13, 0x6e, 0x61, 0x6d, 0x65, 0x2c, 0x69, 0x6d, 0x70, + 0x6f, 0x72, 0x74, 0x5f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x73, 0xca, 0x41, 0x31, 0x0a, 0x12, + 0x49, 0x6d, 0x70, 0x6f, 0x72, 0x74, 0x44, 0x61, 0x74, 0x61, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, + 0x73, 0x65, 0x12, 0x1b, 0x49, 0x6d, 0x70, 0x6f, 0x72, 0x74, 0x44, 0x61, 0x74, 0x61, 0x4f, 0x70, + 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x12, + 0xee, 0x01, 0x0a, 0x0a, 0x45, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x44, 0x61, 0x74, 0x61, 0x12, 0x32, + 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, 0x69, + 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, + 0x2e, 0x45, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x44, 0x61, 0x74, 0x61, 0x52, 0x65, 0x71, 0x75, 0x65, + 0x73, 0x74, 0x1a, 0x1d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x6c, 0x6f, 0x6e, 0x67, + 0x72, 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x2e, 0x4f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, + 0x6e, 0x22, 0x8c, 0x01, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x3d, 0x22, 0x38, 0x2f, 0x76, 0x31, 0x62, + 0x65, 0x74, 0x61, 0x31, 0x2f, 0x7b, 0x6e, 0x61, 0x6d, 0x65, 0x3d, 0x70, 0x72, 0x6f, 0x6a, 0x65, + 0x63, 0x74, 0x73, 0x2f, 0x2a, 0x2f, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, + 0x2a, 0x2f, 0x64, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x73, 0x2f, 0x2a, 0x7d, 0x3a, 0x65, 0x78, + 0x70, 0x6f, 0x72, 0x74, 0x3a, 0x01, 0x2a, 0xda, 0x41, 0x12, 0x6e, 0x61, 0x6d, 0x65, 0x2c, 0x65, + 0x78, 0x70, 0x6f, 0x72, 0x74, 0x5f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0xca, 0x41, 0x31, 0x0a, + 0x12, 0x45, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x44, 0x61, 0x74, 0x61, 0x52, 0x65, 0x73, 0x70, 0x6f, + 0x6e, 0x73, 0x65, 0x12, 0x1b, 0x45, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x44, 0x61, 0x74, 0x61, 0x4f, + 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, + 0x12, 0xce, 0x01, 0x0a, 0x0d, 0x4c, 0x69, 0x73, 0x74, 0x44, 0x61, 0x74, 0x61, 0x49, 0x74, 0x65, + 0x6d, 0x73, 0x12, 0x35, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, + 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x62, + 0x65, 0x74, 0x61, 0x31, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x44, 0x61, 0x74, 0x61, 0x49, 0x74, 0x65, + 0x6d, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x36, 0x2e, 0x67, 0x6f, 0x6f, 0x67, + 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, + 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x4c, 0x69, 0x73, 0x74, + 0x44, 0x61, 0x74, 0x61, 0x49, 0x74, 0x65, 0x6d, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, + 0x65, 0x22, 0x4e, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x3f, 0x12, 0x3d, 0x2f, 0x76, 0x31, 0x62, 0x65, + 0x74, 0x61, 0x31, 0x2f, 0x7b, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x3d, 0x70, 0x72, 0x6f, 0x6a, + 0x65, 0x63, 0x74, 0x73, 0x2f, 0x2a, 0x2f, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, + 0x2f, 0x2a, 0x2f, 0x64, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x73, 0x2f, 0x2a, 0x7d, 0x2f, 0x64, + 0x61, 0x74, 0x61, 0x49, 0x74, 0x65, 0x6d, 0x73, 0xda, 0x41, 0x06, 0x70, 0x61, 0x72, 0x65, 0x6e, + 0x74, 0x12, 0xd2, 0x01, 0x0a, 0x0f, 0x53, 0x65, 0x61, 0x72, 0x63, 0x68, 0x44, 0x61, 0x74, 0x61, + 0x49, 0x74, 0x65, 0x6d, 0x73, 0x12, 0x37, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, - 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x41, 0x6e, 0x6e, 0x6f, - 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x38, + 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x53, 0x65, 0x61, 0x72, 0x63, 0x68, 0x44, 0x61, + 0x74, 0x61, 0x49, 0x74, 0x65, 0x6d, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x38, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, - 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x41, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, - 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x5c, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x4d, - 0x12, 0x4b, 0x2f, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2f, 0x7b, 0x70, 0x61, 0x72, 0x65, - 0x6e, 0x74, 0x3d, 0x70, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x2f, 0x2a, 0x2f, 0x6c, 0x6f, - 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x2a, 0x2f, 0x64, 0x61, 0x74, 0x61, 0x73, 0x65, - 0x74, 0x73, 0x2f, 0x2a, 0x2f, 0x64, 0x61, 0x74, 0x61, 0x49, 0x74, 0x65, 0x6d, 0x73, 0x2f, 0x2a, - 0x7d, 0x2f, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0xda, 0x41, 0x06, - 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x1a, 0x4d, 0xca, 0x41, 0x19, 0x61, 0x69, 0x70, 0x6c, 0x61, - 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, - 0x2e, 0x63, 0x6f, 0x6d, 0xd2, 0x41, 0x2e, 0x68, 0x74, 0x74, 0x70, 0x73, 0x3a, 0x2f, 0x2f, 0x77, - 0x77, 0x77, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2e, 0x63, 0x6f, - 0x6d, 0x2f, 0x61, 0x75, 0x74, 0x68, 0x2f, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2d, 0x70, 0x6c, 0x61, - 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x42, 0xf0, 0x01, 0x0a, 0x23, 0x63, 0x6f, 0x6d, 0x2e, 0x67, 0x6f, + 0x2e, 0x53, 0x65, 0x61, 0x72, 0x63, 0x68, 0x44, 0x61, 0x74, 0x61, 0x49, 0x74, 0x65, 0x6d, 0x73, + 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x4c, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x46, + 0x12, 0x44, 0x2f, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2f, 0x7b, 0x64, 0x61, 0x74, 0x61, + 0x73, 0x65, 0x74, 0x3d, 0x70, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x2f, 0x2a, 0x2f, 0x6c, + 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x2a, 0x2f, 0x64, 0x61, 0x74, 0x61, 0x73, + 0x65, 0x74, 0x73, 0x2f, 0x2a, 0x7d, 0x3a, 0x73, 0x65, 0x61, 0x72, 0x63, 0x68, 0x44, 0x61, 0x74, + 0x61, 0x49, 0x74, 0x65, 0x6d, 0x73, 0x12, 0xda, 0x01, 0x0a, 0x10, 0x4c, 0x69, 0x73, 0x74, 0x53, + 0x61, 0x76, 0x65, 0x64, 0x51, 0x75, 0x65, 0x72, 0x69, 0x65, 0x73, 0x12, 0x38, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, 0x61, - 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x42, 0x13, 0x44, - 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x50, 0x72, 0x6f, - 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x49, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x67, 0x6f, 0x6c, - 0x61, 0x6e, 0x67, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x67, 0x65, 0x6e, 0x70, 0x72, 0x6f, 0x74, 0x6f, - 0x2f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2f, 0x63, 0x6c, 0x6f, 0x75, - 0x64, 0x2f, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2f, 0x76, 0x31, 0x62, - 0x65, 0x74, 0x61, 0x31, 0x3b, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0xaa, - 0x02, 0x1f, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x43, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x41, - 0x49, 0x50, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x56, 0x31, 0x42, 0x65, 0x74, 0x61, - 0x31, 0xca, 0x02, 0x1f, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x5c, 0x43, 0x6c, 0x6f, 0x75, 0x64, - 0x5c, 0x41, 0x49, 0x50, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x5c, 0x56, 0x31, 0x62, 0x65, - 0x74, 0x61, 0x31, 0xea, 0x02, 0x22, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x3a, 0x3a, 0x43, 0x6c, - 0x6f, 0x75, 0x64, 0x3a, 0x3a, 0x41, 0x49, 0x50, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x3a, - 0x3a, 0x56, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, + 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x4c, 0x69, + 0x73, 0x74, 0x53, 0x61, 0x76, 0x65, 0x64, 0x51, 0x75, 0x65, 0x72, 0x69, 0x65, 0x73, 0x52, 0x65, + 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x39, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, + 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, + 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x53, 0x61, 0x76, 0x65, + 0x64, 0x51, 0x75, 0x65, 0x72, 0x69, 0x65, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, + 0x22, 0x51, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x42, 0x12, 0x40, 0x2f, 0x76, 0x31, 0x62, 0x65, 0x74, + 0x61, 0x31, 0x2f, 0x7b, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x3d, 0x70, 0x72, 0x6f, 0x6a, 0x65, + 0x63, 0x74, 0x73, 0x2f, 0x2a, 0x2f, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, + 0x2a, 0x2f, 0x64, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x73, 0x2f, 0x2a, 0x7d, 0x2f, 0x73, 0x61, + 0x76, 0x65, 0x64, 0x51, 0x75, 0x65, 0x72, 0x69, 0x65, 0x73, 0xda, 0x41, 0x06, 0x70, 0x61, 0x72, + 0x65, 0x6e, 0x74, 0x12, 0xd3, 0x01, 0x0a, 0x11, 0x47, 0x65, 0x74, 0x41, 0x6e, 0x6e, 0x6f, 0x74, + 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x53, 0x70, 0x65, 0x63, 0x12, 0x39, 0x2e, 0x67, 0x6f, 0x6f, 0x67, + 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, + 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x47, 0x65, 0x74, 0x41, + 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x53, 0x70, 0x65, 0x63, 0x52, 0x65, 0x71, + 0x75, 0x65, 0x73, 0x74, 0x1a, 0x2f, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, + 0x6f, 0x75, 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, + 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x41, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, + 0x6e, 0x53, 0x70, 0x65, 0x63, 0x22, 0x52, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x45, 0x12, 0x43, 0x2f, + 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2f, 0x7b, 0x6e, 0x61, 0x6d, 0x65, 0x3d, 0x70, 0x72, + 0x6f, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x2f, 0x2a, 0x2f, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, + 0x6e, 0x73, 0x2f, 0x2a, 0x2f, 0x64, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x73, 0x2f, 0x2a, 0x2f, + 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x53, 0x70, 0x65, 0x63, 0x73, 0x2f, + 0x2a, 0x7d, 0xda, 0x41, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0xe2, 0x01, 0x0a, 0x0f, 0x4c, 0x69, + 0x73, 0x74, 0x41, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x37, 0x2e, + 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, 0x69, 0x70, + 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, + 0x4c, 0x69, 0x73, 0x74, 0x41, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x52, + 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x38, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, + 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, + 0x2e, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x41, 0x6e, 0x6e, + 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, + 0x22, 0x5c, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x4d, 0x12, 0x4b, 0x2f, 0x76, 0x31, 0x62, 0x65, 0x74, + 0x61, 0x31, 0x2f, 0x7b, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x3d, 0x70, 0x72, 0x6f, 0x6a, 0x65, + 0x63, 0x74, 0x73, 0x2f, 0x2a, 0x2f, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, + 0x2a, 0x2f, 0x64, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x73, 0x2f, 0x2a, 0x2f, 0x64, 0x61, 0x74, + 0x61, 0x49, 0x74, 0x65, 0x6d, 0x73, 0x2f, 0x2a, 0x7d, 0x2f, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, + 0x74, 0x69, 0x6f, 0x6e, 0x73, 0xda, 0x41, 0x06, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x1a, 0x4d, + 0xca, 0x41, 0x19, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2e, 0x63, 0x6f, 0x6d, 0xd2, 0x41, 0x2e, 0x68, + 0x74, 0x74, 0x70, 0x73, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, + 0x65, 0x61, 0x70, 0x69, 0x73, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x61, 0x75, 0x74, 0x68, 0x2f, 0x63, + 0x6c, 0x6f, 0x75, 0x64, 0x2d, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x42, 0xf0, 0x01, + 0x0a, 0x23, 0x63, 0x6f, 0x6d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, + 0x75, 0x64, 0x2e, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x2e, 0x76, 0x31, + 0x62, 0x65, 0x74, 0x61, 0x31, 0x42, 0x13, 0x44, 0x61, 0x74, 0x61, 0x73, 0x65, 0x74, 0x53, 0x65, + 0x72, 0x76, 0x69, 0x63, 0x65, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x49, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2e, 0x6f, 0x72, 0x67, 0x2f, + 0x67, 0x65, 0x6e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, + 0x70, 0x69, 0x73, 0x2f, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2f, 0x61, 0x69, 0x70, 0x6c, 0x61, 0x74, + 0x66, 0x6f, 0x72, 0x6d, 0x2f, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x3b, 0x61, 0x69, 0x70, + 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0xaa, 0x02, 0x1f, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, + 0x2e, 0x43, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x41, 0x49, 0x50, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, + 0x6d, 0x2e, 0x56, 0x31, 0x42, 0x65, 0x74, 0x61, 0x31, 0xca, 0x02, 0x1f, 0x47, 0x6f, 0x6f, 0x67, + 0x6c, 0x65, 0x5c, 0x43, 0x6c, 0x6f, 0x75, 0x64, 0x5c, 0x41, 0x49, 0x50, 0x6c, 0x61, 0x74, 0x66, + 0x6f, 0x72, 0x6d, 0x5c, 0x56, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0xea, 0x02, 0x22, 0x47, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x3a, 0x3a, 0x43, 0x6c, 0x6f, 0x75, 0x64, 0x3a, 0x3a, 0x41, 0x49, 0x50, + 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x3a, 0x3a, 0x56, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, + 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( @@ -1763,85 +2271,96 @@ func file_google_cloud_aiplatform_v1beta1_dataset_service_proto_rawDescGZIP() [] return file_google_cloud_aiplatform_v1beta1_dataset_service_proto_rawDescData } -var file_google_cloud_aiplatform_v1beta1_dataset_service_proto_msgTypes = make([]protoimpl.MessageInfo, 20) +var file_google_cloud_aiplatform_v1beta1_dataset_service_proto_msgTypes = make([]protoimpl.MessageInfo, 24) var file_google_cloud_aiplatform_v1beta1_dataset_service_proto_goTypes = []interface{}{ - (*CreateDatasetRequest)(nil), // 0: google.cloud.aiplatform.v1beta1.CreateDatasetRequest - (*CreateDatasetOperationMetadata)(nil), // 1: google.cloud.aiplatform.v1beta1.CreateDatasetOperationMetadata - (*GetDatasetRequest)(nil), // 2: google.cloud.aiplatform.v1beta1.GetDatasetRequest - (*UpdateDatasetRequest)(nil), // 3: google.cloud.aiplatform.v1beta1.UpdateDatasetRequest - (*ListDatasetsRequest)(nil), // 4: google.cloud.aiplatform.v1beta1.ListDatasetsRequest - (*ListDatasetsResponse)(nil), // 5: google.cloud.aiplatform.v1beta1.ListDatasetsResponse - (*DeleteDatasetRequest)(nil), // 6: google.cloud.aiplatform.v1beta1.DeleteDatasetRequest - (*ImportDataRequest)(nil), // 7: google.cloud.aiplatform.v1beta1.ImportDataRequest - (*ImportDataResponse)(nil), // 8: google.cloud.aiplatform.v1beta1.ImportDataResponse - (*ImportDataOperationMetadata)(nil), // 9: google.cloud.aiplatform.v1beta1.ImportDataOperationMetadata - (*ExportDataRequest)(nil), // 10: google.cloud.aiplatform.v1beta1.ExportDataRequest - (*ExportDataResponse)(nil), // 11: google.cloud.aiplatform.v1beta1.ExportDataResponse - (*ExportDataOperationMetadata)(nil), // 12: google.cloud.aiplatform.v1beta1.ExportDataOperationMetadata - (*ListDataItemsRequest)(nil), // 13: google.cloud.aiplatform.v1beta1.ListDataItemsRequest - (*ListDataItemsResponse)(nil), // 14: google.cloud.aiplatform.v1beta1.ListDataItemsResponse - (*ListSavedQueriesRequest)(nil), // 15: google.cloud.aiplatform.v1beta1.ListSavedQueriesRequest - (*ListSavedQueriesResponse)(nil), // 16: google.cloud.aiplatform.v1beta1.ListSavedQueriesResponse - (*GetAnnotationSpecRequest)(nil), // 17: google.cloud.aiplatform.v1beta1.GetAnnotationSpecRequest - (*ListAnnotationsRequest)(nil), // 18: google.cloud.aiplatform.v1beta1.ListAnnotationsRequest - (*ListAnnotationsResponse)(nil), // 19: google.cloud.aiplatform.v1beta1.ListAnnotationsResponse - (*Dataset)(nil), // 20: google.cloud.aiplatform.v1beta1.Dataset - (*GenericOperationMetadata)(nil), // 21: google.cloud.aiplatform.v1beta1.GenericOperationMetadata - (*fieldmaskpb.FieldMask)(nil), // 22: google.protobuf.FieldMask - (*ImportDataConfig)(nil), // 23: google.cloud.aiplatform.v1beta1.ImportDataConfig - (*ExportDataConfig)(nil), // 24: google.cloud.aiplatform.v1beta1.ExportDataConfig - (*DataItem)(nil), // 25: google.cloud.aiplatform.v1beta1.DataItem - (*SavedQuery)(nil), // 26: google.cloud.aiplatform.v1beta1.SavedQuery - (*Annotation)(nil), // 27: google.cloud.aiplatform.v1beta1.Annotation - (*longrunning.Operation)(nil), // 28: google.longrunning.Operation - (*AnnotationSpec)(nil), // 29: google.cloud.aiplatform.v1beta1.AnnotationSpec + (*CreateDatasetRequest)(nil), // 0: google.cloud.aiplatform.v1beta1.CreateDatasetRequest + (*CreateDatasetOperationMetadata)(nil), // 1: google.cloud.aiplatform.v1beta1.CreateDatasetOperationMetadata + (*GetDatasetRequest)(nil), // 2: google.cloud.aiplatform.v1beta1.GetDatasetRequest + (*UpdateDatasetRequest)(nil), // 3: google.cloud.aiplatform.v1beta1.UpdateDatasetRequest + (*ListDatasetsRequest)(nil), // 4: google.cloud.aiplatform.v1beta1.ListDatasetsRequest + (*ListDatasetsResponse)(nil), // 5: google.cloud.aiplatform.v1beta1.ListDatasetsResponse + (*DeleteDatasetRequest)(nil), // 6: google.cloud.aiplatform.v1beta1.DeleteDatasetRequest + (*ImportDataRequest)(nil), // 7: google.cloud.aiplatform.v1beta1.ImportDataRequest + (*ImportDataResponse)(nil), // 8: google.cloud.aiplatform.v1beta1.ImportDataResponse + (*ImportDataOperationMetadata)(nil), // 9: google.cloud.aiplatform.v1beta1.ImportDataOperationMetadata + (*ExportDataRequest)(nil), // 10: google.cloud.aiplatform.v1beta1.ExportDataRequest + (*ExportDataResponse)(nil), // 11: google.cloud.aiplatform.v1beta1.ExportDataResponse + (*ExportDataOperationMetadata)(nil), // 12: google.cloud.aiplatform.v1beta1.ExportDataOperationMetadata + (*ListDataItemsRequest)(nil), // 13: google.cloud.aiplatform.v1beta1.ListDataItemsRequest + (*ListDataItemsResponse)(nil), // 14: google.cloud.aiplatform.v1beta1.ListDataItemsResponse + (*SearchDataItemsRequest)(nil), // 15: google.cloud.aiplatform.v1beta1.SearchDataItemsRequest + (*SearchDataItemsResponse)(nil), // 16: google.cloud.aiplatform.v1beta1.SearchDataItemsResponse + (*DataItemView)(nil), // 17: google.cloud.aiplatform.v1beta1.DataItemView + (*ListSavedQueriesRequest)(nil), // 18: google.cloud.aiplatform.v1beta1.ListSavedQueriesRequest + (*ListSavedQueriesResponse)(nil), // 19: google.cloud.aiplatform.v1beta1.ListSavedQueriesResponse + (*GetAnnotationSpecRequest)(nil), // 20: google.cloud.aiplatform.v1beta1.GetAnnotationSpecRequest + (*ListAnnotationsRequest)(nil), // 21: google.cloud.aiplatform.v1beta1.ListAnnotationsRequest + (*ListAnnotationsResponse)(nil), // 22: google.cloud.aiplatform.v1beta1.ListAnnotationsResponse + (*SearchDataItemsRequest_OrderByAnnotation)(nil), // 23: google.cloud.aiplatform.v1beta1.SearchDataItemsRequest.OrderByAnnotation + (*Dataset)(nil), // 24: google.cloud.aiplatform.v1beta1.Dataset + (*GenericOperationMetadata)(nil), // 25: google.cloud.aiplatform.v1beta1.GenericOperationMetadata + (*fieldmaskpb.FieldMask)(nil), // 26: google.protobuf.FieldMask + (*ImportDataConfig)(nil), // 27: google.cloud.aiplatform.v1beta1.ImportDataConfig + (*ExportDataConfig)(nil), // 28: google.cloud.aiplatform.v1beta1.ExportDataConfig + (*DataItem)(nil), // 29: google.cloud.aiplatform.v1beta1.DataItem + (*Annotation)(nil), // 30: google.cloud.aiplatform.v1beta1.Annotation + (*SavedQuery)(nil), // 31: google.cloud.aiplatform.v1beta1.SavedQuery + (*longrunning.Operation)(nil), // 32: google.longrunning.Operation + (*AnnotationSpec)(nil), // 33: google.cloud.aiplatform.v1beta1.AnnotationSpec } var file_google_cloud_aiplatform_v1beta1_dataset_service_proto_depIdxs = []int32{ - 20, // 0: google.cloud.aiplatform.v1beta1.CreateDatasetRequest.dataset:type_name -> google.cloud.aiplatform.v1beta1.Dataset - 21, // 1: google.cloud.aiplatform.v1beta1.CreateDatasetOperationMetadata.generic_metadata:type_name -> google.cloud.aiplatform.v1beta1.GenericOperationMetadata - 22, // 2: google.cloud.aiplatform.v1beta1.GetDatasetRequest.read_mask:type_name -> google.protobuf.FieldMask - 20, // 3: google.cloud.aiplatform.v1beta1.UpdateDatasetRequest.dataset:type_name -> google.cloud.aiplatform.v1beta1.Dataset - 22, // 4: google.cloud.aiplatform.v1beta1.UpdateDatasetRequest.update_mask:type_name -> google.protobuf.FieldMask - 22, // 5: google.cloud.aiplatform.v1beta1.ListDatasetsRequest.read_mask:type_name -> google.protobuf.FieldMask - 20, // 6: google.cloud.aiplatform.v1beta1.ListDatasetsResponse.datasets:type_name -> google.cloud.aiplatform.v1beta1.Dataset - 23, // 7: google.cloud.aiplatform.v1beta1.ImportDataRequest.import_configs:type_name -> google.cloud.aiplatform.v1beta1.ImportDataConfig - 21, // 8: google.cloud.aiplatform.v1beta1.ImportDataOperationMetadata.generic_metadata:type_name -> google.cloud.aiplatform.v1beta1.GenericOperationMetadata - 24, // 9: google.cloud.aiplatform.v1beta1.ExportDataRequest.export_config:type_name -> google.cloud.aiplatform.v1beta1.ExportDataConfig - 21, // 10: google.cloud.aiplatform.v1beta1.ExportDataOperationMetadata.generic_metadata:type_name -> google.cloud.aiplatform.v1beta1.GenericOperationMetadata - 22, // 11: google.cloud.aiplatform.v1beta1.ListDataItemsRequest.read_mask:type_name -> google.protobuf.FieldMask - 25, // 12: google.cloud.aiplatform.v1beta1.ListDataItemsResponse.data_items:type_name -> google.cloud.aiplatform.v1beta1.DataItem - 22, // 13: google.cloud.aiplatform.v1beta1.ListSavedQueriesRequest.read_mask:type_name -> google.protobuf.FieldMask - 26, // 14: google.cloud.aiplatform.v1beta1.ListSavedQueriesResponse.saved_queries:type_name -> google.cloud.aiplatform.v1beta1.SavedQuery - 22, // 15: google.cloud.aiplatform.v1beta1.GetAnnotationSpecRequest.read_mask:type_name -> google.protobuf.FieldMask - 22, // 16: google.cloud.aiplatform.v1beta1.ListAnnotationsRequest.read_mask:type_name -> google.protobuf.FieldMask - 27, // 17: google.cloud.aiplatform.v1beta1.ListAnnotationsResponse.annotations:type_name -> google.cloud.aiplatform.v1beta1.Annotation - 0, // 18: google.cloud.aiplatform.v1beta1.DatasetService.CreateDataset:input_type -> google.cloud.aiplatform.v1beta1.CreateDatasetRequest - 2, // 19: google.cloud.aiplatform.v1beta1.DatasetService.GetDataset:input_type -> google.cloud.aiplatform.v1beta1.GetDatasetRequest - 3, // 20: google.cloud.aiplatform.v1beta1.DatasetService.UpdateDataset:input_type -> google.cloud.aiplatform.v1beta1.UpdateDatasetRequest - 4, // 21: google.cloud.aiplatform.v1beta1.DatasetService.ListDatasets:input_type -> google.cloud.aiplatform.v1beta1.ListDatasetsRequest - 6, // 22: google.cloud.aiplatform.v1beta1.DatasetService.DeleteDataset:input_type -> google.cloud.aiplatform.v1beta1.DeleteDatasetRequest - 7, // 23: google.cloud.aiplatform.v1beta1.DatasetService.ImportData:input_type -> google.cloud.aiplatform.v1beta1.ImportDataRequest - 10, // 24: google.cloud.aiplatform.v1beta1.DatasetService.ExportData:input_type -> google.cloud.aiplatform.v1beta1.ExportDataRequest - 13, // 25: google.cloud.aiplatform.v1beta1.DatasetService.ListDataItems:input_type -> google.cloud.aiplatform.v1beta1.ListDataItemsRequest - 15, // 26: google.cloud.aiplatform.v1beta1.DatasetService.ListSavedQueries:input_type -> google.cloud.aiplatform.v1beta1.ListSavedQueriesRequest - 17, // 27: google.cloud.aiplatform.v1beta1.DatasetService.GetAnnotationSpec:input_type -> google.cloud.aiplatform.v1beta1.GetAnnotationSpecRequest - 18, // 28: google.cloud.aiplatform.v1beta1.DatasetService.ListAnnotations:input_type -> google.cloud.aiplatform.v1beta1.ListAnnotationsRequest - 28, // 29: google.cloud.aiplatform.v1beta1.DatasetService.CreateDataset:output_type -> google.longrunning.Operation - 20, // 30: google.cloud.aiplatform.v1beta1.DatasetService.GetDataset:output_type -> google.cloud.aiplatform.v1beta1.Dataset - 20, // 31: google.cloud.aiplatform.v1beta1.DatasetService.UpdateDataset:output_type -> google.cloud.aiplatform.v1beta1.Dataset - 5, // 32: google.cloud.aiplatform.v1beta1.DatasetService.ListDatasets:output_type -> google.cloud.aiplatform.v1beta1.ListDatasetsResponse - 28, // 33: google.cloud.aiplatform.v1beta1.DatasetService.DeleteDataset:output_type -> google.longrunning.Operation - 28, // 34: google.cloud.aiplatform.v1beta1.DatasetService.ImportData:output_type -> google.longrunning.Operation - 28, // 35: google.cloud.aiplatform.v1beta1.DatasetService.ExportData:output_type -> google.longrunning.Operation - 14, // 36: google.cloud.aiplatform.v1beta1.DatasetService.ListDataItems:output_type -> google.cloud.aiplatform.v1beta1.ListDataItemsResponse - 16, // 37: google.cloud.aiplatform.v1beta1.DatasetService.ListSavedQueries:output_type -> google.cloud.aiplatform.v1beta1.ListSavedQueriesResponse - 29, // 38: google.cloud.aiplatform.v1beta1.DatasetService.GetAnnotationSpec:output_type -> google.cloud.aiplatform.v1beta1.AnnotationSpec - 19, // 39: google.cloud.aiplatform.v1beta1.DatasetService.ListAnnotations:output_type -> google.cloud.aiplatform.v1beta1.ListAnnotationsResponse - 29, // [29:40] is the sub-list for method output_type - 18, // [18:29] is the sub-list for method input_type - 18, // [18:18] is the sub-list for extension type_name - 18, // [18:18] is the sub-list for extension extendee - 0, // [0:18] is the sub-list for field type_name + 24, // 0: google.cloud.aiplatform.v1beta1.CreateDatasetRequest.dataset:type_name -> google.cloud.aiplatform.v1beta1.Dataset + 25, // 1: google.cloud.aiplatform.v1beta1.CreateDatasetOperationMetadata.generic_metadata:type_name -> google.cloud.aiplatform.v1beta1.GenericOperationMetadata + 26, // 2: google.cloud.aiplatform.v1beta1.GetDatasetRequest.read_mask:type_name -> google.protobuf.FieldMask + 24, // 3: google.cloud.aiplatform.v1beta1.UpdateDatasetRequest.dataset:type_name -> google.cloud.aiplatform.v1beta1.Dataset + 26, // 4: google.cloud.aiplatform.v1beta1.UpdateDatasetRequest.update_mask:type_name -> google.protobuf.FieldMask + 26, // 5: google.cloud.aiplatform.v1beta1.ListDatasetsRequest.read_mask:type_name -> google.protobuf.FieldMask + 24, // 6: google.cloud.aiplatform.v1beta1.ListDatasetsResponse.datasets:type_name -> google.cloud.aiplatform.v1beta1.Dataset + 27, // 7: google.cloud.aiplatform.v1beta1.ImportDataRequest.import_configs:type_name -> google.cloud.aiplatform.v1beta1.ImportDataConfig + 25, // 8: google.cloud.aiplatform.v1beta1.ImportDataOperationMetadata.generic_metadata:type_name -> google.cloud.aiplatform.v1beta1.GenericOperationMetadata + 28, // 9: google.cloud.aiplatform.v1beta1.ExportDataRequest.export_config:type_name -> google.cloud.aiplatform.v1beta1.ExportDataConfig + 25, // 10: google.cloud.aiplatform.v1beta1.ExportDataOperationMetadata.generic_metadata:type_name -> google.cloud.aiplatform.v1beta1.GenericOperationMetadata + 26, // 11: google.cloud.aiplatform.v1beta1.ListDataItemsRequest.read_mask:type_name -> google.protobuf.FieldMask + 29, // 12: google.cloud.aiplatform.v1beta1.ListDataItemsResponse.data_items:type_name -> google.cloud.aiplatform.v1beta1.DataItem + 23, // 13: google.cloud.aiplatform.v1beta1.SearchDataItemsRequest.order_by_annotation:type_name -> google.cloud.aiplatform.v1beta1.SearchDataItemsRequest.OrderByAnnotation + 26, // 14: google.cloud.aiplatform.v1beta1.SearchDataItemsRequest.field_mask:type_name -> google.protobuf.FieldMask + 17, // 15: google.cloud.aiplatform.v1beta1.SearchDataItemsResponse.data_item_views:type_name -> google.cloud.aiplatform.v1beta1.DataItemView + 29, // 16: google.cloud.aiplatform.v1beta1.DataItemView.data_item:type_name -> google.cloud.aiplatform.v1beta1.DataItem + 30, // 17: google.cloud.aiplatform.v1beta1.DataItemView.annotations:type_name -> google.cloud.aiplatform.v1beta1.Annotation + 26, // 18: google.cloud.aiplatform.v1beta1.ListSavedQueriesRequest.read_mask:type_name -> google.protobuf.FieldMask + 31, // 19: google.cloud.aiplatform.v1beta1.ListSavedQueriesResponse.saved_queries:type_name -> google.cloud.aiplatform.v1beta1.SavedQuery + 26, // 20: google.cloud.aiplatform.v1beta1.GetAnnotationSpecRequest.read_mask:type_name -> google.protobuf.FieldMask + 26, // 21: google.cloud.aiplatform.v1beta1.ListAnnotationsRequest.read_mask:type_name -> google.protobuf.FieldMask + 30, // 22: google.cloud.aiplatform.v1beta1.ListAnnotationsResponse.annotations:type_name -> google.cloud.aiplatform.v1beta1.Annotation + 0, // 23: google.cloud.aiplatform.v1beta1.DatasetService.CreateDataset:input_type -> google.cloud.aiplatform.v1beta1.CreateDatasetRequest + 2, // 24: google.cloud.aiplatform.v1beta1.DatasetService.GetDataset:input_type -> google.cloud.aiplatform.v1beta1.GetDatasetRequest + 3, // 25: google.cloud.aiplatform.v1beta1.DatasetService.UpdateDataset:input_type -> google.cloud.aiplatform.v1beta1.UpdateDatasetRequest + 4, // 26: google.cloud.aiplatform.v1beta1.DatasetService.ListDatasets:input_type -> google.cloud.aiplatform.v1beta1.ListDatasetsRequest + 6, // 27: google.cloud.aiplatform.v1beta1.DatasetService.DeleteDataset:input_type -> google.cloud.aiplatform.v1beta1.DeleteDatasetRequest + 7, // 28: google.cloud.aiplatform.v1beta1.DatasetService.ImportData:input_type -> google.cloud.aiplatform.v1beta1.ImportDataRequest + 10, // 29: google.cloud.aiplatform.v1beta1.DatasetService.ExportData:input_type -> google.cloud.aiplatform.v1beta1.ExportDataRequest + 13, // 30: google.cloud.aiplatform.v1beta1.DatasetService.ListDataItems:input_type -> google.cloud.aiplatform.v1beta1.ListDataItemsRequest + 15, // 31: google.cloud.aiplatform.v1beta1.DatasetService.SearchDataItems:input_type -> google.cloud.aiplatform.v1beta1.SearchDataItemsRequest + 18, // 32: google.cloud.aiplatform.v1beta1.DatasetService.ListSavedQueries:input_type -> google.cloud.aiplatform.v1beta1.ListSavedQueriesRequest + 20, // 33: google.cloud.aiplatform.v1beta1.DatasetService.GetAnnotationSpec:input_type -> google.cloud.aiplatform.v1beta1.GetAnnotationSpecRequest + 21, // 34: google.cloud.aiplatform.v1beta1.DatasetService.ListAnnotations:input_type -> google.cloud.aiplatform.v1beta1.ListAnnotationsRequest + 32, // 35: google.cloud.aiplatform.v1beta1.DatasetService.CreateDataset:output_type -> google.longrunning.Operation + 24, // 36: google.cloud.aiplatform.v1beta1.DatasetService.GetDataset:output_type -> google.cloud.aiplatform.v1beta1.Dataset + 24, // 37: google.cloud.aiplatform.v1beta1.DatasetService.UpdateDataset:output_type -> google.cloud.aiplatform.v1beta1.Dataset + 5, // 38: google.cloud.aiplatform.v1beta1.DatasetService.ListDatasets:output_type -> google.cloud.aiplatform.v1beta1.ListDatasetsResponse + 32, // 39: google.cloud.aiplatform.v1beta1.DatasetService.DeleteDataset:output_type -> google.longrunning.Operation + 32, // 40: google.cloud.aiplatform.v1beta1.DatasetService.ImportData:output_type -> google.longrunning.Operation + 32, // 41: google.cloud.aiplatform.v1beta1.DatasetService.ExportData:output_type -> google.longrunning.Operation + 14, // 42: google.cloud.aiplatform.v1beta1.DatasetService.ListDataItems:output_type -> google.cloud.aiplatform.v1beta1.ListDataItemsResponse + 16, // 43: google.cloud.aiplatform.v1beta1.DatasetService.SearchDataItems:output_type -> google.cloud.aiplatform.v1beta1.SearchDataItemsResponse + 19, // 44: google.cloud.aiplatform.v1beta1.DatasetService.ListSavedQueries:output_type -> google.cloud.aiplatform.v1beta1.ListSavedQueriesResponse + 33, // 45: google.cloud.aiplatform.v1beta1.DatasetService.GetAnnotationSpec:output_type -> google.cloud.aiplatform.v1beta1.AnnotationSpec + 22, // 46: google.cloud.aiplatform.v1beta1.DatasetService.ListAnnotations:output_type -> google.cloud.aiplatform.v1beta1.ListAnnotationsResponse + 35, // [35:47] is the sub-list for method output_type + 23, // [23:35] is the sub-list for method input_type + 23, // [23:23] is the sub-list for extension type_name + 23, // [23:23] is the sub-list for extension extendee + 0, // [0:23] is the sub-list for field type_name } func init() { file_google_cloud_aiplatform_v1beta1_dataset_service_proto_init() } @@ -2037,7 +2556,7 @@ func file_google_cloud_aiplatform_v1beta1_dataset_service_proto_init() { } } file_google_cloud_aiplatform_v1beta1_dataset_service_proto_msgTypes[15].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ListSavedQueriesRequest); i { + switch v := v.(*SearchDataItemsRequest); i { case 0: return &v.state case 1: @@ -2049,7 +2568,7 @@ func file_google_cloud_aiplatform_v1beta1_dataset_service_proto_init() { } } file_google_cloud_aiplatform_v1beta1_dataset_service_proto_msgTypes[16].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ListSavedQueriesResponse); i { + switch v := v.(*SearchDataItemsResponse); i { case 0: return &v.state case 1: @@ -2061,7 +2580,7 @@ func file_google_cloud_aiplatform_v1beta1_dataset_service_proto_init() { } } file_google_cloud_aiplatform_v1beta1_dataset_service_proto_msgTypes[17].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*GetAnnotationSpecRequest); i { + switch v := v.(*DataItemView); i { case 0: return &v.state case 1: @@ -2073,7 +2592,7 @@ func file_google_cloud_aiplatform_v1beta1_dataset_service_proto_init() { } } file_google_cloud_aiplatform_v1beta1_dataset_service_proto_msgTypes[18].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ListAnnotationsRequest); i { + switch v := v.(*ListSavedQueriesRequest); i { case 0: return &v.state case 1: @@ -2085,6 +2604,42 @@ func file_google_cloud_aiplatform_v1beta1_dataset_service_proto_init() { } } file_google_cloud_aiplatform_v1beta1_dataset_service_proto_msgTypes[19].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*ListSavedQueriesResponse); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_google_cloud_aiplatform_v1beta1_dataset_service_proto_msgTypes[20].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*GetAnnotationSpecRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_google_cloud_aiplatform_v1beta1_dataset_service_proto_msgTypes[21].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*ListAnnotationsRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_google_cloud_aiplatform_v1beta1_dataset_service_proto_msgTypes[22].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ListAnnotationsResponse); i { case 0: return &v.state @@ -2096,6 +2651,22 @@ func file_google_cloud_aiplatform_v1beta1_dataset_service_proto_init() { return nil } } + file_google_cloud_aiplatform_v1beta1_dataset_service_proto_msgTypes[23].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*SearchDataItemsRequest_OrderByAnnotation); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + file_google_cloud_aiplatform_v1beta1_dataset_service_proto_msgTypes[15].OneofWrappers = []interface{}{ + (*SearchDataItemsRequest_OrderByDataItem)(nil), + (*SearchDataItemsRequest_OrderByAnnotation_)(nil), } type x struct{} out := protoimpl.TypeBuilder{ @@ -2103,7 +2674,7 @@ func file_google_cloud_aiplatform_v1beta1_dataset_service_proto_init() { GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_google_cloud_aiplatform_v1beta1_dataset_service_proto_rawDesc, NumEnums: 0, - NumMessages: 20, + NumMessages: 24, NumExtensions: 0, NumServices: 1, }, @@ -2145,6 +2716,8 @@ type DatasetServiceClient interface { ExportData(ctx context.Context, in *ExportDataRequest, opts ...grpc.CallOption) (*longrunning.Operation, error) // Lists DataItems in a Dataset. ListDataItems(ctx context.Context, in *ListDataItemsRequest, opts ...grpc.CallOption) (*ListDataItemsResponse, error) + // Searches DataItems in a Dataset. + SearchDataItems(ctx context.Context, in *SearchDataItemsRequest, opts ...grpc.CallOption) (*SearchDataItemsResponse, error) // Lists SavedQueries in a Dataset. ListSavedQueries(ctx context.Context, in *ListSavedQueriesRequest, opts ...grpc.CallOption) (*ListSavedQueriesResponse, error) // Gets an AnnotationSpec. @@ -2233,6 +2806,15 @@ func (c *datasetServiceClient) ListDataItems(ctx context.Context, in *ListDataIt return out, nil } +func (c *datasetServiceClient) SearchDataItems(ctx context.Context, in *SearchDataItemsRequest, opts ...grpc.CallOption) (*SearchDataItemsResponse, error) { + out := new(SearchDataItemsResponse) + err := c.cc.Invoke(ctx, "/google.cloud.aiplatform.v1beta1.DatasetService/SearchDataItems", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + func (c *datasetServiceClient) ListSavedQueries(ctx context.Context, in *ListSavedQueriesRequest, opts ...grpc.CallOption) (*ListSavedQueriesResponse, error) { out := new(ListSavedQueriesResponse) err := c.cc.Invoke(ctx, "/google.cloud.aiplatform.v1beta1.DatasetService/ListSavedQueries", in, out, opts...) @@ -2278,6 +2860,8 @@ type DatasetServiceServer interface { ExportData(context.Context, *ExportDataRequest) (*longrunning.Operation, error) // Lists DataItems in a Dataset. ListDataItems(context.Context, *ListDataItemsRequest) (*ListDataItemsResponse, error) + // Searches DataItems in a Dataset. + SearchDataItems(context.Context, *SearchDataItemsRequest) (*SearchDataItemsResponse, error) // Lists SavedQueries in a Dataset. ListSavedQueries(context.Context, *ListSavedQueriesRequest) (*ListSavedQueriesResponse, error) // Gets an AnnotationSpec. @@ -2314,6 +2898,9 @@ func (*UnimplementedDatasetServiceServer) ExportData(context.Context, *ExportDat func (*UnimplementedDatasetServiceServer) ListDataItems(context.Context, *ListDataItemsRequest) (*ListDataItemsResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method ListDataItems not implemented") } +func (*UnimplementedDatasetServiceServer) SearchDataItems(context.Context, *SearchDataItemsRequest) (*SearchDataItemsResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method SearchDataItems not implemented") +} func (*UnimplementedDatasetServiceServer) ListSavedQueries(context.Context, *ListSavedQueriesRequest) (*ListSavedQueriesResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method ListSavedQueries not implemented") } @@ -2472,6 +3059,24 @@ func _DatasetService_ListDataItems_Handler(srv interface{}, ctx context.Context, return interceptor(ctx, in, info, handler) } +func _DatasetService_SearchDataItems_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(SearchDataItemsRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(DatasetServiceServer).SearchDataItems(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/google.cloud.aiplatform.v1beta1.DatasetService/SearchDataItems", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(DatasetServiceServer).SearchDataItems(ctx, req.(*SearchDataItemsRequest)) + } + return interceptor(ctx, in, info, handler) +} + func _DatasetService_ListSavedQueries_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(ListSavedQueriesRequest) if err := dec(in); err != nil { @@ -2562,6 +3167,10 @@ var _DatasetService_serviceDesc = grpc.ServiceDesc{ MethodName: "ListDataItems", Handler: _DatasetService_ListDataItems_Handler, }, + { + MethodName: "SearchDataItems", + Handler: _DatasetService_SearchDataItems_Handler, + }, { MethodName: "ListSavedQueries", Handler: _DatasetService_ListSavedQueries_Handler, diff --git a/aiplatform/apiv1beta1/aiplatformpb/deployed_index_ref.pb.go b/aiplatform/apiv1beta1/aiplatformpb/deployed_index_ref.pb.go index 0ae77c2a1cfd..eeba372b18e0 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/deployed_index_ref.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/deployed_index_ref.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/deployed_index_ref.proto package aiplatformpb diff --git a/aiplatform/apiv1beta1/aiplatformpb/deployed_model_ref.pb.go b/aiplatform/apiv1beta1/aiplatformpb/deployed_model_ref.pb.go index 24c60953c3eb..a46830210d56 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/deployed_model_ref.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/deployed_model_ref.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/deployed_model_ref.proto package aiplatformpb diff --git a/aiplatform/apiv1beta1/aiplatformpb/deployment_resource_pool.pb.go b/aiplatform/apiv1beta1/aiplatformpb/deployment_resource_pool.pb.go index 388b7dba3639..002652d6f6b5 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/deployment_resource_pool.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/deployment_resource_pool.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/deployment_resource_pool.proto package aiplatformpb diff --git a/aiplatform/apiv1beta1/aiplatformpb/deployment_resource_pool_service.pb.go b/aiplatform/apiv1beta1/aiplatformpb/deployment_resource_pool_service.pb.go index 66fea3325535..a2b18817d313 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/deployment_resource_pool_service.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/deployment_resource_pool_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/deployment_resource_pool_service.proto package aiplatformpb diff --git a/aiplatform/apiv1beta1/aiplatformpb/encryption_spec.pb.go b/aiplatform/apiv1beta1/aiplatformpb/encryption_spec.pb.go index be8e2773b255..d5697a1a6ed0 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/encryption_spec.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/encryption_spec.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/encryption_spec.proto package aiplatformpb diff --git a/aiplatform/apiv1beta1/aiplatformpb/endpoint.pb.go b/aiplatform/apiv1beta1/aiplatformpb/endpoint.pb.go index 7b4ba597a0ef..bd51cd2d7fc1 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/endpoint.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/endpoint.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/endpoint.proto package aiplatformpb @@ -261,7 +261,6 @@ type DeployedModel struct { // [Model.supported_deployment_resources_types][google.cloud.aiplatform.v1beta1.Model.supported_deployment_resources_types]. // // Types that are assignable to PredictionResources: - // // *DeployedModel_DedicatedResources // *DeployedModel_AutomaticResources // *DeployedModel_SharedResources diff --git a/aiplatform/apiv1beta1/aiplatformpb/endpoint_service.pb.go b/aiplatform/apiv1beta1/aiplatformpb/endpoint_service.pb.go index 11911b57b265..2f1dc142e351 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/endpoint_service.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/endpoint_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/endpoint_service.proto package aiplatformpb @@ -229,18 +229,18 @@ type ListEndpointsRequest struct { // Optional. An expression for filtering the results of the request. For field names // both snake_case and camelCase are supported. // - // - `endpoint` supports = and !=. `endpoint` represents the Endpoint ID, + // * `endpoint` supports = and !=. `endpoint` represents the Endpoint ID, // i.e. the last segment of the Endpoint's [resource name][google.cloud.aiplatform.v1beta1.Endpoint.name]. - // - `display_name` supports = and, != - // - `labels` supports general map functions that is: - // - `labels.key=value` - key:value equality - // - `labels.key:* or labels:key - key existence - // - A key including a space must be quoted. `labels."a key"`. + // * `display_name` supports = and, != + // * `labels` supports general map functions that is: + // * `labels.key=value` - key:value equality + // * `labels.key:* or labels:key - key existence + // * A key including a space must be quoted. `labels."a key"`. // // Some examples: - // - `endpoint=1` - // - `displayName="myDisplayName"` - // - `labels.myKey="myValue"` + // * `endpoint=1` + // * `displayName="myDisplayName"` + // * `labels.myKey="myValue"` Filter string `protobuf:"bytes,2,opt,name=filter,proto3" json:"filter,omitempty"` // Optional. The standard list page size. PageSize int32 `protobuf:"varint,3,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"` diff --git a/aiplatform/apiv1beta1/aiplatformpb/entity_type.pb.go b/aiplatform/apiv1beta1/aiplatformpb/entity_type.pb.go index 10dc7a06995d..a18bfe0feb57 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/entity_type.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/entity_type.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/entity_type.proto package aiplatformpb diff --git a/aiplatform/apiv1beta1/aiplatformpb/env_var.pb.go b/aiplatform/apiv1beta1/aiplatformpb/env_var.pb.go index 103a683b9fc0..43eb5dc3d171 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/env_var.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/env_var.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/env_var.proto package aiplatformpb diff --git a/aiplatform/apiv1beta1/aiplatformpb/event.pb.go b/aiplatform/apiv1beta1/aiplatformpb/event.pb.go index a6ea6fdaff85..06ffb578f7b1 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/event.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/event.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/event.proto package aiplatformpb diff --git a/aiplatform/apiv1beta1/aiplatformpb/execution.pb.go b/aiplatform/apiv1beta1/aiplatformpb/execution.pb.go index c47a778f4838..e4b7307364d4 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/execution.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/execution.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/execution.proto package aiplatformpb diff --git a/aiplatform/apiv1beta1/aiplatformpb/explanation.pb.go b/aiplatform/apiv1beta1/aiplatformpb/explanation.pb.go index a349d2461dbb..94c5ab03b2f2 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/explanation.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/explanation.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/explanation.proto package aiplatformpb @@ -371,13 +371,13 @@ type Attribution struct { // // The format of the value is determined by the feature's input format: // - // - If the feature is a scalar value, the attribution value is a + // * If the feature is a scalar value, the attribution value is a // [floating number][google.protobuf.Value.number_value]. // - // - If the feature is an array of scalar values, the attribution value is + // * If the feature is an array of scalar values, the attribution value is // an [array][google.protobuf.Value.list_value]. // - // - If the feature is a struct, the attribution value is a + // * If the feature is a struct, the attribution value is a // [struct][google.protobuf.Value.struct_value]. The keys in the // attribution value struct are the same as the keys in the feature // struct. The formats of the values in the attribution struct are @@ -631,7 +631,6 @@ type ExplanationParameters struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Method: - // // *ExplanationParameters_SampledShapleyAttribution // *ExplanationParameters_IntegratedGradientsAttribution // *ExplanationParameters_XraiAttribution @@ -1022,7 +1021,6 @@ type SmoothGradConfig struct { // prior to computing gradients. // // Types that are assignable to GradientNoiseSigma: - // // *SmoothGradConfig_NoiseSigma // *SmoothGradConfig_FeatureNoiseSigma GradientNoiseSigma isSmoothGradConfig_GradientNoiseSigma `protobuf_oneof:"GradientNoiseSigma"` @@ -1244,7 +1242,6 @@ type Examples struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Config: - // // *Examples_NearestNeighborSearchConfig // *Examples_Presets Config isExamples_Config `protobuf_oneof:"config"` diff --git a/aiplatform/apiv1beta1/aiplatformpb/explanation_metadata.pb.go b/aiplatform/apiv1beta1/aiplatformpb/explanation_metadata.pb.go index 0ebc4a528f3d..6dfed2b7c932 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/explanation_metadata.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/explanation_metadata.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/explanation_metadata.proto package aiplatformpb @@ -86,12 +86,10 @@ const ( // ``` // input = ["This", "is", "a", "test", "."] // encoded = [[0.1, 0.2, 0.3, 0.4, 0.5], - // - // [0.2, 0.1, 0.4, 0.3, 0.5], - // [0.5, 0.1, 0.3, 0.5, 0.4], - // [0.5, 0.3, 0.1, 0.2, 0.4], - // [0.4, 0.3, 0.2, 0.5, 0.1]] - // + // [0.2, 0.1, 0.4, 0.3, 0.5], + // [0.5, 0.1, 0.3, 0.5, 0.4], + // [0.5, 0.3, 0.1, 0.2, 0.4], + // [0.4, 0.3, 0.2, 0.5, 0.1]] // ``` ExplanationMetadata_InputMetadata_CONCAT_EMBEDDING ExplanationMetadata_InputMetadata_Encoding = 6 ) @@ -704,7 +702,6 @@ type ExplanationMetadata_OutputMetadata struct { // [Attribution.output_display_name][google.cloud.aiplatform.v1beta1.Attribution.output_display_name] will not be populated. // // Types that are assignable to DisplayNameMapping: - // // *ExplanationMetadata_OutputMetadata_IndexDisplayNameMapping // *ExplanationMetadata_OutputMetadata_DisplayNameMappingKey DisplayNameMapping isExplanationMetadata_OutputMetadata_DisplayNameMapping `protobuf_oneof:"display_name_mapping"` diff --git a/aiplatform/apiv1beta1/aiplatformpb/feature.pb.go b/aiplatform/apiv1beta1/aiplatformpb/feature.pb.go index ab538e743ca6..ded98896a35e 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/feature.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/feature.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/feature.proto package aiplatformpb diff --git a/aiplatform/apiv1beta1/aiplatformpb/feature_monitoring_stats.pb.go b/aiplatform/apiv1beta1/aiplatformpb/feature_monitoring_stats.pb.go index 9f09418f0ba1..051ebdd95f30 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/feature_monitoring_stats.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/feature_monitoring_stats.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/feature_monitoring_stats.proto package aiplatformpb @@ -72,10 +72,10 @@ type FeatureStatsAnomaly struct { // (https://github.com/tensorflow/metadata/blob/master/tensorflow_metadata/proto/v0/anomalies.proto). AnomalyUri string `protobuf:"bytes,4,opt,name=anomaly_uri,json=anomalyUri,proto3" json:"anomaly_uri,omitempty"` // Deviation from the current stats to baseline stats. - // 1. For categorical feature, the distribution distance is calculated by - // L-inifinity norm. - // 2. For numerical feature, the distribution distance is calculated by - // Jensen–Shannon divergence. + // 1. For categorical feature, the distribution distance is calculated by + // L-inifinity norm. + // 2. For numerical feature, the distribution distance is calculated by + // Jensen–Shannon divergence. DistributionDeviation float64 `protobuf:"fixed64,5,opt,name=distribution_deviation,json=distributionDeviation,proto3" json:"distribution_deviation,omitempty"` // This is the threshold used when detecting anomalies. // The threshold can be changed by user, so this one might be different from diff --git a/aiplatform/apiv1beta1/aiplatformpb/feature_selector.pb.go b/aiplatform/apiv1beta1/aiplatformpb/feature_selector.pb.go index 204817b66c53..28ce51b66b2f 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/feature_selector.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/feature_selector.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/feature_selector.proto package aiplatformpb @@ -44,10 +44,10 @@ type IdMatcher struct { // Required. The following are accepted as `ids`: // - // - A single-element list containing only `*`, which selects all Features - // in the target EntityType, or - // - A list containing only Feature IDs, which selects only Features with - // those IDs in the target EntityType. + // * A single-element list containing only `*`, which selects all Features + // in the target EntityType, or + // * A list containing only Feature IDs, which selects only Features with + // those IDs in the target EntityType. Ids []string `protobuf:"bytes,1,rep,name=ids,proto3" json:"ids,omitempty"` } diff --git a/aiplatform/apiv1beta1/aiplatformpb/featurestore.pb.go b/aiplatform/apiv1beta1/aiplatformpb/featurestore.pb.go index 1a22f7135e1f..a97203d42972 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/featurestore.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/featurestore.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/featurestore.proto package aiplatformpb diff --git a/aiplatform/apiv1beta1/aiplatformpb/featurestore_monitoring.pb.go b/aiplatform/apiv1beta1/aiplatformpb/featurestore_monitoring.pb.go index 3903fbc11b2d..ee2d07bd4a5f 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/featurestore_monitoring.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/featurestore_monitoring.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/featurestore_monitoring.proto package aiplatformpb @@ -255,18 +255,14 @@ type FeaturestoreMonitoringConfig_SnapshotAnalysis struct { // The monitoring schedule for snapshot analysis. // For EntityType-level config: - // - // unset / disabled = true indicates disabled by - // default for Features under it; otherwise by default enable snapshot - // analysis monitoring with monitoring_interval for Features under it. - // + // unset / disabled = true indicates disabled by + // default for Features under it; otherwise by default enable snapshot + // analysis monitoring with monitoring_interval for Features under it. // Feature-level config: - // - // disabled = true indicates disabled regardless of the EntityType-level - // config; unset monitoring_interval indicates going with EntityType-level - // config; otherwise run snapshot analysis monitoring with - // monitoring_interval regardless of the EntityType-level config. - // + // disabled = true indicates disabled regardless of the EntityType-level + // config; unset monitoring_interval indicates going with EntityType-level + // config; otherwise run snapshot analysis monitoring with + // monitoring_interval regardless of the EntityType-level config. // Explicitly Disable the snapshot analysis based monitoring. Disabled bool `protobuf:"varint,1,opt,name=disabled,proto3" json:"disabled,omitempty"` // Configuration of the snapshot analysis based monitoring pipeline running @@ -419,7 +415,6 @@ type FeaturestoreMonitoringConfig_ThresholdConfig struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Threshold: - // // *FeaturestoreMonitoringConfig_ThresholdConfig_Value Threshold isFeaturestoreMonitoringConfig_ThresholdConfig_Threshold `protobuf_oneof:"threshold"` } diff --git a/aiplatform/apiv1beta1/aiplatformpb/featurestore_online_service.pb.go b/aiplatform/apiv1beta1/aiplatformpb/featurestore_online_service.pb.go index fe2d47f98d0a..a7e8658fbafc 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/featurestore_online_service.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/featurestore_online_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/featurestore_online_service.proto package aiplatformpb @@ -423,7 +423,6 @@ type FeatureValue struct { // Value for the feature. // // Types that are assignable to Value: - // // *FeatureValue_BoolValue // *FeatureValue_DoubleValue // *FeatureValue_Int64Value @@ -844,7 +843,6 @@ type ReadFeatureValuesResponse_EntityView_Data struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Data: - // // *ReadFeatureValuesResponse_EntityView_Data_Value // *ReadFeatureValuesResponse_EntityView_Data_Values Data isReadFeatureValuesResponse_EntityView_Data_Data `protobuf_oneof:"data"` diff --git a/aiplatform/apiv1beta1/aiplatformpb/featurestore_service.pb.go b/aiplatform/apiv1beta1/aiplatformpb/featurestore_service.pb.go index e021e554c2ab..f7fdb415c416 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/featurestore_service.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/featurestore_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/featurestore_service.proto package aiplatformpb @@ -183,24 +183,20 @@ type ListFeaturestoresRequest struct { // // * `create_time`: Supports `=`, `!=`, `<`, `>`, `<=`, and `>=` comparisons. // Values must be - // - // in RFC 3339 format. - // + // in RFC 3339 format. // * `update_time`: Supports `=`, `!=`, `<`, `>`, `<=`, and `>=` comparisons. // Values must be - // - // in RFC 3339 format. - // + // in RFC 3339 format. // * `online_serving_config.fixed_node_count`: Supports `=`, `!=`, `<`, `>`, // `<=`, and `>=` comparisons. // * `labels`: Supports key-value equality and key presence. // // Examples: // - // - `create_time > "2020-01-01" OR update_time > "2020-01-01"` - // Featurestores created or updated after 2020-01-01. - // - `labels.env = "prod"` - // Featurestores with label "env" set to "prod". + // * `create_time > "2020-01-01" OR update_time > "2020-01-01"` + // Featurestores created or updated after 2020-01-01. + // * `labels.env = "prod"` + // Featurestores with label "env" set to "prod". Filter string `protobuf:"bytes,2,opt,name=filter,proto3" json:"filter,omitempty"` // The maximum number of Featurestores to return. The service may return fewer // than this value. If unspecified, at most 100 Featurestores will be @@ -219,9 +215,9 @@ type ListFeaturestoresRequest struct { // Use "desc" after a field name for descending. // Supported Fields: // - // - `create_time` - // - `update_time` - // - `online_serving_config.fixed_node_count` + // * `create_time` + // * `update_time` + // * `online_serving_config.fixed_node_count` OrderBy string `protobuf:"bytes,5,opt,name=order_by,json=orderBy,proto3" json:"order_by,omitempty"` // Mask specifying which fields to read. ReadMask *fieldmaskpb.FieldMask `protobuf:"bytes,6,opt,name=read_mask,json=readMask,proto3" json:"read_mask,omitempty"` @@ -382,10 +378,10 @@ type UpdateFeaturestoreRequest struct { // // Updatable fields: // - // - `labels` - // - `online_serving_config.fixed_node_count` - // - `online_serving_config.scaling` - // - `online_storage_ttl_days` + // * `labels` + // * `online_serving_config.fixed_node_count` + // * `online_serving_config.scaling` + // * `online_storage_ttl_days` UpdateMask *fieldmaskpb.FieldMask `protobuf:"bytes,2,opt,name=update_mask,json=updateMask,proto3" json:"update_mask,omitempty"` } @@ -507,7 +503,6 @@ type ImportFeatureValuesRequest struct { // the format. // // Types that are assignable to Source: - // // *ImportFeatureValuesRequest_AvroSource // *ImportFeatureValuesRequest_BigquerySource // *ImportFeatureValuesRequest_CsvSource @@ -516,7 +511,6 @@ type ImportFeatureValuesRequest struct { // Timestamps must be millisecond-aligned. // // Types that are assignable to FeatureTimeSource: - // // *ImportFeatureValuesRequest_FeatureTimeField // *ImportFeatureValuesRequest_FeatureTime FeatureTimeSource isImportFeatureValuesRequest_FeatureTimeSource `protobuf_oneof:"feature_time_source"` @@ -800,7 +794,6 @@ type BatchReadFeatureValuesRequest struct { unknownFields protoimpl.UnknownFields // Types that are assignable to ReadOption: - // // *BatchReadFeatureValuesRequest_CsvReadInstances // *BatchReadFeatureValuesRequest_BigqueryReadInstances ReadOption isBatchReadFeatureValuesRequest_ReadOption `protobuf_oneof:"read_option"` @@ -941,8 +934,7 @@ type BatchReadFeatureValuesRequest_CsvReadInstances struct { // // `csv_read_instances` are read instances stored in a plain-text CSV file. // The header should be: - // - // [ENTITY_TYPE_ID1], [ENTITY_TYPE_ID2], ..., timestamp + // [ENTITY_TYPE_ID1], [ENTITY_TYPE_ID2], ..., timestamp // // The columns can be in any order. // @@ -970,7 +962,6 @@ type ExportFeatureValuesRequest struct { // Required. The mode in which Feature values are exported. // // Types that are assignable to Mode: - // // *ExportFeatureValuesRequest_SnapshotExport_ // *ExportFeatureValuesRequest_FullExport_ Mode isExportFeatureValuesRequest_Mode `protobuf_oneof:"mode"` @@ -1152,7 +1143,6 @@ type FeatureValueDestination struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Destination: - // // *FeatureValueDestination_BigqueryDestination // *FeatureValueDestination_TfrecordDestination // *FeatureValueDestination_CsvDestination @@ -1236,12 +1226,12 @@ type FeatureValueDestination_TfrecordDestination struct { // Below are the mapping from Feature value type // in Featurestore to Feature value type in TFRecord: // - // Value type in Featurestore | Value type in TFRecord - // DOUBLE, DOUBLE_ARRAY | FLOAT_LIST - // INT64, INT64_ARRAY | INT64_LIST - // STRING, STRING_ARRAY, BYTES | BYTES_LIST - // true -> byte_string("true"), false -> byte_string("false") - // BOOL, BOOL_ARRAY (true, false) | BYTES_LIST + // Value type in Featurestore | Value type in TFRecord + // DOUBLE, DOUBLE_ARRAY | FLOAT_LIST + // INT64, INT64_ARRAY | INT64_LIST + // STRING, STRING_ARRAY, BYTES | BYTES_LIST + // true -> byte_string("true"), false -> byte_string("false") + // BOOL, BOOL_ARRAY (true, false) | BYTES_LIST TfrecordDestination *TFRecordDestination `protobuf:"bytes,2,opt,name=tfrecord_destination,json=tfrecordDestination,proto3,oneof"` } @@ -1482,13 +1472,13 @@ type ListEntityTypesRequest struct { // // Examples: // - // - `create_time > \"2020-01-31T15:30:00.000000Z\" OR - // update_time > \"2020-01-31T15:30:00.000000Z\"` --> EntityTypes created - // or updated after 2020-01-31T15:30:00.000000Z. - // - `labels.active = yes AND labels.env = prod` --> EntityTypes having both + // * `create_time > \"2020-01-31T15:30:00.000000Z\" OR + // update_time > \"2020-01-31T15:30:00.000000Z\"` --> EntityTypes created + // or updated after 2020-01-31T15:30:00.000000Z. + // * `labels.active = yes AND labels.env = prod` --> EntityTypes having both // (active: yes) and (env: prod) labels. - // - `labels.env: *` --> Any EntityType which has a label with 'env' as the - // key. + // * `labels.env: *` --> Any EntityType which has a label with 'env' as the + // key. Filter string `protobuf:"bytes,2,opt,name=filter,proto3" json:"filter,omitempty"` // The maximum number of EntityTypes to return. The service may return fewer // than this value. If unspecified, at most 1000 EntityTypes will be returned. @@ -1508,9 +1498,9 @@ type ListEntityTypesRequest struct { // // Supported fields: // - // - `entity_type_id` - // - `create_time` - // - `update_time` + // * `entity_type_id` + // * `create_time` + // * `update_time` OrderBy string `protobuf:"bytes,5,opt,name=order_by,json=orderBy,proto3" json:"order_by,omitempty"` // Mask specifying which fields to read. ReadMask *fieldmaskpb.FieldMask `protobuf:"bytes,6,opt,name=read_mask,json=readMask,proto3" json:"read_mask,omitempty"` @@ -1671,16 +1661,16 @@ type UpdateEntityTypeRequest struct { // // Updatable fields: // - // - `description` - // - `labels` - // - `monitoring_config.snapshot_analysis.disabled` - // - `monitoring_config.snapshot_analysis.monitoring_interval_days` - // - `monitoring_config.snapshot_analysis.staleness_days` - // - `monitoring_config.import_features_analysis.state` - // - `monitoring_config.import_features_analysis.anomaly_detection_baseline` - // - `monitoring_config.numerical_threshold_config.value` - // - `monitoring_config.categorical_threshold_config.value` - // - `offline_storage_ttl_days` + // * `description` + // * `labels` + // * `monitoring_config.snapshot_analysis.disabled` + // * `monitoring_config.snapshot_analysis.monitoring_interval_days` + // * `monitoring_config.snapshot_analysis.staleness_days` + // * `monitoring_config.import_features_analysis.state` + // * `monitoring_config.import_features_analysis.anomaly_detection_baseline` + // * `monitoring_config.numerical_threshold_config.value` + // * `monitoring_config.categorical_threshold_config.value` + // * `offline_storage_ttl_days` UpdateMask *fieldmaskpb.FieldMask `protobuf:"bytes,2,opt,name=update_mask,json=updateMask,proto3" json:"update_mask,omitempty"` } @@ -2051,14 +2041,14 @@ type ListFeaturesRequest struct { // // Examples: // - // - `value_type = DOUBLE` --> Features whose type is DOUBLE. - // - `create_time > \"2020-01-31T15:30:00.000000Z\" OR - // update_time > \"2020-01-31T15:30:00.000000Z\"` --> EntityTypes created - // or updated after 2020-01-31T15:30:00.000000Z. - // - `labels.active = yes AND labels.env = prod` --> Features having both + // * `value_type = DOUBLE` --> Features whose type is DOUBLE. + // * `create_time > \"2020-01-31T15:30:00.000000Z\" OR + // update_time > \"2020-01-31T15:30:00.000000Z\"` --> EntityTypes created + // or updated after 2020-01-31T15:30:00.000000Z. + // * `labels.active = yes AND labels.env = prod` --> Features having both // (active: yes) and (env: prod) labels. - // - `labels.env: *` --> Any Feature which has a label with 'env' as the - // key. + // * `labels.env: *` --> Any Feature which has a label with 'env' as the + // key. Filter string `protobuf:"bytes,2,opt,name=filter,proto3" json:"filter,omitempty"` // The maximum number of Features to return. The service may return fewer // than this value. If unspecified, at most 1000 Features will be returned. @@ -2077,10 +2067,10 @@ type ListFeaturesRequest struct { // Use "desc" after a field name for descending. // Supported fields: // - // - `feature_id` - // - `value_type` - // - `create_time` - // - `update_time` + // * `feature_id` + // * `value_type` + // * `create_time` + // * `update_time` OrderBy string `protobuf:"bytes,5,opt,name=order_by,json=orderBy,proto3" json:"order_by,omitempty"` // Mask specifying which fields to read. ReadMask *fieldmaskpb.FieldMask `protobuf:"bytes,6,opt,name=read_mask,json=readMask,proto3" json:"read_mask,omitempty"` @@ -2251,13 +2241,13 @@ type SearchFeaturesRequest struct { // and the FIELD are converted to a sequence of words (i.e. tokens) for // comparison. This is done by: // - // - Removing leading/trailing whitespace and tokenizing the search value. - // Characters that are not one of alphanumeric `[a-zA-Z0-9]`, underscore - // `_`, or asterisk `*` are treated as delimiters for tokens. `*` is treated - // as a wildcard that matches characters within a token. - // - Ignoring case. - // - Prepending an asterisk to the first and appending an asterisk to the - // last token in QUERY. + // * Removing leading/trailing whitespace and tokenizing the search value. + // Characters that are not one of alphanumeric `[a-zA-Z0-9]`, underscore + // `_`, or asterisk `*` are treated as delimiters for tokens. `*` is treated + // as a wildcard that matches characters within a token. + // * Ignoring case. + // * Prepending an asterisk to the first and appending an asterisk to the + // last token in QUERY. // // A QUERY must be either a singular token or a phrase. A phrase is one or // multiple words enclosed in double quotation marks ("). With phrases, the @@ -2280,6 +2270,7 @@ type SearchFeaturesRequest struct { // containing the substring `foo` and description containing the substring // `bar`. // + // // Besides field queries, the following exact-match filters are // supported. The exact-match filters do not support wildcards. Unlike // field-restricted queries, exact-match filters are case-sensitive. @@ -2295,11 +2286,11 @@ type SearchFeaturesRequest struct { // Examples: // * `description = "foo bar"` --> Any Feature with description exactly equal // to `foo bar` - // - `value_type = DOUBLE` --> Features whose type is DOUBLE. - // - `labels.active = yes AND labels.env = prod` --> Features having both + // * `value_type = DOUBLE` --> Features whose type is DOUBLE. + // * `labels.active = yes AND labels.env = prod` --> Features having both // (active: yes) and (env: prod) labels. - // - `labels.env: *` --> Any Feature which has a label with `env` as the - // key. + // * `labels.env: *` --> Any Feature which has a label with `env` as the + // key. Query string `protobuf:"bytes,3,opt,name=query,proto3" json:"query,omitempty"` // The maximum number of Features to return. The service may return fewer // than this value. If unspecified, at most 100 Features will be returned. @@ -2386,11 +2377,11 @@ type SearchFeaturesResponse struct { // // Fields returned: // - // - `name` - // - `description` - // - `labels` - // - `create_time` - // - `update_time` + // * `name` + // * `description` + // * `labels` + // * `create_time` + // * `update_time` Features []*Feature `protobuf:"bytes,1,rep,name=features,proto3" json:"features,omitempty"` // A token, which can be sent as [SearchFeaturesRequest.page_token][google.cloud.aiplatform.v1beta1.SearchFeaturesRequest.page_token] to // retrieve the next page. @@ -2465,9 +2456,9 @@ type UpdateFeatureRequest struct { // // Updatable fields: // - // - `description` - // - `labels` - // - `disable_monitoring` + // * `description` + // * `labels` + // * `disable_monitoring` UpdateMask *fieldmaskpb.FieldMask `protobuf:"bytes,2,opt,name=update_mask,json=updateMask,proto3" json:"update_mask,omitempty"` } @@ -3068,7 +3059,6 @@ type DeleteFeatureValuesRequest struct { // Defines options to select feature values to be deleted. // // Types that are assignable to DeleteOption: - // // *DeleteFeatureValuesRequest_SelectEntity_ // *DeleteFeatureValuesRequest_SelectTimeRangeAndFeature_ DeleteOption isDeleteFeatureValuesRequest_DeleteOption `protobuf_oneof:"DeleteOption"` @@ -3207,7 +3197,6 @@ type EntityIdSelector struct { // the format. // // Types that are assignable to EntityIdsSource: - // // *EntityIdSelector_CsvSource EntityIdsSource isEntityIdSelector_EntityIdsSource `protobuf_oneof:"EntityIdsSource"` // Source column that holds entity IDs. If not provided, entity IDs are @@ -5630,13 +5619,13 @@ type FeaturestoreServiceClient interface { // // There are also scenarios where the caller can cause inconsistency. // - // - Source data for import contains multiple distinct Feature values for - // the same entity ID and timestamp. - // - Source is modified during an import. This includes adding, updating, or - // removing source data and/or metadata. Examples of updating metadata - // include but are not limited to changing storage location, storage class, - // or retention policy. - // - Online serving cluster is under-provisioned. + // - Source data for import contains multiple distinct Feature values for + // the same entity ID and timestamp. + // - Source is modified during an import. This includes adding, updating, or + // removing source data and/or metadata. Examples of updating metadata + // include but are not limited to changing storage location, storage class, + // or retention policy. + // - Online serving cluster is under-provisioned. ImportFeatureValues(ctx context.Context, in *ImportFeatureValuesRequest, opts ...grpc.CallOption) (*longrunning.Operation, error) // Batch reads Feature values from a Featurestore. // @@ -5908,13 +5897,13 @@ type FeaturestoreServiceServer interface { // // There are also scenarios where the caller can cause inconsistency. // - // - Source data for import contains multiple distinct Feature values for - // the same entity ID and timestamp. - // - Source is modified during an import. This includes adding, updating, or - // removing source data and/or metadata. Examples of updating metadata - // include but are not limited to changing storage location, storage class, - // or retention policy. - // - Online serving cluster is under-provisioned. + // - Source data for import contains multiple distinct Feature values for + // the same entity ID and timestamp. + // - Source is modified during an import. This includes adding, updating, or + // removing source data and/or metadata. Examples of updating metadata + // include but are not limited to changing storage location, storage class, + // or retention policy. + // - Online serving cluster is under-provisioned. ImportFeatureValues(context.Context, *ImportFeatureValuesRequest) (*longrunning.Operation, error) // Batch reads Feature values from a Featurestore. // diff --git a/aiplatform/apiv1beta1/aiplatformpb/hyperparameter_tuning_job.pb.go b/aiplatform/apiv1beta1/aiplatformpb/hyperparameter_tuning_job.pb.go index bd69091a34d6..d67b6779331d 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/hyperparameter_tuning_job.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/hyperparameter_tuning_job.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/hyperparameter_tuning_job.proto package aiplatformpb diff --git a/aiplatform/apiv1beta1/aiplatformpb/index.pb.go b/aiplatform/apiv1beta1/aiplatformpb/index.pb.go index c512dbfa3319..e09f538536b9 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/index.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/index.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/index.proto package aiplatformpb diff --git a/aiplatform/apiv1beta1/aiplatformpb/index_endpoint.pb.go b/aiplatform/apiv1beta1/aiplatformpb/index_endpoint.pb.go index 4ad9ec36e8a2..b953c5f10aab 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/index_endpoint.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/index_endpoint.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/index_endpoint.proto package aiplatformpb diff --git a/aiplatform/apiv1beta1/aiplatformpb/index_endpoint_service.pb.go b/aiplatform/apiv1beta1/aiplatformpb/index_endpoint_service.pb.go index 022cfcbd3669..6a00d40b7484 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/index_endpoint_service.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/index_endpoint_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/index_endpoint_service.proto package aiplatformpb @@ -214,21 +214,21 @@ type ListIndexEndpointsRequest struct { // Optional. An expression for filtering the results of the request. For field names // both snake_case and camelCase are supported. // - // - `index_endpoint` supports = and !=. `index_endpoint` represents the - // IndexEndpoint ID, ie. the last segment of the IndexEndpoint's - // [resourcename][google.cloud.aiplatform.v1beta1.IndexEndpoint.name]. - // - `display_name` supports =, != and regex() - // (uses [re2](https://github.com/google/re2/wiki/Syntax) syntax) - // - `labels` supports general map functions that is: - // `labels.key=value` - key:value equality - // `labels.key:* or labels:key - key existence - // A key including a space must be quoted. `labels."a key"`. + // * `index_endpoint` supports = and !=. `index_endpoint` represents the + // IndexEndpoint ID, ie. the last segment of the IndexEndpoint's + // [resourcename][google.cloud.aiplatform.v1beta1.IndexEndpoint.name]. + // * `display_name` supports =, != and regex() + // (uses [re2](https://github.com/google/re2/wiki/Syntax) syntax) + // * `labels` supports general map functions that is: + // `labels.key=value` - key:value equality + // `labels.key:* or labels:key - key existence + // A key including a space must be quoted. `labels."a key"`. // // Some examples: - // - `index_endpoint="1"` - // - `display_name="myDisplayName"` - // - `regex(display_name, "^A") -> The display name starts with an A. - // - `labels.myKey="myValue"` + // * `index_endpoint="1"` + // * `display_name="myDisplayName"` + // * `regex(display_name, "^A") -> The display name starts with an A. + // * `labels.myKey="myValue"` Filter string `protobuf:"bytes,2,opt,name=filter,proto3" json:"filter,omitempty"` // Optional. The standard list page size. PageSize int32 `protobuf:"varint,3,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"` diff --git a/aiplatform/apiv1beta1/aiplatformpb/index_service.pb.go b/aiplatform/apiv1beta1/aiplatformpb/index_service.pb.go index d0e67393ec50..074dd55baa58 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/index_service.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/index_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/index_service.proto package aiplatformpb diff --git a/aiplatform/apiv1beta1/aiplatformpb/io.pb.go b/aiplatform/apiv1beta1/aiplatformpb/io.pb.go index f5ead0a5284e..bce52102b582 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/io.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/io.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/io.proto package aiplatformpb @@ -455,11 +455,11 @@ type ContainerRegistryDestination struct { // Only Google Container Registry and Artifact Registry are supported now. // Accepted forms: // - // - Google Container Registry path. For example: - // `gcr.io/projectId/imageName:tag`. + // * Google Container Registry path. For example: + // `gcr.io/projectId/imageName:tag`. // - // - Artifact Registry path. For example: - // `us-central1-docker.pkg.dev/projectId/repoName/imageName:tag`. + // * Artifact Registry path. For example: + // `us-central1-docker.pkg.dev/projectId/repoName/imageName:tag`. // // If a tag is not specified, "latest" will be used as the default tag. OutputUri string `protobuf:"bytes,1,opt,name=output_uri,json=outputUri,proto3" json:"output_uri,omitempty"` diff --git a/aiplatform/apiv1beta1/aiplatformpb/job_service.pb.go b/aiplatform/apiv1beta1/aiplatformpb/job_service.pb.go index 04a21300e19f..0bff92b4e8f7 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/job_service.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/job_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/job_service.proto package aiplatformpb @@ -167,22 +167,22 @@ type ListCustomJobsRequest struct { // // Supported fields: // - // - `display_name` supports `=`, `!=` comparisons, and `:` wildcard. - // - `state` supports `=`, `!=` comparisons. - // - `create_time` supports `=`, `!=`,`<`, `<=`,`>`, `>=` comparisons. + // * `display_name` supports `=`, `!=` comparisons, and `:` wildcard. + // * `state` supports `=`, `!=` comparisons. + // * `create_time` supports `=`, `!=`,`<`, `<=`,`>`, `>=` comparisons. // `create_time` must be in RFC 3339 format. - // - `labels` supports general map functions that is: + // * `labels` supports general map functions that is: // `labels.key=value` - key:value equality // `labels.key:* - key existence // // Some examples of using the filter are: // - // - `state="JOB_STATE_SUCCEEDED" AND display_name:"my_job_*"` - // - `state!="JOB_STATE_FAILED" OR display_name="my_job"` - // - `NOT display_name="my_job"` - // - `create_time>"2021-05-18T00:00:00Z"` - // - `labels.keyA=valueA` - // - `labels.keyB:*` + // * `state="JOB_STATE_SUCCEEDED" AND display_name:"my_job_*"` + // * `state!="JOB_STATE_FAILED" OR display_name="my_job"` + // * `NOT display_name="my_job"` + // * `create_time>"2021-05-18T00:00:00Z"` + // * `labels.keyA=valueA` + // * `labels.keyB:*` Filter string `protobuf:"bytes,2,opt,name=filter,proto3" json:"filter,omitempty"` // The standard list page size. PageSize int32 `protobuf:"varint,3,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"` @@ -546,22 +546,22 @@ type ListDataLabelingJobsRequest struct { // // Supported fields: // - // - `display_name` supports `=`, `!=` comparisons, and `:` wildcard. - // - `state` supports `=`, `!=` comparisons. - // - `create_time` supports `=`, `!=`,`<`, `<=`,`>`, `>=` comparisons. + // * `display_name` supports `=`, `!=` comparisons, and `:` wildcard. + // * `state` supports `=`, `!=` comparisons. + // * `create_time` supports `=`, `!=`,`<`, `<=`,`>`, `>=` comparisons. // `create_time` must be in RFC 3339 format. - // - `labels` supports general map functions that is: + // * `labels` supports general map functions that is: // `labels.key=value` - key:value equality // `labels.key:* - key existence // // Some examples of using the filter are: // - // - `state="JOB_STATE_SUCCEEDED" AND display_name:"my_job_*"` - // - `state!="JOB_STATE_FAILED" OR display_name="my_job"` - // - `NOT display_name="my_job"` - // - `create_time>"2021-05-18T00:00:00Z"` - // - `labels.keyA=valueA` - // - `labels.keyB:*` + // * `state="JOB_STATE_SUCCEEDED" AND display_name:"my_job_*"` + // * `state!="JOB_STATE_FAILED" OR display_name="my_job"` + // * `NOT display_name="my_job"` + // * `create_time>"2021-05-18T00:00:00Z"` + // * `labels.keyA=valueA` + // * `labels.keyB:*` Filter string `protobuf:"bytes,2,opt,name=filter,proto3" json:"filter,omitempty"` // The standard list page size. PageSize int32 `protobuf:"varint,3,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"` @@ -936,22 +936,22 @@ type ListHyperparameterTuningJobsRequest struct { // // Supported fields: // - // - `display_name` supports `=`, `!=` comparisons, and `:` wildcard. - // - `state` supports `=`, `!=` comparisons. - // - `create_time` supports `=`, `!=`,`<`, `<=`,`>`, `>=` comparisons. + // * `display_name` supports `=`, `!=` comparisons, and `:` wildcard. + // * `state` supports `=`, `!=` comparisons. + // * `create_time` supports `=`, `!=`,`<`, `<=`,`>`, `>=` comparisons. // `create_time` must be in RFC 3339 format. - // - `labels` supports general map functions that is: + // * `labels` supports general map functions that is: // `labels.key=value` - key:value equality // `labels.key:* - key existence // // Some examples of using the filter are: // - // - `state="JOB_STATE_SUCCEEDED" AND display_name:"my_job_*"` - // - `state!="JOB_STATE_FAILED" OR display_name="my_job"` - // - `NOT display_name="my_job"` - // - `create_time>"2021-05-18T00:00:00Z"` - // - `labels.keyA=valueA` - // - `labels.keyB:*` + // * `state="JOB_STATE_SUCCEEDED" AND display_name:"my_job_*"` + // * `state!="JOB_STATE_FAILED" OR display_name="my_job"` + // * `NOT display_name="my_job"` + // * `create_time>"2021-05-18T00:00:00Z"` + // * `labels.keyA=valueA` + // * `labels.keyB:*` Filter string `protobuf:"bytes,2,opt,name=filter,proto3" json:"filter,omitempty"` // The standard list page size. PageSize int32 `protobuf:"varint,3,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"` @@ -1317,23 +1317,23 @@ type ListBatchPredictionJobsRequest struct { // // Supported fields: // - // - `display_name` supports `=`, `!=` comparisons, and `:` wildcard. - // - `model_display_name` supports `=`, `!=` comparisons. - // - `state` supports `=`, `!=` comparisons. - // - `create_time` supports `=`, `!=`,`<`, `<=`,`>`, `>=` comparisons. + // * `display_name` supports `=`, `!=` comparisons, and `:` wildcard. + // * `model_display_name` supports `=`, `!=` comparisons. + // * `state` supports `=`, `!=` comparisons. + // * `create_time` supports `=`, `!=`,`<`, `<=`,`>`, `>=` comparisons. // `create_time` must be in RFC 3339 format. - // - `labels` supports general map functions that is: + // * `labels` supports general map functions that is: // `labels.key=value` - key:value equality // `labels.key:* - key existence // // Some examples of using the filter are: // - // - `state="JOB_STATE_SUCCEEDED" AND display_name:"my_job_*"` - // - `state!="JOB_STATE_FAILED" OR display_name="my_job"` - // - `NOT display_name="my_job"` - // - `create_time>"2021-05-18T00:00:00Z"` - // - `labels.keyA=valueA` - // - `labels.keyB:*` + // * `state="JOB_STATE_SUCCEEDED" AND display_name:"my_job_*"` + // * `state!="JOB_STATE_FAILED" OR display_name="my_job"` + // * `NOT display_name="my_job"` + // * `create_time>"2021-05-18T00:00:00Z"` + // * `labels.keyA=valueA` + // * `labels.keyB:*` Filter string `protobuf:"bytes,2,opt,name=filter,proto3" json:"filter,omitempty"` // The standard list page size. PageSize int32 `protobuf:"varint,3,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"` @@ -1888,22 +1888,22 @@ type ListModelDeploymentMonitoringJobsRequest struct { // // Supported fields: // - // - `display_name` supports `=`, `!=` comparisons, and `:` wildcard. - // - `state` supports `=`, `!=` comparisons. - // - `create_time` supports `=`, `!=`,`<`, `<=`,`>`, `>=` comparisons. + // * `display_name` supports `=`, `!=` comparisons, and `:` wildcard. + // * `state` supports `=`, `!=` comparisons. + // * `create_time` supports `=`, `!=`,`<`, `<=`,`>`, `>=` comparisons. // `create_time` must be in RFC 3339 format. - // - `labels` supports general map functions that is: + // * `labels` supports general map functions that is: // `labels.key=value` - key:value equality // `labels.key:* - key existence // // Some examples of using the filter are: // - // - `state="JOB_STATE_SUCCEEDED" AND display_name:"my_job_*"` - // - `state!="JOB_STATE_FAILED" OR display_name="my_job"` - // - `NOT display_name="my_job"` - // - `create_time>"2021-05-18T00:00:00Z"` - // - `labels.keyA=valueA` - // - `labels.keyB:*` + // * `state="JOB_STATE_SUCCEEDED" AND display_name:"my_job_*"` + // * `state!="JOB_STATE_FAILED" OR display_name="my_job"` + // * `NOT display_name="my_job"` + // * `create_time>"2021-05-18T00:00:00Z"` + // * `labels.keyA=valueA` + // * `labels.keyB:*` Filter string `protobuf:"bytes,2,opt,name=filter,proto3" json:"filter,omitempty"` // The standard list page size. PageSize int32 `protobuf:"varint,3,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"` @@ -2064,21 +2064,19 @@ type UpdateModelDeploymentMonitoringJobRequest struct { // // Updatable fields: // - // - `display_name` - // - `model_deployment_monitoring_schedule_config` - // - `model_monitoring_alert_config` - // - `logging_sampling_strategy` - // - `labels` - // - `log_ttl` - // - `enable_monitoring_pipeline_logs` - // + // * `display_name` + // * `model_deployment_monitoring_schedule_config` + // * `model_monitoring_alert_config` + // * `logging_sampling_strategy` + // * `labels` + // * `log_ttl` + // * `enable_monitoring_pipeline_logs` // . and - // - `model_deployment_monitoring_objective_configs` - // + // * `model_deployment_monitoring_objective_configs` // . or - // - `model_deployment_monitoring_objective_configs.objective_config.training_dataset` - // - `model_deployment_monitoring_objective_configs.objective_config.training_prediction_skew_detection_config` - // - `model_deployment_monitoring_objective_configs.objective_config.prediction_drift_detection_config` + // * `model_deployment_monitoring_objective_configs.objective_config.training_dataset` + // * `model_deployment_monitoring_objective_configs.objective_config.training_prediction_skew_detection_config` + // * `model_deployment_monitoring_objective_configs.objective_config.prediction_drift_detection_config` UpdateMask *fieldmaskpb.FieldMask `protobuf:"bytes,2,opt,name=update_mask,json=updateMask,proto3" json:"update_mask,omitempty"` } diff --git a/aiplatform/apiv1beta1/aiplatformpb/job_state.pb.go b/aiplatform/apiv1beta1/aiplatformpb/job_state.pb.go index 99cc2d4541ed..0c73c09a2b70 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/job_state.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/job_state.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/job_state.proto package aiplatformpb diff --git a/aiplatform/apiv1beta1/aiplatformpb/lineage_subgraph.pb.go b/aiplatform/apiv1beta1/aiplatformpb/lineage_subgraph.pb.go index d015b3641ebf..9922d6cd4a1f 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/lineage_subgraph.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/lineage_subgraph.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/lineage_subgraph.proto package aiplatformpb diff --git a/aiplatform/apiv1beta1/aiplatformpb/machine_resources.pb.go b/aiplatform/apiv1beta1/aiplatformpb/machine_resources.pb.go index 9c7921df0dc9..5003ac43245f 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/machine_resources.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/machine_resources.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/machine_resources.proto package aiplatformpb diff --git a/aiplatform/apiv1beta1/aiplatformpb/manual_batch_tuning_parameters.pb.go b/aiplatform/apiv1beta1/aiplatformpb/manual_batch_tuning_parameters.pb.go index 7726ce118a2e..5d6832bc412c 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/manual_batch_tuning_parameters.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/manual_batch_tuning_parameters.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/manual_batch_tuning_parameters.proto package aiplatformpb diff --git a/aiplatform/apiv1beta1/aiplatformpb/metadata_schema.pb.go b/aiplatform/apiv1beta1/aiplatformpb/metadata_schema.pb.go index 4c803c836e7a..b5ea8c8fd260 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/metadata_schema.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/metadata_schema.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/metadata_schema.proto package aiplatformpb diff --git a/aiplatform/apiv1beta1/aiplatformpb/metadata_service.pb.go b/aiplatform/apiv1beta1/aiplatformpb/metadata_service.pb.go index 76acf8757c53..78b8b2475bd4 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/metadata_service.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/metadata_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/metadata_service.proto package aiplatformpb @@ -619,18 +619,18 @@ type ListArtifactsRequest struct { // The syntax to define filter query is based on https://google.aip.dev/160. // The supported set of filters include the following: // - // - **Attribute filtering**: + // * **Attribute filtering**: // For example: `display_name = "test"`. // Supported fields include: `name`, `display_name`, `uri`, `state`, // `schema_title`, `create_time`, and `update_time`. // Time fields, such as `create_time` and `update_time`, require values // specified in RFC-3339 format. // For example: `create_time = "2020-11-19T11:30:00-04:00"` - // - **Metadata field**: + // * **Metadata field**: // To filter on metadata fields use traversal operation as follows: // `metadata..`. // For example: `metadata.field_1.number_value = 10.0` - // - **Context based filtering**: + // * **Context based filtering**: // To filter Artifacts based on the contexts to which they belong, use the // function operator with the full resource name // `in_context()`. @@ -1248,29 +1248,27 @@ type ListContextsRequest struct { // The syntax to define filter query is based on https://google.aip.dev/160. // Following are the supported set of filters: // - // - **Attribute filtering**: - // For example: `display_name = "test"`. - // Supported fields include: `name`, `display_name`, `schema_title`, - // `create_time`, and `update_time`. - // Time fields, such as `create_time` and `update_time`, require values - // specified in RFC-3339 format. - // For example: `create_time = "2020-11-19T11:30:00-04:00"`. - // - // - **Metadata field**: - // To filter on metadata fields use traversal operation as follows: - // `metadata..`. - // For example: `metadata.field_1.number_value = 10.0`. + // * **Attribute filtering**: + // For example: `display_name = "test"`. + // Supported fields include: `name`, `display_name`, `schema_title`, + // `create_time`, and `update_time`. + // Time fields, such as `create_time` and `update_time`, require values + // specified in RFC-3339 format. + // For example: `create_time = "2020-11-19T11:30:00-04:00"`. + // * **Metadata field**: + // To filter on metadata fields use traversal operation as follows: + // `metadata..`. + // For example: `metadata.field_1.number_value = 10.0`. + // * **Parent Child filtering**: + // To filter Contexts based on parent-child relationship use the HAS + // operator as follows: // - // - **Parent Child filtering**: - // To filter Contexts based on parent-child relationship use the HAS - // operator as follows: - // - // ``` - // parent_contexts: - // "projects//locations//metadataStores//contexts/" - // child_contexts: - // "projects//locations//metadataStores//contexts/" - // ``` + // ``` + // parent_contexts: + // "projects//locations//metadataStores//contexts/" + // child_contexts: + // "projects//locations//metadataStores//contexts/" + // ``` // // Each of the above supported filters can be combined together using // logical operators (`AND` & `OR`). Maximum nested expression depth allowed @@ -2267,23 +2265,23 @@ type ListExecutionsRequest struct { // The syntax to define filter query is based on https://google.aip.dev/160. // Following are the supported set of filters: // - // - **Attribute filtering**: - // For example: `display_name = "test"`. - // Supported fields include: `name`, `display_name`, `state`, - // `schema_title`, `create_time`, and `update_time`. - // Time fields, such as `create_time` and `update_time`, require values - // specified in RFC-3339 format. - // For example: `create_time = "2020-11-19T11:30:00-04:00"`. - // - **Metadata field**: - // To filter on metadata fields use traversal operation as follows: - // `metadata..` - // For example: `metadata.field_1.number_value = 10.0` - // - **Context based filtering**: - // To filter Executions based on the contexts to which they belong use - // the function operator with the full resource name: - // `in_context()`. - // For example: - // `in_context("projects//locations//metadataStores//contexts/")` + // * **Attribute filtering**: + // For example: `display_name = "test"`. + // Supported fields include: `name`, `display_name`, `state`, + // `schema_title`, `create_time`, and `update_time`. + // Time fields, such as `create_time` and `update_time`, require values + // specified in RFC-3339 format. + // For example: `create_time = "2020-11-19T11:30:00-04:00"`. + // * **Metadata field**: + // To filter on metadata fields use traversal operation as follows: + // `metadata..` + // For example: `metadata.field_1.number_value = 10.0` + // * **Context based filtering**: + // To filter Executions based on the contexts to which they belong use + // the function operator with the full resource name: + // `in_context()`. + // For example: + // `in_context("projects//locations//metadataStores//contexts/")` // // Each of the above supported filters can be combined together using // logical operators (`AND` & `OR`). Maximum nested expression depth allowed @@ -3197,17 +3195,17 @@ type QueryArtifactLineageSubgraphRequest struct { // The syntax to define filter query is based on https://google.aip.dev/160. // The supported set of filters include the following: // - // - **Attribute filtering**: - // For example: `display_name = "test"` - // Supported fields include: `name`, `display_name`, `uri`, `state`, - // `schema_title`, `create_time`, and `update_time`. - // Time fields, such as `create_time` and `update_time`, require values - // specified in RFC-3339 format. - // For example: `create_time = "2020-11-19T11:30:00-04:00"` - // - **Metadata field**: - // To filter on metadata fields use traversal operation as follows: - // `metadata..`. - // For example: `metadata.field_1.number_value = 10.0` + // * **Attribute filtering**: + // For example: `display_name = "test"` + // Supported fields include: `name`, `display_name`, `uri`, `state`, + // `schema_title`, `create_time`, and `update_time`. + // Time fields, such as `create_time` and `update_time`, require values + // specified in RFC-3339 format. + // For example: `create_time = "2020-11-19T11:30:00-04:00"` + // * **Metadata field**: + // To filter on metadata fields use traversal operation as follows: + // `metadata..`. + // For example: `metadata.field_1.number_value = 10.0` // // Each of the above supported filter types can be combined together using // logical operators (`AND` & `OR`). Maximum nested expression depth allowed diff --git a/aiplatform/apiv1beta1/aiplatformpb/metadata_store.pb.go b/aiplatform/apiv1beta1/aiplatformpb/metadata_store.pb.go index 7121e6dc2206..6d823baabab2 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/metadata_store.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/metadata_store.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/metadata_store.proto package aiplatformpb diff --git a/aiplatform/apiv1beta1/aiplatformpb/migratable_resource.pb.go b/aiplatform/apiv1beta1/aiplatformpb/migratable_resource.pb.go index 013381f1ff3f..378b08e2aa3c 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/migratable_resource.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/migratable_resource.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/migratable_resource.proto package aiplatformpb @@ -45,7 +45,6 @@ type MigratableResource struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Resource: - // // *MigratableResource_MlEngineModelVersion_ // *MigratableResource_AutomlModel_ // *MigratableResource_AutomlDataset_ diff --git a/aiplatform/apiv1beta1/aiplatformpb/migration_service.pb.go b/aiplatform/apiv1beta1/aiplatformpb/migration_service.pb.go index c86b879187db..029521151162 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/migration_service.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/migration_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/migration_service.proto package aiplatformpb @@ -61,16 +61,16 @@ type SearchMigratableResourcesRequest struct { PageToken string `protobuf:"bytes,3,opt,name=page_token,json=pageToken,proto3" json:"page_token,omitempty"` // A filter for your search. You can use the following types of filters: // - // - Resource type filters. The following strings filter for a specific type + // * Resource type filters. The following strings filter for a specific type // of [MigratableResource][google.cloud.aiplatform.v1beta1.MigratableResource]: - // - `ml_engine_model_version:*` - // - `automl_model:*` - // - `automl_dataset:*` - // - `data_labeling_dataset:*` - // - "Migrated or not" filters. The following strings filter for resources + // * `ml_engine_model_version:*` + // * `automl_model:*` + // * `automl_dataset:*` + // * `data_labeling_dataset:*` + // * "Migrated or not" filters. The following strings filter for resources // that either have or have not already been migrated: - // - `last_migrate_time:*` filters for migrated resources. - // - `NOT last_migrate_time:*` filters for not yet migrated resources. + // * `last_migrate_time:*` filters for migrated resources. + // * `NOT last_migrate_time:*` filters for not yet migrated resources. Filter string `protobuf:"bytes,4,opt,name=filter,proto3" json:"filter,omitempty"` } @@ -264,7 +264,6 @@ type MigrateResourceRequest struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Request: - // // *MigrateResourceRequest_MigrateMlEngineModelVersionConfig_ // *MigrateResourceRequest_MigrateAutomlModelConfig_ // *MigrateResourceRequest_MigrateAutomlDatasetConfig_ @@ -433,7 +432,6 @@ type MigrateResourceResponse struct { // After migration, the resource name in Vertex AI. // // Types that are assignable to MigratedResource: - // // *MigrateResourceResponse_Dataset // *MigrateResourceResponse_Model MigratedResource isMigrateResourceResponse_MigratedResource `protobuf_oneof:"migrated_resource"` @@ -918,7 +916,6 @@ type BatchMigrateResourcesOperationMetadata_PartialResult struct { // migrated resource name will be filled. // // Types that are assignable to Result: - // // *BatchMigrateResourcesOperationMetadata_PartialResult_Error // *BatchMigrateResourcesOperationMetadata_PartialResult_Model // *BatchMigrateResourcesOperationMetadata_PartialResult_Dataset diff --git a/aiplatform/apiv1beta1/aiplatformpb/model.pb.go b/aiplatform/apiv1beta1/aiplatformpb/model.pb.go index 7bf7c0d31152..6b37a7cfb313 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/model.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/model.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/model.proto package aiplatformpb @@ -327,6 +327,7 @@ type Model struct { // `gcs_source` field of the // [InputConfig][google.cloud.aiplatform.v1beta1.BatchPredictionJob.InputConfig] object. // + // // If this Model doesn't support any of these formats it means it cannot be // used with a [BatchPredictionJob][google.cloud.aiplatform.v1beta1.BatchPredictionJob]. However, if it has // [supported_deployment_resources_types][google.cloud.aiplatform.v1beta1.Model.supported_deployment_resources_types], it could serve online @@ -358,6 +359,7 @@ type Model struct { // [BigQueryDestination][google.cloud.aiplatform.v1beta1.BatchPredictionJob.OutputConfig.bigquery_destination] // . // + // // If this Model doesn't support any of these formats it means it cannot be // used with a [BatchPredictionJob][google.cloud.aiplatform.v1beta1.BatchPredictionJob]. However, if it has // [supported_deployment_resources_types][google.cloud.aiplatform.v1beta1.Model.supported_deployment_resources_types], it could serve online @@ -845,16 +847,14 @@ type ModelContainerSpec struct { // // ```json // [ - // - // { - // "name": "VAR_1", - // "value": "foo" - // }, - // { - // "name": "VAR_2", - // "value": "$(VAR_1) bar" - // } - // + // { + // "name": "VAR_1", + // "value": "foo" + // }, + // { + // "name": "VAR_2", + // "value": "$(VAR_1) bar" + // } // ] // ``` // @@ -876,11 +876,9 @@ type ModelContainerSpec struct { // // ```json // [ - // - // { - // "containerPort": 8080 - // } - // + // { + // "containerPort": 8080 + // } // ] // ``` // @@ -906,16 +904,16 @@ type ModelContainerSpec struct { // /v1/endpoints/ENDPOINT/deployedModels/DEPLOYED_MODEL:predict // The placeholders in this value are replaced as follows: // - // - ENDPOINT: The last segment (following `endpoints/`)of the - // Endpoint.name][] field of the Endpoint where this Model has been - // deployed. (Vertex AI makes this value available to your container code - // as the [`AIP_ENDPOINT_ID` environment - // variable](https://cloud.google.com/vertex-ai/docs/predictions/custom-container-requirements#aip-variables).) + // * ENDPOINT: The last segment (following `endpoints/`)of the + // Endpoint.name][] field of the Endpoint where this Model has been + // deployed. (Vertex AI makes this value available to your container code + // as the [`AIP_ENDPOINT_ID` environment + // variable](https://cloud.google.com/vertex-ai/docs/predictions/custom-container-requirements#aip-variables).) // - // - DEPLOYED_MODEL: [DeployedModel.id][google.cloud.aiplatform.v1beta1.DeployedModel.id] of the `DeployedModel`. - // (Vertex AI makes this value available to your container code - // as the [`AIP_DEPLOYED_MODEL_ID` environment - // variable](https://cloud.google.com/vertex-ai/docs/predictions/custom-container-requirements#aip-variables).) + // * DEPLOYED_MODEL: [DeployedModel.id][google.cloud.aiplatform.v1beta1.DeployedModel.id] of the `DeployedModel`. + // (Vertex AI makes this value available to your container code + // as the [`AIP_DEPLOYED_MODEL_ID` environment + // variable](https://cloud.google.com/vertex-ai/docs/predictions/custom-container-requirements#aip-variables).) PredictRoute string `protobuf:"bytes,6,opt,name=predict_route,json=predictRoute,proto3" json:"predict_route,omitempty"` // Immutable. HTTP path on the container to send health checks to. Vertex AI // intermittently sends GET requests to this path on the container's IP @@ -933,16 +931,16 @@ type ModelContainerSpec struct { // /v1/endpoints/ENDPOINT/deployedModels/DEPLOYED_MODEL:predict // The placeholders in this value are replaced as follows: // - // - ENDPOINT: The last segment (following `endpoints/`)of the - // Endpoint.name][] field of the Endpoint where this Model has been - // deployed. (Vertex AI makes this value available to your container code - // as the [`AIP_ENDPOINT_ID` environment - // variable](https://cloud.google.com/vertex-ai/docs/predictions/custom-container-requirements#aip-variables).) + // * ENDPOINT: The last segment (following `endpoints/`)of the + // Endpoint.name][] field of the Endpoint where this Model has been + // deployed. (Vertex AI makes this value available to your container code + // as the [`AIP_ENDPOINT_ID` environment + // variable](https://cloud.google.com/vertex-ai/docs/predictions/custom-container-requirements#aip-variables).) // - // - DEPLOYED_MODEL: [DeployedModel.id][google.cloud.aiplatform.v1beta1.DeployedModel.id] of the `DeployedModel`. - // (Vertex AI makes this value available to your container code as the - // [`AIP_DEPLOYED_MODEL_ID` environment - // variable](https://cloud.google.com/vertex-ai/docs/predictions/custom-container-requirements#aip-variables).) + // * DEPLOYED_MODEL: [DeployedModel.id][google.cloud.aiplatform.v1beta1.DeployedModel.id] of the `DeployedModel`. + // (Vertex AI makes this value available to your container code as the + // [`AIP_DEPLOYED_MODEL_ID` environment + // variable](https://cloud.google.com/vertex-ai/docs/predictions/custom-container-requirements#aip-variables).) HealthRoute string `protobuf:"bytes,7,opt,name=health_route,json=healthRoute,proto3" json:"health_route,omitempty"` } diff --git a/aiplatform/apiv1beta1/aiplatformpb/model_deployment_monitoring_job.pb.go b/aiplatform/apiv1beta1/aiplatformpb/model_deployment_monitoring_job.pb.go index 92ed1a044245..874bf5a753b5 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/model_deployment_monitoring_job.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/model_deployment_monitoring_job.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/model_deployment_monitoring_job.proto package aiplatformpb diff --git a/aiplatform/apiv1beta1/aiplatformpb/model_evaluation.pb.go b/aiplatform/apiv1beta1/aiplatformpb/model_evaluation.pb.go index 6e1e9e485915..232516cff383 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/model_evaluation.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/model_evaluation.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/model_evaluation.proto package aiplatformpb @@ -67,6 +67,7 @@ type ModelEvaluation struct { // Aggregated explanation metrics for the Model's prediction output over the // data this ModelEvaluation uses. This field is populated only if the Model // is evaluated with explanations, and only for AutoML tabular Models. + // ModelExplanation *ModelExplanation `protobuf:"bytes,8,opt,name=model_explanation,json=modelExplanation,proto3" json:"model_explanation,omitempty"` // Describes the values of [ExplanationSpec][google.cloud.aiplatform.v1beta1.ExplanationSpec] that are used for explaining // the predicted values on the evaluated data. @@ -182,8 +183,8 @@ type ModelEvaluation_ModelEvaluationExplanationSpec struct { // // For AutoML Image Classification models, possible values are: // - // - `image-integrated-gradients` - // - `image-xrai` + // * `image-integrated-gradients` + // * `image-xrai` ExplanationType string `protobuf:"bytes,1,opt,name=explanation_type,json=explanationType,proto3" json:"explanation_type,omitempty"` // Explanation spec details. ExplanationSpec *ExplanationSpec `protobuf:"bytes,2,opt,name=explanation_spec,json=explanationSpec,proto3" json:"explanation_spec,omitempty"` diff --git a/aiplatform/apiv1beta1/aiplatformpb/model_evaluation_slice.pb.go b/aiplatform/apiv1beta1/aiplatformpb/model_evaluation_slice.pb.go index 1719a5843065..c1af1c169b8b 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/model_evaluation_slice.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/model_evaluation_slice.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/model_evaluation_slice.proto package aiplatformpb @@ -136,7 +136,7 @@ type ModelEvaluationSlice_Slice struct { // Output only. The dimension of the slice. // Well-known dimensions are: - // - `annotationSpec`: This slice is on the test data that has either + // * `annotationSpec`: This slice is on the test data that has either // ground truth or prediction with [AnnotationSpec.display_name][google.cloud.aiplatform.v1beta1.AnnotationSpec.display_name] // equals to [value][google.cloud.aiplatform.v1beta1.ModelEvaluationSlice.Slice.value]. Dimension string `protobuf:"bytes,1,opt,name=dimension,proto3" json:"dimension,omitempty"` diff --git a/aiplatform/apiv1beta1/aiplatformpb/model_monitoring.pb.go b/aiplatform/apiv1beta1/aiplatformpb/model_monitoring.pb.go index 2e126cc4adbd..c17f55b4e13e 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/model_monitoring.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/model_monitoring.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/model_monitoring.proto package aiplatformpb @@ -258,7 +258,6 @@ type ModelMonitoringAlertConfig struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Alert: - // // *ModelMonitoringAlertConfig_EmailAlertConfig_ Alert isModelMonitoringAlertConfig_Alert `protobuf_oneof:"alert"` // Dump the anomalies to Cloud Logging. The anomalies will be put to json @@ -340,7 +339,6 @@ type ThresholdConfig struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Threshold: - // // *ThresholdConfig_Value Threshold isThresholdConfig_Threshold `protobuf_oneof:"threshold"` } @@ -398,11 +396,10 @@ type isThresholdConfig_Threshold interface { type ThresholdConfig_Value struct { // Specify a threshold value that can trigger the alert. // If this threshold config is for feature distribution distance: - // 1. For categorical feature, the distribution distance is calculated by - // L-inifinity norm. - // 2. For numerical feature, the distribution distance is calculated by - // Jensen–Shannon divergence. - // + // 1. For categorical feature, the distribution distance is calculated by + // L-inifinity norm. + // 2. For numerical feature, the distribution distance is calculated by + // Jensen–Shannon divergence. // Each feature must have a non-zero threshold if they need to be monitored. // Otherwise no alert will be triggered for that feature. Value float64 `protobuf:"fixed64,1,opt,name=value,proto3,oneof"` @@ -467,7 +464,6 @@ type ModelMonitoringObjectiveConfig_TrainingDataset struct { unknownFields protoimpl.UnknownFields // Types that are assignable to DataSource: - // // *ModelMonitoringObjectiveConfig_TrainingDataset_Dataset // *ModelMonitoringObjectiveConfig_TrainingDataset_GcsSource // *ModelMonitoringObjectiveConfig_TrainingDataset_BigquerySource @@ -824,7 +820,6 @@ type ModelMonitoringObjectiveConfig_ExplanationConfig_ExplanationBaseline struct // used to generate the baseline of feature attribution scores. // // Types that are assignable to Destination: - // // *ModelMonitoringObjectiveConfig_ExplanationConfig_ExplanationBaseline_Gcs // *ModelMonitoringObjectiveConfig_ExplanationConfig_ExplanationBaseline_Bigquery Destination isModelMonitoringObjectiveConfig_ExplanationConfig_ExplanationBaseline_Destination `protobuf_oneof:"destination"` diff --git a/aiplatform/apiv1beta1/aiplatformpb/model_service.pb.go b/aiplatform/apiv1beta1/aiplatformpb/model_service.pb.go index 2e39d4de2bb8..44f4e78e1666 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/model_service.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/model_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/model_service.proto package aiplatformpb @@ -243,11 +243,9 @@ type GetModelRequest struct { // // In order to retrieve a specific version of the model, also provide // the version ID or version alias. - // - // Example: `projects/{project}/locations/{location}/models/{model}@2` - // or - // `projects/{project}/locations/{location}/models/{model}@golden` - // + // Example: `projects/{project}/locations/{location}/models/{model}@2` + // or + // `projects/{project}/locations/{location}/models/{model}@golden` // If no version ID or alias is specified, the "default" version will be // returned. The "default" version alias is created for the first version of // the model, and can be moved to other versions later on. There will be @@ -306,19 +304,19 @@ type ListModelsRequest struct { // An expression for filtering the results of the request. For field names // both snake_case and camelCase are supported. // - // - `model` supports = and !=. `model` represents the Model ID, + // * `model` supports = and !=. `model` represents the Model ID, // i.e. the last segment of the Model's [resource name][google.cloud.aiplatform.v1beta1.Model.name]. - // - `display_name` supports = and != - // - `labels` supports general map functions that is: - // - `labels.key=value` - key:value equality - // - `labels.key:* or labels:key - key existence - // - A key including a space must be quoted. `labels."a key"`. + // * `display_name` supports = and != + // * `labels` supports general map functions that is: + // * `labels.key=value` - key:value equality + // * `labels.key:* or labels:key - key existence + // * A key including a space must be quoted. `labels."a key"`. // // Some examples: // - // - `model=1234` - // - `displayName="myDisplayName"` - // - `labels.myKey="myValue"` + // * `model=1234` + // * `displayName="myDisplayName"` + // * `labels.myKey="myValue"` Filter string `protobuf:"bytes,2,opt,name=filter,proto3" json:"filter,omitempty"` // The standard list page size. PageSize int32 `protobuf:"varint,3,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"` @@ -475,14 +473,14 @@ type ListModelVersionsRequest struct { // An expression for filtering the results of the request. For field names // both snake_case and camelCase are supported. // - // - `labels` supports general map functions that is: - // - `labels.key=value` - key:value equality - // - `labels.key:* or labels:key - key existence - // - A key including a space must be quoted. `labels."a key"`. + // * `labels` supports general map functions that is: + // * `labels.key=value` - key:value equality + // * `labels.key:* or labels:key - key existence + // * A key including a space must be quoted. `labels."a key"`. // // Some examples: // - // - `labels.myKey="myValue"` + // * `labels.myKey="myValue"` Filter string `protobuf:"bytes,4,opt,name=filter,proto3" json:"filter,omitempty"` // Mask specifying which fields to read. ReadMask *fieldmaskpb.FieldMask `protobuf:"bytes,5,opt,name=read_mask,json=readMask,proto3" json:"read_mask,omitempty"` @@ -1602,7 +1600,7 @@ type ListModelEvaluationSlicesRequest struct { Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // The standard list filter. // - // - `slice.dimension` - for =. + // * `slice.dimension` - for =. Filter string `protobuf:"bytes,2,opt,name=filter,proto3" json:"filter,omitempty"` // The standard list page size. PageSize int32 `protobuf:"varint,3,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"` diff --git a/aiplatform/apiv1beta1/aiplatformpb/operation.pb.go b/aiplatform/apiv1beta1/aiplatformpb/operation.pb.go index d5d5f137f963..6ddd0cf07e7d 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/operation.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/operation.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/operation.proto package aiplatformpb diff --git a/aiplatform/apiv1beta1/aiplatformpb/pipeline_failure_policy.pb.go b/aiplatform/apiv1beta1/aiplatformpb/pipeline_failure_policy.pb.go index 1f86b3ca8a5c..99bf9dd5df28 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/pipeline_failure_policy.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/pipeline_failure_policy.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/pipeline_failure_policy.proto package aiplatformpb diff --git a/aiplatform/apiv1beta1/aiplatformpb/pipeline_job.pb.go b/aiplatform/apiv1beta1/aiplatformpb/pipeline_job.pb.go index 812607f8d32c..867829a2c274 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/pipeline_job.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/pipeline_job.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/pipeline_job.proto package aiplatformpb @@ -638,7 +638,6 @@ type PipelineTaskExecutorDetail struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Details: - // // *PipelineTaskExecutorDetail_ContainerDetail_ // *PipelineTaskExecutorDetail_CustomJobDetail_ Details isPipelineTaskExecutorDetail_Details `protobuf_oneof:"details"` @@ -834,7 +833,6 @@ type PipelineJob_RuntimeConfig_InputArtifact struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Kind: - // // *PipelineJob_RuntimeConfig_InputArtifact_ArtifactId Kind isPipelineJob_RuntimeConfig_InputArtifact_Kind `protobuf_oneof:"kind"` } diff --git a/aiplatform/apiv1beta1/aiplatformpb/pipeline_service.pb.go b/aiplatform/apiv1beta1/aiplatformpb/pipeline_service.pb.go index d3a03f7048db..f436f75fcdc9 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/pipeline_service.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/pipeline_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/pipeline_service.proto package aiplatformpb @@ -166,22 +166,22 @@ type ListTrainingPipelinesRequest struct { // // Supported fields: // - // - `display_name` supports `=`, `!=` comparisons, and `:` wildcard. - // - `state` supports `=`, `!=` comparisons. - // - `training_task_definition` `=`, `!=` comparisons, and `:` wildcard. - // - `create_time` supports `=`, `!=`,`<`, `<=`,`>`, `>=` comparisons. + // * `display_name` supports `=`, `!=` comparisons, and `:` wildcard. + // * `state` supports `=`, `!=` comparisons. + // * `training_task_definition` `=`, `!=` comparisons, and `:` wildcard. + // * `create_time` supports `=`, `!=`,`<`, `<=`,`>`, `>=` comparisons. // `create_time` must be in RFC 3339 format. - // - `labels` supports general map functions that is: + // * `labels` supports general map functions that is: // `labels.key=value` - key:value equality // `labels.key:* - key existence // // Some examples of using the filter are: // - // - `state="PIPELINE_STATE_SUCCEEDED" AND display_name:"my_pipeline_*"` - // - `state!="PIPELINE_STATE_FAILED" OR display_name="my_pipeline"` - // - `NOT display_name="my_pipeline"` - // - `create_time>"2021-05-18T00:00:00Z"` - // - `training_task_definition:"*automl_text_classification*"` + // * `state="PIPELINE_STATE_SUCCEEDED" AND display_name:"my_pipeline_*"` + // * `state!="PIPELINE_STATE_FAILED" OR display_name="my_pipeline"` + // * `NOT display_name="my_pipeline"` + // * `create_time>"2021-05-18T00:00:00Z"` + // * `training_task_definition:"*automl_text_classification*"` Filter string `protobuf:"bytes,2,opt,name=filter,proto3" json:"filter,omitempty"` // The standard list page size. PageSize int32 `protobuf:"varint,3,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"` @@ -558,22 +558,22 @@ type ListPipelineJobsRequest struct { // Lists the PipelineJobs that match the filter expression. The following // fields are supported: // - // - `pipeline_name`: Supports `=` and `!=` comparisons. - // - `display_name`: Supports `=`, `!=` comparisons, and `:` wildcard. - // - `pipeline_job_user_id`: Supports `=`, `!=` comparisons, and `:` wildcard. - // for example, can check if pipeline's display_name contains *step* by - // doing display_name:\"*step*\" - // - `state`: Supports `=` and `!=` comparisons. - // - `create_time`: Supports `=`, `!=`, `<`, `>`, `<=`, and `>=` comparisons. - // Values must be in RFC 3339 format. - // - `update_time`: Supports `=`, `!=`, `<`, `>`, `<=`, and `>=` comparisons. - // Values must be in RFC 3339 format. - // - `end_time`: Supports `=`, `!=`, `<`, `>`, `<=`, and `>=` comparisons. - // Values must be in RFC 3339 format. - // - `labels`: Supports key-value equality and key presence. - // - `template_uri`: Supports `=`, `!=` comparisons, and `:` wildcard. - // - `template_metadata.version`: Supports `=`, `!=` comparisons, and `:` - // wildcard. + // * `pipeline_name`: Supports `=` and `!=` comparisons. + // * `display_name`: Supports `=`, `!=` comparisons, and `:` wildcard. + // * `pipeline_job_user_id`: Supports `=`, `!=` comparisons, and `:` wildcard. + // for example, can check if pipeline's display_name contains *step* by + // doing display_name:\"*step*\" + // * `state`: Supports `=` and `!=` comparisons. + // * `create_time`: Supports `=`, `!=`, `<`, `>`, `<=`, and `>=` comparisons. + // Values must be in RFC 3339 format. + // * `update_time`: Supports `=`, `!=`, `<`, `>`, `<=`, and `>=` comparisons. + // Values must be in RFC 3339 format. + // * `end_time`: Supports `=`, `!=`, `<`, `>`, `<=`, and `>=` comparisons. + // Values must be in RFC 3339 format. + // * `labels`: Supports key-value equality and key presence. + // * `template_uri`: Supports `=`, `!=` comparisons, and `:` wildcard. + // * `template_metadata.version`: Supports `=`, `!=` comparisons, and `:` + // wildcard. // // Filter expressions can be combined together using logical operators // (`AND` & `OR`). @@ -584,11 +584,11 @@ type ListPipelineJobsRequest struct { // // Examples: // - // - `create_time>"2021-05-18T00:00:00Z" OR - // update_time>"2020-05-18T00:00:00Z"` PipelineJobs created or updated - // after 2020-05-18 00:00:00 UTC. - // - `labels.env = "prod"` - // PipelineJobs with label "env" set to "prod". + // * `create_time>"2021-05-18T00:00:00Z" OR + // update_time>"2020-05-18T00:00:00Z"` PipelineJobs created or updated + // after 2020-05-18 00:00:00 UTC. + // * `labels.env = "prod"` + // PipelineJobs with label "env" set to "prod". Filter string `protobuf:"bytes,2,opt,name=filter,proto3" json:"filter,omitempty"` // The standard list page size. PageSize int32 `protobuf:"varint,3,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"` @@ -606,10 +606,10 @@ type ListPipelineJobsRequest struct { // time in ascending order. if order_by is not specified, it will order by // default order is create time in descending order. Supported fields: // - // - `create_time` - // - `update_time` - // - `end_time` - // - `start_time` + // * `create_time` + // * `update_time` + // * `end_time` + // * `start_time` OrderBy string `protobuf:"bytes,6,opt,name=order_by,json=orderBy,proto3" json:"order_by,omitempty"` // Mask specifying which fields to read. ReadMask *fieldmaskpb.FieldMask `protobuf:"bytes,7,opt,name=read_mask,json=readMask,proto3" json:"read_mask,omitempty"` diff --git a/aiplatform/apiv1beta1/aiplatformpb/pipeline_state.pb.go b/aiplatform/apiv1beta1/aiplatformpb/pipeline_state.pb.go index 266b98829666..10b5bca7e885 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/pipeline_state.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/pipeline_state.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/pipeline_state.proto package aiplatformpb diff --git a/aiplatform/apiv1beta1/aiplatformpb/prediction_service.pb.go b/aiplatform/apiv1beta1/aiplatformpb/prediction_service.pb.go index 4e5c45b54924..1becd123d629 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/prediction_service.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/prediction_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/prediction_service.proto package aiplatformpb @@ -315,10 +315,10 @@ type ExplainRequest struct { // [explanation_spec][google.cloud.aiplatform.v1beta1.DeployedModel.explanation_spec] of the DeployedModel. // Can be used for explaining prediction results with different // configurations, such as: - // - Explaining top-5 predictions results as opposed to top-1; - // - Increasing path count or step count of the attribution methods to reduce - // approximate errors; - // - Using different baselines for explaining the prediction results. + // - Explaining top-5 predictions results as opposed to top-1; + // - Increasing path count or step count of the attribution methods to reduce + // approximate errors; + // - Using different baselines for explaining the prediction results. ExplanationSpecOverride *ExplanationSpecOverride `protobuf:"bytes,5,opt,name=explanation_spec_override,json=explanationSpecOverride,proto3" json:"explanation_spec_override,omitempty"` // If specified, this ExplainRequest will be served by the chosen // DeployedModel, overriding [Endpoint.traffic_split][google.cloud.aiplatform.v1beta1.Endpoint.traffic_split]. diff --git a/aiplatform/apiv1beta1/aiplatformpb/saved_query.pb.go b/aiplatform/apiv1beta1/aiplatformpb/saved_query.pb.go index 26ed4557b8cd..4bd97626c36c 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/saved_query.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/saved_query.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/saved_query.proto package aiplatformpb diff --git a/aiplatform/apiv1beta1/aiplatformpb/specialist_pool.pb.go b/aiplatform/apiv1beta1/aiplatformpb/specialist_pool.pb.go index 50c6491e655b..f7c48f9f99d8 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/specialist_pool.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/specialist_pool.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/specialist_pool.proto package aiplatformpb diff --git a/aiplatform/apiv1beta1/aiplatformpb/specialist_pool_service.pb.go b/aiplatform/apiv1beta1/aiplatformpb/specialist_pool_service.pb.go index bb0c6d3f7d28..7e45c64601c2 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/specialist_pool_service.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/specialist_pool_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/specialist_pool_service.proto package aiplatformpb diff --git a/aiplatform/apiv1beta1/aiplatformpb/study.pb.go b/aiplatform/apiv1beta1/aiplatformpb/study.pb.go index ffe57e99a59b..44ee1a57b643 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/study.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/study.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/study.proto package aiplatformpb @@ -736,7 +736,6 @@ type StudySpec struct { unknownFields protoimpl.UnknownFields // Types that are assignable to AutomatedStoppingSpec: - // // *StudySpec_DecayCurveStoppingSpec // *StudySpec_MedianAutomatedStoppingSpec_ // *StudySpec_ConvexStopConfig_ @@ -1104,7 +1103,6 @@ type StudySpec_ParameterSpec struct { unknownFields protoimpl.UnknownFields // Types that are assignable to ParameterValueSpec: - // // *StudySpec_ParameterSpec_DoubleValueSpec_ // *StudySpec_ParameterSpec_IntegerValueSpec_ // *StudySpec_ParameterSpec_CategoricalValueSpec_ @@ -1923,7 +1921,6 @@ type StudySpec_ParameterSpec_ConditionalParameterSpec struct { // space. // // Types that are assignable to ParentValueCondition: - // // *StudySpec_ParameterSpec_ConditionalParameterSpec_ParentDiscreteValues // *StudySpec_ParameterSpec_ConditionalParameterSpec_ParentIntValues // *StudySpec_ParameterSpec_ConditionalParameterSpec_ParentCategoricalValues diff --git a/aiplatform/apiv1beta1/aiplatformpb/tensorboard.pb.go b/aiplatform/apiv1beta1/aiplatformpb/tensorboard.pb.go index 70f5353f5344..21cf34031d41 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/tensorboard.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/tensorboard.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/tensorboard.proto package aiplatformpb diff --git a/aiplatform/apiv1beta1/aiplatformpb/tensorboard_data.pb.go b/aiplatform/apiv1beta1/aiplatformpb/tensorboard_data.pb.go index ef75cff38aa6..04122ad66e4d 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/tensorboard_data.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/tensorboard_data.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/tensorboard_data.proto package aiplatformpb @@ -115,7 +115,6 @@ type TimeSeriesDataPoint struct { // Value of this time series data point. // // Types that are assignable to Value: - // // *TimeSeriesDataPoint_Scalar // *TimeSeriesDataPoint_Tensor // *TimeSeriesDataPoint_Blobs diff --git a/aiplatform/apiv1beta1/aiplatformpb/tensorboard_experiment.pb.go b/aiplatform/apiv1beta1/aiplatformpb/tensorboard_experiment.pb.go index fffde9efccde..84912cf676f4 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/tensorboard_experiment.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/tensorboard_experiment.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/tensorboard_experiment.proto package aiplatformpb @@ -69,7 +69,7 @@ type TensorboardExperiment struct { // and are immutable. Following system labels exist for each Dataset: // * "aiplatform.googleapis.com/dataset_metadata_schema": // - output only, its value is the - // [metadata_schema's][metadata_schema_uri] title. + // [metadata_schema's][metadata_schema_uri] title. Labels map[string]string `protobuf:"bytes,6,rep,name=labels,proto3" json:"labels,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` // Used to perform consistent read-modify-write updates. If not set, a blind // "overwrite" update happens. diff --git a/aiplatform/apiv1beta1/aiplatformpb/tensorboard_run.pb.go b/aiplatform/apiv1beta1/aiplatformpb/tensorboard_run.pb.go index 17d4d1215569..0f0779a44e7b 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/tensorboard_run.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/tensorboard_run.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/tensorboard_run.proto package aiplatformpb diff --git a/aiplatform/apiv1beta1/aiplatformpb/tensorboard_service.pb.go b/aiplatform/apiv1beta1/aiplatformpb/tensorboard_service.pb.go index 8678cbfd9ed2..87276a19d4ef 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/tensorboard_service.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/tensorboard_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/tensorboard_service.proto package aiplatformpb diff --git a/aiplatform/apiv1beta1/aiplatformpb/tensorboard_time_series.pb.go b/aiplatform/apiv1beta1/aiplatformpb/tensorboard_time_series.pb.go index 5204f504cc12..d5f2681ddfde 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/tensorboard_time_series.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/tensorboard_time_series.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/tensorboard_time_series.proto package aiplatformpb diff --git a/aiplatform/apiv1beta1/aiplatformpb/training_pipeline.pb.go b/aiplatform/apiv1beta1/aiplatformpb/training_pipeline.pb.go index da82780dbef2..ae5a02869d8d 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/training_pipeline.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/training_pipeline.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/training_pipeline.proto package aiplatformpb @@ -297,7 +297,6 @@ type InputDataConfig struct { // If no split type is provided, the [fraction_split][google.cloud.aiplatform.v1beta1.InputDataConfig.fraction_split] is used by default. // // Types that are assignable to Split: - // // *InputDataConfig_FractionSplit // *InputDataConfig_FilterSplit // *InputDataConfig_PredefinedSplit @@ -309,8 +308,8 @@ type InputDataConfig struct { // The destination of the training data to be written to. // // Supported destination file formats: - // - For non-tabular data: "jsonl". - // - For tabular data: "csv" and "bigquery". + // * For non-tabular data: "jsonl". + // * For tabular data: "csv" and "bigquery". // // The following Vertex AI environment variables are passed to containers // or python modules of the training task when this field is set: @@ -321,7 +320,6 @@ type InputDataConfig struct { // * AIP_TEST_DATA_URI : Sharded exported test data uris. // // Types that are assignable to Destination: - // // *InputDataConfig_GcsDestination // *InputDataConfig_BigqueryDestination Destination isInputDataConfig_Destination `protobuf_oneof:"destination"` diff --git a/aiplatform/apiv1beta1/aiplatformpb/types.pb.go b/aiplatform/apiv1beta1/aiplatformpb/types.pb.go index e0bac25b2900..830e6a84dcf3 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/types.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/types.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/types.proto package aiplatformpb diff --git a/aiplatform/apiv1beta1/aiplatformpb/unmanaged_container_model.pb.go b/aiplatform/apiv1beta1/aiplatformpb/unmanaged_container_model.pb.go index 6d7c2641e84e..cadfb6a96340 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/unmanaged_container_model.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/unmanaged_container_model.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/unmanaged_container_model.proto package aiplatformpb diff --git a/aiplatform/apiv1beta1/aiplatformpb/user_action_reference.pb.go b/aiplatform/apiv1beta1/aiplatformpb/user_action_reference.pb.go index 1bfa865de2c4..335b596ddd3b 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/user_action_reference.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/user_action_reference.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/user_action_reference.proto package aiplatformpb @@ -43,7 +43,6 @@ type UserActionReference struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Reference: - // // *UserActionReference_Operation // *UserActionReference_DataLabelingJob Reference isUserActionReference_Reference `protobuf_oneof:"reference"` diff --git a/aiplatform/apiv1beta1/aiplatformpb/value.pb.go b/aiplatform/apiv1beta1/aiplatformpb/value.pb.go index 4d9975085c59..182d0b14cca9 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/value.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/value.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/value.proto package aiplatformpb @@ -42,7 +42,6 @@ type Value struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Value: - // // *Value_IntValue // *Value_DoubleValue // *Value_StringValue diff --git a/aiplatform/apiv1beta1/aiplatformpb/vizier_service.pb.go b/aiplatform/apiv1beta1/aiplatformpb/vizier_service.pb.go index 3369a06ba57b..ca9c85ef3bea 100644 --- a/aiplatform/apiv1beta1/aiplatformpb/vizier_service.pb.go +++ b/aiplatform/apiv1beta1/aiplatformpb/vizier_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/aiplatform/v1beta1/vizier_service.proto package aiplatformpb diff --git a/aiplatform/apiv1beta1/dataset_client.go b/aiplatform/apiv1beta1/dataset_client.go index c4104bf483fc..55478e8fcec8 100644 --- a/aiplatform/apiv1beta1/dataset_client.go +++ b/aiplatform/apiv1beta1/dataset_client.go @@ -57,6 +57,7 @@ type DatasetCallOptions struct { ImportData []gax.CallOption ExportData []gax.CallOption ListDataItems []gax.CallOption + SearchDataItems []gax.CallOption ListSavedQueries []gax.CallOption GetAnnotationSpec []gax.CallOption ListAnnotations []gax.CallOption @@ -94,6 +95,7 @@ func defaultDatasetCallOptions() *DatasetCallOptions { ImportData: []gax.CallOption{}, ExportData: []gax.CallOption{}, ListDataItems: []gax.CallOption{}, + SearchDataItems: []gax.CallOption{}, ListSavedQueries: []gax.CallOption{}, GetAnnotationSpec: []gax.CallOption{}, ListAnnotations: []gax.CallOption{}, @@ -120,6 +122,7 @@ func defaultDatasetRESTCallOptions() *DatasetCallOptions { ImportData: []gax.CallOption{}, ExportData: []gax.CallOption{}, ListDataItems: []gax.CallOption{}, + SearchDataItems: []gax.CallOption{}, ListSavedQueries: []gax.CallOption{}, GetAnnotationSpec: []gax.CallOption{}, ListAnnotations: []gax.CallOption{}, @@ -153,6 +156,7 @@ type internalDatasetClient interface { ExportData(context.Context, *aiplatformpb.ExportDataRequest, ...gax.CallOption) (*ExportDataOperation, error) ExportDataOperation(name string) *ExportDataOperation ListDataItems(context.Context, *aiplatformpb.ListDataItemsRequest, ...gax.CallOption) *DataItemIterator + SearchDataItems(context.Context, *aiplatformpb.SearchDataItemsRequest, ...gax.CallOption) *DataItemViewIterator ListSavedQueries(context.Context, *aiplatformpb.ListSavedQueriesRequest, ...gax.CallOption) *SavedQueryIterator GetAnnotationSpec(context.Context, *aiplatformpb.GetAnnotationSpecRequest, ...gax.CallOption) (*aiplatformpb.AnnotationSpec, error) ListAnnotations(context.Context, *aiplatformpb.ListAnnotationsRequest, ...gax.CallOption) *AnnotationIterator @@ -273,6 +277,11 @@ func (c *DatasetClient) ListDataItems(ctx context.Context, req *aiplatformpb.Lis return c.internalClient.ListDataItems(ctx, req, opts...) } +// SearchDataItems searches DataItems in a Dataset. +func (c *DatasetClient) SearchDataItems(ctx context.Context, req *aiplatformpb.SearchDataItemsRequest, opts ...gax.CallOption) *DataItemViewIterator { + return c.internalClient.SearchDataItems(ctx, req, opts...) +} + // ListSavedQueries lists SavedQueries in a Dataset. func (c *DatasetClient) ListSavedQueries(ctx context.Context, req *aiplatformpb.ListSavedQueriesRequest, opts ...gax.CallOption) *SavedQueryIterator { return c.internalClient.ListSavedQueries(ctx, req, opts...) @@ -770,6 +779,51 @@ func (c *datasetGRPCClient) ListDataItems(ctx context.Context, req *aiplatformpb return it } +func (c *datasetGRPCClient) SearchDataItems(ctx context.Context, req *aiplatformpb.SearchDataItemsRequest, opts ...gax.CallOption) *DataItemViewIterator { + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "dataset", url.QueryEscape(req.GetDataset()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).SearchDataItems[0:len((*c.CallOptions).SearchDataItems):len((*c.CallOptions).SearchDataItems)], opts...) + it := &DataItemViewIterator{} + req = proto.Clone(req).(*aiplatformpb.SearchDataItemsRequest) + it.InternalFetch = func(pageSize int, pageToken string) ([]*aiplatformpb.DataItemView, string, error) { + resp := &aiplatformpb.SearchDataItemsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.datasetClient.SearchDataItems(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, "", err + } + + it.Response = resp + return resp.GetDataItemViews(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + func (c *datasetGRPCClient) ListSavedQueries(ctx context.Context, req *aiplatformpb.ListSavedQueriesRequest, opts ...gax.CallOption) *SavedQueryIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1682,6 +1736,130 @@ func (c *datasetRESTClient) ListDataItems(ctx context.Context, req *aiplatformpb return it } +// SearchDataItems searches DataItems in a Dataset. +func (c *datasetRESTClient) SearchDataItems(ctx context.Context, req *aiplatformpb.SearchDataItemsRequest, opts ...gax.CallOption) *DataItemViewIterator { + it := &DataItemViewIterator{} + req = proto.Clone(req).(*aiplatformpb.SearchDataItemsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*aiplatformpb.DataItemView, string, error) { + resp := &aiplatformpb.SearchDataItemsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1beta1/%v:searchDataItems", req.GetDataset()) + + params := url.Values{} + if items := req.GetAnnotationFilters(); len(items) > 0 { + for _, item := range items { + params.Add("annotationFilters", fmt.Sprintf("%v", item)) + } + } + if req.GetAnnotationsFilter() != "" { + params.Add("annotationsFilter", fmt.Sprintf("%v", req.GetAnnotationsFilter())) + } + if req.GetAnnotationsLimit() != 0 { + params.Add("annotationsLimit", fmt.Sprintf("%v", req.GetAnnotationsLimit())) + } + if req.GetDataItemFilter() != "" { + params.Add("dataItemFilter", fmt.Sprintf("%v", req.GetDataItemFilter())) + } + if req.GetDataLabelingJob() != "" { + params.Add("dataLabelingJob", fmt.Sprintf("%v", req.GetDataLabelingJob())) + } + if req.GetFieldMask() != nil { + fieldMask, err := protojson.Marshal(req.GetFieldMask()) + if err != nil { + return nil, "", err + } + params.Add("fieldMask", string(fieldMask)) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetOrderByAnnotation().GetOrderBy() != "" { + params.Add("orderByAnnotation.orderBy", fmt.Sprintf("%v", req.GetOrderByAnnotation().GetOrderBy())) + } + params.Add("orderByAnnotation.savedQuery", fmt.Sprintf("%v", req.GetOrderByAnnotation().GetSavedQuery())) + if req.GetOrderByDataItem() != "" { + params.Add("orderByDataItem", fmt.Sprintf("%v", req.GetOrderByDataItem())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + if req.GetSavedQuery() != "" { + params.Add("savedQuery", fmt.Sprintf("%v", req.GetSavedQuery())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetDataItemViews(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + // ListSavedQueries lists SavedQueries in a Dataset. func (c *datasetRESTClient) ListSavedQueries(ctx context.Context, req *aiplatformpb.ListSavedQueriesRequest, opts ...gax.CallOption) *SavedQueryIterator { it := &SavedQueryIterator{} @@ -2965,6 +3143,53 @@ func (it *DataItemIterator) takeBuf() interface{} { return b } +// DataItemViewIterator manages a stream of *aiplatformpb.DataItemView. +type DataItemViewIterator struct { + items []*aiplatformpb.DataItemView + pageInfo *iterator.PageInfo + nextFunc func() error + + // Response is the raw response for the current page. + // It must be cast to the RPC response type. + // Calling Next() or InternalFetch() updates this value. + Response interface{} + + // 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 []*aiplatformpb.DataItemView, nextPageToken string, err error) +} + +// PageInfo supports pagination. See the google.golang.org/api/iterator package for details. +func (it *DataItemViewIterator) 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 *DataItemViewIterator) Next() (*aiplatformpb.DataItemView, error) { + var item *aiplatformpb.DataItemView + if err := it.nextFunc(); err != nil { + return item, err + } + item = it.items[0] + it.items = it.items[1:] + return item, nil +} + +func (it *DataItemViewIterator) bufLen() int { + return len(it.items) +} + +func (it *DataItemViewIterator) takeBuf() interface{} { + b := it.items + it.items = nil + return b +} + // DatasetIterator manages a stream of *aiplatformpb.Dataset. type DatasetIterator struct { items []*aiplatformpb.Dataset diff --git a/aiplatform/apiv1beta1/dataset_client_example_test.go b/aiplatform/apiv1beta1/dataset_client_example_test.go index b3778e7adc40..e6106a53df15 100644 --- a/aiplatform/apiv1beta1/dataset_client_example_test.go +++ b/aiplatform/apiv1beta1/dataset_client_example_test.go @@ -291,6 +291,37 @@ func ExampleDatasetClient_ListDataItems() { } } +func ExampleDatasetClient_SearchDataItems() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := aiplatform.NewDatasetClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + req := &aiplatformpb.SearchDataItemsRequest{ + // TODO: Fill request struct fields. + // See https://pkg.go.dev/cloud.google.com/go/aiplatform/apiv1beta1/aiplatformpb#SearchDataItemsRequest. + } + it := c.SearchDataItems(ctx, req) + for { + resp, err := it.Next() + if err == iterator.Done { + break + } + if err != nil { + // TODO: Handle error. + } + // TODO: Use resp. + _ = resp + } +} + func ExampleDatasetClient_ListSavedQueries() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/aiplatform/apiv1beta1/gapic_metadata.json b/aiplatform/apiv1beta1/gapic_metadata.json index 9b69c1227ffb..8f16b8c05d6c 100644 --- a/aiplatform/apiv1beta1/gapic_metadata.json +++ b/aiplatform/apiv1beta1/gapic_metadata.json @@ -95,6 +95,11 @@ "ListSavedQueries" ] }, + "SearchDataItems": { + "methods": [ + "SearchDataItems" + ] + }, "SetIamPolicy": { "methods": [ "SetIamPolicy" @@ -205,6 +210,11 @@ "ListSavedQueries" ] }, + "SearchDataItems": { + "methods": [ + "SearchDataItems" + ] + }, "SetIamPolicy": { "methods": [ "SetIamPolicy" diff --git a/aiplatform/apiv1beta1/tensorboard_client.go b/aiplatform/apiv1beta1/tensorboard_client.go index 799770933248..6031135f3db1 100644 --- a/aiplatform/apiv1beta1/tensorboard_client.go +++ b/aiplatform/apiv1beta1/tensorboard_client.go @@ -3085,8 +3085,10 @@ func (c *tensorboardRESTClient) BatchReadTensorboardTimeSeriesData(ctx context.C baseUrl.Path += fmt.Sprintf("/v1beta1/%v/experiments/*/runs/*/timeSeries:batchRead", req.GetTensorboard()) params := url.Values{} - if req.GetTimeSeries() != nil { - params.Add("timeSeries", fmt.Sprintf("%v", req.GetTimeSeries())) + if items := req.GetTimeSeries(); len(items) > 0 { + for _, item := range items { + params.Add("timeSeries", fmt.Sprintf("%v", item)) + } } baseUrl.RawQuery = params.Encode() @@ -3215,8 +3217,10 @@ func (c *tensorboardRESTClient) ReadTensorboardBlobData(ctx context.Context, req baseUrl.Path += fmt.Sprintf("/v1beta1/%v:readBlobData", req.GetTimeSeries()) params := url.Values{} - if req.GetBlobIds() != nil { - params.Add("blobIds", fmt.Sprintf("%v", req.GetBlobIds())) + if items := req.GetBlobIds(); len(items) > 0 { + for _, item := range items { + params.Add("blobIds", fmt.Sprintf("%v", item)) + } } baseUrl.RawQuery = params.Encode() diff --git a/analytics/admin/apiv1alpha/adminpb/access_report.pb.go b/analytics/admin/apiv1alpha/adminpb/access_report.pb.go index d0cdbf9626c3..2f80bba9d15f 100644 --- a/analytics/admin/apiv1alpha/adminpb/access_report.pb.go +++ b/analytics/admin/apiv1alpha/adminpb/access_report.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/analytics/admin/v1alpha/access_report.proto package adminpb @@ -414,7 +414,6 @@ type AccessFilterExpression struct { // Specify one type of filter expression for `FilterExpression`. // // Types that are assignable to OneExpression: - // // *AccessFilterExpression_AndGroup // *AccessFilterExpression_OrGroup // *AccessFilterExpression_NotExpression @@ -580,7 +579,6 @@ type AccessFilter struct { // Specify one type of filter for `Filter`. // // Types that are assignable to OneFilter: - // // *AccessFilter_StringFilter // *AccessFilter_InListFilter // *AccessFilter_NumericFilter @@ -946,7 +944,6 @@ type NumericValue struct { // One of a numeric value // // Types that are assignable to OneValue: - // // *NumericValue_Int64Value // *NumericValue_DoubleValue OneValue isNumericValue_OneValue `protobuf_oneof:"one_value"` @@ -1034,7 +1031,6 @@ type AccessOrderBy struct { // Specify one type of order by for `OrderBy`. // // Types that are assignable to OneOrderBy: - // // *AccessOrderBy_Metric // *AccessOrderBy_Dimension OneOrderBy isAccessOrderBy_OneOrderBy `protobuf_oneof:"one_order_by"` diff --git a/analytics/admin/apiv1alpha/adminpb/analytics_admin.pb.go b/analytics/admin/apiv1alpha/adminpb/analytics_admin.pb.go index a9ef1f59ae3d..e71cbc4f9a30 100644 --- a/analytics/admin/apiv1alpha/adminpb/analytics_admin.pb.go +++ b/analytics/admin/apiv1alpha/adminpb/analytics_admin.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/analytics/admin/v1alpha/analytics_admin.proto package adminpb diff --git a/analytics/admin/apiv1alpha/adminpb/audience.pb.go b/analytics/admin/apiv1alpha/adminpb/audience.pb.go index 25436d9bc956..d82093558699 100644 --- a/analytics/admin/apiv1alpha/adminpb/audience.pb.go +++ b/analytics/admin/apiv1alpha/adminpb/audience.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/analytics/admin/v1alpha/audience.proto package adminpb @@ -402,7 +402,6 @@ type AudienceDimensionOrMetricFilter struct { // One of the above filters. // // Types that are assignable to OneFilter: - // // *AudienceDimensionOrMetricFilter_StringFilter_ // *AudienceDimensionOrMetricFilter_InListFilter_ // *AudienceDimensionOrMetricFilter_NumericFilter_ @@ -630,7 +629,6 @@ type AudienceFilterExpression struct { // The expression applied to a filter. // // Types that are assignable to Expr: - // // *AudienceFilterExpression_AndGroup // *AudienceFilterExpression_OrGroup // *AudienceFilterExpression_NotExpression @@ -946,7 +944,6 @@ type AudienceFilterClause struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Filter: - // // *AudienceFilterClause_SimpleFilter // *AudienceFilterClause_SequenceFilter Filter isAudienceFilterClause_Filter `protobuf_oneof:"filter"` @@ -1346,7 +1343,6 @@ type AudienceDimensionOrMetricFilter_NumericValue struct { // One of a numeric value. // // Types that are assignable to OneValue: - // // *AudienceDimensionOrMetricFilter_NumericValue_Int64Value // *AudienceDimensionOrMetricFilter_NumericValue_DoubleValue OneValue isAudienceDimensionOrMetricFilter_NumericValue_OneValue `protobuf_oneof:"one_value"` diff --git a/analytics/admin/apiv1alpha/adminpb/resources.pb.go b/analytics/admin/apiv1alpha/adminpb/resources.pb.go index 645e5beaca0b..61fe3dc09306 100644 --- a/analytics/admin/apiv1alpha/adminpb/resources.pb.go +++ b/analytics/admin/apiv1alpha/adminpb/resources.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/analytics/admin/v1alpha/resources.proto package adminpb @@ -1467,6 +1467,7 @@ type Property struct { TimeZone string `protobuf:"bytes,7,opt,name=time_zone,json=timeZone,proto3" json:"time_zone,omitempty"` // The currency type used in reports involving monetary values. // + // // Format: https://en.wikipedia.org/wiki/ISO_4217 // Examples: "USD", "EUR", "JPY" CurrencyCode string `protobuf:"bytes,8,opt,name=currency_code,json=currencyCode,proto3" json:"currency_code,omitempty"` @@ -1618,7 +1619,6 @@ type DataStream struct { // set corresponds to the type of this stream. // // Types that are assignable to StreamData: - // // *DataStream_WebStreamData_ // *DataStream_AndroidAppStreamData_ // *DataStream_IosAppStreamData_ @@ -3733,7 +3733,6 @@ type ChangeHistoryChange_ChangeHistoryResource struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Resource: - // // *ChangeHistoryChange_ChangeHistoryResource_Account // *ChangeHistoryChange_ChangeHistoryResource_Property // *ChangeHistoryChange_ChangeHistoryResource_FirebaseLink diff --git a/analytics/admin/apiv1alpha/analytics_admin_client.go b/analytics/admin/apiv1alpha/analytics_admin_client.go index d312adc11d8d..0c1115096ae3 100644 --- a/analytics/admin/apiv1alpha/analytics_admin_client.go +++ b/analytics/admin/apiv1alpha/analytics_admin_client.go @@ -4765,6 +4765,11 @@ func (c *analyticsAdminRESTClient) GetAccount(ctx context.Context, req *adminpb. } baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -4836,6 +4841,7 @@ func (c *analyticsAdminRESTClient) ListAccounts(ctx context.Context, req *adminp baseUrl.Path += fmt.Sprintf("/v1alpha/accounts") params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -4922,6 +4928,11 @@ func (c *analyticsAdminRESTClient) DeleteAccount(ctx context.Context, req *admin } baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -4965,6 +4976,7 @@ func (c *analyticsAdminRESTClient) UpdateAccount(ctx context.Context, req *admin baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetAccount().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -5034,6 +5046,11 @@ func (c *analyticsAdminRESTClient) ProvisionAccountTicket(ctx context.Context, r } baseUrl.Path += fmt.Sprintf("/v1alpha/accounts:provisionAccountTicket") + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) opts = append((*c.CallOptions).ProvisionAccountTicket[0:len((*c.CallOptions).ProvisionAccountTicket):len((*c.CallOptions).ProvisionAccountTicket)], opts...) @@ -5099,6 +5116,7 @@ func (c *analyticsAdminRESTClient) ListAccountSummaries(ctx context.Context, req baseUrl.Path += fmt.Sprintf("/v1alpha/accountSummaries") params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -5172,6 +5190,11 @@ func (c *analyticsAdminRESTClient) GetProperty(ctx context.Context, req *adminpb } baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -5244,6 +5267,7 @@ func (c *analyticsAdminRESTClient) ListProperties(ctx context.Context, req *admi baseUrl.Path += fmt.Sprintf("/v1alpha/properties") params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) @@ -5328,6 +5352,11 @@ func (c *analyticsAdminRESTClient) CreateProperty(ctx context.Context, req *admi } baseUrl.Path += fmt.Sprintf("/v1alpha/properties") + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) opts = append((*c.CallOptions).CreateProperty[0:len((*c.CallOptions).CreateProperty):len((*c.CallOptions).CreateProperty)], opts...) @@ -5389,6 +5418,11 @@ func (c *analyticsAdminRESTClient) DeleteProperty(ctx context.Context, req *admi } baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -5450,6 +5484,7 @@ func (c *analyticsAdminRESTClient) UpdateProperty(ctx context.Context, req *admi baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetProperty().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -5513,6 +5548,11 @@ func (c *analyticsAdminRESTClient) GetUserLink(ctx context.Context, req *adminpb } baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -5567,8 +5607,11 @@ func (c *analyticsAdminRESTClient) BatchGetUserLinks(ctx context.Context, req *a baseUrl.Path += fmt.Sprintf("/v1alpha/%v/userLinks:batchGet", req.GetParent()) params := url.Values{} - if req.GetNames() != nil { - params.Add("names", fmt.Sprintf("%v", req.GetNames())) + params.Add("$alt", "json;enum-encoding=int") + if items := req.GetNames(); len(items) > 0 { + for _, item := range items { + params.Add("names", fmt.Sprintf("%v", item)) + } } baseUrl.RawQuery = params.Encode() @@ -5640,6 +5683,7 @@ func (c *analyticsAdminRESTClient) ListUserLinks(ctx context.Context, req *admin baseUrl.Path += fmt.Sprintf("/v1alpha/%v/userLinks", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -5740,6 +5784,11 @@ func (c *analyticsAdminRESTClient) AuditUserLinks(ctx context.Context, req *admi } baseUrl.Path += fmt.Sprintf("/v1alpha/%v/userLinks:audit", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { @@ -5816,6 +5865,7 @@ func (c *analyticsAdminRESTClient) CreateUserLink(ctx context.Context, req *admi baseUrl.Path += fmt.Sprintf("/v1alpha/%v/userLinks", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetNotifyNewUser() { params.Add("notifyNewUser", fmt.Sprintf("%v", req.GetNotifyNewUser())) } @@ -5884,6 +5934,11 @@ func (c *analyticsAdminRESTClient) BatchCreateUserLinks(ctx context.Context, req } baseUrl.Path += fmt.Sprintf("/v1alpha/%v/userLinks:batchCreate", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -5944,6 +5999,11 @@ func (c *analyticsAdminRESTClient) UpdateUserLink(ctx context.Context, req *admi } baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetUserLink().GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "user_link.name", url.QueryEscape(req.GetUserLink().GetName()))) @@ -6003,6 +6063,11 @@ func (c *analyticsAdminRESTClient) BatchUpdateUserLinks(ctx context.Context, req } baseUrl.Path += fmt.Sprintf("/v1alpha/%v/userLinks:batchUpdate", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -6056,6 +6121,11 @@ func (c *analyticsAdminRESTClient) DeleteUserLink(ctx context.Context, req *admi } baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -6097,6 +6167,11 @@ func (c *analyticsAdminRESTClient) BatchDeleteUserLinks(ctx context.Context, req } baseUrl.Path += fmt.Sprintf("/v1alpha/%v/userLinks:batchDelete", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -6141,6 +6216,11 @@ func (c *analyticsAdminRESTClient) CreateFirebaseLink(ctx context.Context, req * } baseUrl.Path += fmt.Sprintf("/v1alpha/%v/firebaseLinks", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -6194,6 +6274,11 @@ func (c *analyticsAdminRESTClient) DeleteFirebaseLink(ctx context.Context, req * } baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -6244,6 +6329,7 @@ func (c *analyticsAdminRESTClient) ListFirebaseLinks(ctx context.Context, req *a baseUrl.Path += fmt.Sprintf("/v1alpha/%v/firebaseLinks", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -6318,6 +6404,11 @@ func (c *analyticsAdminRESTClient) GetGlobalSiteTag(ctx context.Context, req *ad } baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -6378,6 +6469,11 @@ func (c *analyticsAdminRESTClient) CreateGoogleAdsLink(ctx context.Context, req } baseUrl.Path += fmt.Sprintf("/v1alpha/%v/googleAdsLinks", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -6439,6 +6535,7 @@ func (c *analyticsAdminRESTClient) UpdateGoogleAdsLink(ctx context.Context, req baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetGoogleAdsLink().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -6502,6 +6599,11 @@ func (c *analyticsAdminRESTClient) DeleteGoogleAdsLink(ctx context.Context, req } baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -6551,6 +6653,7 @@ func (c *analyticsAdminRESTClient) ListGoogleAdsLinks(ctx context.Context, req * baseUrl.Path += fmt.Sprintf("/v1alpha/%v/googleAdsLinks", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -6625,6 +6728,11 @@ func (c *analyticsAdminRESTClient) GetDataSharingSettings(ctx context.Context, r } baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -6678,6 +6786,11 @@ func (c *analyticsAdminRESTClient) GetMeasurementProtocolSecret(ctx context.Cont } baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -6746,6 +6859,7 @@ func (c *analyticsAdminRESTClient) ListMeasurementProtocolSecrets(ctx context.Co baseUrl.Path += fmt.Sprintf("/v1alpha/%v/measurementProtocolSecrets", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -6826,6 +6940,11 @@ func (c *analyticsAdminRESTClient) CreateMeasurementProtocolSecret(ctx context.C } baseUrl.Path += fmt.Sprintf("/v1alpha/%v/measurementProtocolSecrets", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -6879,6 +6998,11 @@ func (c *analyticsAdminRESTClient) DeleteMeasurementProtocolSecret(ctx context.C } baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -6922,6 +7046,7 @@ func (c *analyticsAdminRESTClient) UpdateMeasurementProtocolSecret(ctx context.C baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetMeasurementProtocolSecret().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -6994,6 +7119,11 @@ func (c *analyticsAdminRESTClient) AcknowledgeUserDataCollection(ctx context.Con } baseUrl.Path += fmt.Sprintf("/v1alpha/%v:acknowledgeUserDataCollection", req.GetProperty()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "property", url.QueryEscape(req.GetProperty()))) @@ -7067,6 +7197,11 @@ func (c *analyticsAdminRESTClient) SearchChangeHistoryEvents(ctx context.Context } baseUrl.Path += fmt.Sprintf("/v1alpha/%v:searchChangeHistoryEvents", req.GetAccount()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { @@ -7131,6 +7266,11 @@ func (c *analyticsAdminRESTClient) GetGoogleSignalsSettings(ctx context.Context, } baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -7192,6 +7332,7 @@ func (c *analyticsAdminRESTClient) UpdateGoogleSignalsSettings(ctx context.Conte baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetGoogleSignalsSettings().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -7262,6 +7403,11 @@ func (c *analyticsAdminRESTClient) CreateConversionEvent(ctx context.Context, re } baseUrl.Path += fmt.Sprintf("/v1alpha/%v/conversionEvents", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -7315,6 +7461,11 @@ func (c *analyticsAdminRESTClient) GetConversionEvent(ctx context.Context, req * } baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -7368,6 +7519,11 @@ func (c *analyticsAdminRESTClient) DeleteConversionEvent(ctx context.Context, re } baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -7419,6 +7575,7 @@ func (c *analyticsAdminRESTClient) ListConversionEvents(ctx context.Context, req baseUrl.Path += fmt.Sprintf("/v1alpha/%v/conversionEvents", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -7492,6 +7649,11 @@ func (c *analyticsAdminRESTClient) GetDisplayVideo360AdvertiserLink(ctx context. } baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -7559,6 +7721,7 @@ func (c *analyticsAdminRESTClient) ListDisplayVideo360AdvertiserLinks(ctx contex baseUrl.Path += fmt.Sprintf("/v1alpha/%v/displayVideo360AdvertiserLinks", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -7643,6 +7806,11 @@ func (c *analyticsAdminRESTClient) CreateDisplayVideo360AdvertiserLink(ctx conte } baseUrl.Path += fmt.Sprintf("/v1alpha/%v/displayVideo360AdvertiserLinks", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -7696,6 +7864,11 @@ func (c *analyticsAdminRESTClient) DeleteDisplayVideo360AdvertiserLink(ctx conte } baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -7739,6 +7912,7 @@ func (c *analyticsAdminRESTClient) UpdateDisplayVideo360AdvertiserLink(ctx conte baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetDisplayVideo_360AdvertiserLink().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -7802,6 +7976,11 @@ func (c *analyticsAdminRESTClient) GetDisplayVideo360AdvertiserLinkProposal(ctx } baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -7869,6 +8048,7 @@ func (c *analyticsAdminRESTClient) ListDisplayVideo360AdvertiserLinkProposals(ct baseUrl.Path += fmt.Sprintf("/v1alpha/%v/displayVideo360AdvertiserLinkProposals", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -7949,6 +8129,11 @@ func (c *analyticsAdminRESTClient) CreateDisplayVideo360AdvertiserLinkProposal(c } baseUrl.Path += fmt.Sprintf("/v1alpha/%v/displayVideo360AdvertiserLinkProposals", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -8003,6 +8188,11 @@ func (c *analyticsAdminRESTClient) DeleteDisplayVideo360AdvertiserLinkProposal(c } baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -8046,6 +8236,11 @@ func (c *analyticsAdminRESTClient) ApproveDisplayVideo360AdvertiserLinkProposal( } baseUrl.Path += fmt.Sprintf("/v1alpha/%v:approve", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -8111,6 +8306,11 @@ func (c *analyticsAdminRESTClient) CancelDisplayVideo360AdvertiserLinkProposal(c } baseUrl.Path += fmt.Sprintf("/v1alpha/%v:cancel", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -8171,6 +8371,11 @@ func (c *analyticsAdminRESTClient) CreateCustomDimension(ctx context.Context, re } baseUrl.Path += fmt.Sprintf("/v1alpha/%v/customDimensions", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -8232,6 +8437,7 @@ func (c *analyticsAdminRESTClient) UpdateCustomDimension(ctx context.Context, re baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetCustomDimension().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -8309,6 +8515,7 @@ func (c *analyticsAdminRESTClient) ListCustomDimensions(ctx context.Context, req baseUrl.Path += fmt.Sprintf("/v1alpha/%v/customDimensions", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -8388,6 +8595,11 @@ func (c *analyticsAdminRESTClient) ArchiveCustomDimension(ctx context.Context, r } baseUrl.Path += fmt.Sprintf("/v1alpha/%v:archive", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -8423,6 +8635,11 @@ func (c *analyticsAdminRESTClient) GetCustomDimension(ctx context.Context, req * } baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -8483,6 +8700,11 @@ func (c *analyticsAdminRESTClient) CreateCustomMetric(ctx context.Context, req * } baseUrl.Path += fmt.Sprintf("/v1alpha/%v/customMetrics", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -8544,6 +8766,7 @@ func (c *analyticsAdminRESTClient) UpdateCustomMetric(ctx context.Context, req * baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetCustomMetric().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -8621,6 +8844,7 @@ func (c *analyticsAdminRESTClient) ListCustomMetrics(ctx context.Context, req *a baseUrl.Path += fmt.Sprintf("/v1alpha/%v/customMetrics", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -8700,6 +8924,11 @@ func (c *analyticsAdminRESTClient) ArchiveCustomMetric(ctx context.Context, req } baseUrl.Path += fmt.Sprintf("/v1alpha/%v:archive", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -8735,6 +8964,11 @@ func (c *analyticsAdminRESTClient) GetCustomMetric(ctx context.Context, req *adm } baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -8788,6 +9022,11 @@ func (c *analyticsAdminRESTClient) GetDataRetentionSettings(ctx context.Context, } baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -8849,6 +9088,7 @@ func (c *analyticsAdminRESTClient) UpdateDataRetentionSettings(ctx context.Conte baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetDataRetentionSettings().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -8919,6 +9159,11 @@ func (c *analyticsAdminRESTClient) CreateDataStream(ctx context.Context, req *ad } baseUrl.Path += fmt.Sprintf("/v1alpha/%v/dataStreams", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -8972,6 +9217,11 @@ func (c *analyticsAdminRESTClient) DeleteDataStream(ctx context.Context, req *ad } baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -9015,6 +9265,7 @@ func (c *analyticsAdminRESTClient) UpdateDataStream(ctx context.Context, req *ad baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetDataStream().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -9092,6 +9343,7 @@ func (c *analyticsAdminRESTClient) ListDataStreams(ctx context.Context, req *adm baseUrl.Path += fmt.Sprintf("/v1alpha/%v/dataStreams", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -9165,6 +9417,11 @@ func (c *analyticsAdminRESTClient) GetDataStream(ctx context.Context, req *admin } baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -9219,6 +9476,11 @@ func (c *analyticsAdminRESTClient) GetAudience(ctx context.Context, req *adminpb } baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -9287,6 +9549,7 @@ func (c *analyticsAdminRESTClient) ListAudiences(ctx context.Context, req *admin baseUrl.Path += fmt.Sprintf("/v1alpha/%v/audiences", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -9367,6 +9630,11 @@ func (c *analyticsAdminRESTClient) CreateAudience(ctx context.Context, req *admi } baseUrl.Path += fmt.Sprintf("/v1alpha/%v/audiences", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -9428,6 +9696,7 @@ func (c *analyticsAdminRESTClient) UpdateAudience(ctx context.Context, req *admi baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetAudience().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -9497,6 +9766,11 @@ func (c *analyticsAdminRESTClient) ArchiveAudience(ctx context.Context, req *adm } baseUrl.Path += fmt.Sprintf("/v1alpha/%v:archive", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -9532,6 +9806,11 @@ func (c *analyticsAdminRESTClient) GetAttributionSettings(ctx context.Context, r } baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -9593,6 +9872,7 @@ func (c *analyticsAdminRESTClient) UpdateAttributionSettings(ctx context.Context baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetAttributionSettings().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -9674,6 +9954,11 @@ func (c *analyticsAdminRESTClient) RunAccessReport(ctx context.Context, req *adm } baseUrl.Path += fmt.Sprintf("/v1alpha/%v:runAccessReport", req.GetEntity()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "entity", url.QueryEscape(req.GetEntity()))) diff --git a/apigateway/apiv1/api_gateway_client.go b/apigateway/apiv1/api_gateway_client.go index 7d6826e48190..019b77feec92 100644 --- a/apigateway/apiv1/api_gateway_client.go +++ b/apigateway/apiv1/api_gateway_client.go @@ -17,9 +17,12 @@ package apigateway import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,14 +30,17 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -190,6 +196,116 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + ListGateways: []gax.CallOption{}, + GetGateway: []gax.CallOption{}, + CreateGateway: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 2.00, + }, + http.StatusInternalServerError, + http.StatusServiceUnavailable) + }), + }, + UpdateGateway: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 2.00, + }, + http.StatusInternalServerError, + http.StatusServiceUnavailable) + }), + }, + DeleteGateway: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 2.00, + }, + http.StatusInternalServerError, + http.StatusServiceUnavailable) + }), + }, + ListApis: []gax.CallOption{}, + GetApi: []gax.CallOption{}, + CreateApi: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 2.00, + }, + http.StatusInternalServerError, + http.StatusServiceUnavailable) + }), + }, + UpdateApi: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 2.00, + }, + http.StatusInternalServerError, + http.StatusServiceUnavailable) + }), + }, + DeleteApi: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 2.00, + }, + http.StatusInternalServerError, + http.StatusServiceUnavailable) + }), + }, + ListApiConfigs: []gax.CallOption{}, + GetApiConfig: []gax.CallOption{}, + CreateApiConfig: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 2.00, + }, + http.StatusInternalServerError, + http.StatusServiceUnavailable) + }), + }, + UpdateApiConfig: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 2.00, + }, + http.StatusInternalServerError, + http.StatusServiceUnavailable) + }), + }, + DeleteApiConfig: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 2.00, + }, + http.StatusInternalServerError, + http.StatusServiceUnavailable) + }), + }, + } +} + // internalClient is an interface that defines the methods available from API Gateway API. type internalClient interface { Close() error @@ -487,6 +603,89 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new api gateway service rest client. +// +// The API Gateway Service is the interface for managing API Gateways. +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://apigateway.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://apigateway.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://apigateway.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) ListGateways(ctx context.Context, req *apigatewaypb.ListGatewaysRequest, opts ...gax.CallOption) *GatewayIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -889,92 +1088,1200 @@ func (c *gRPCClient) DeleteApiConfig(ctx context.Context, req *apigatewaypb.Dele }, nil } -// CreateApiOperation manages a long-running operation from CreateApi. -type CreateApiOperation struct { - lro *longrunning.Operation -} +// ListGateways lists Gateways in a given project and location. +func (c *restClient) ListGateways(ctx context.Context, req *apigatewaypb.ListGatewaysRequest, opts ...gax.CallOption) *GatewayIterator { + it := &GatewayIterator{} + req = proto.Clone(req).(*apigatewaypb.ListGatewaysRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*apigatewaypb.Gateway, string, error) { + resp := &apigatewaypb.ListGatewaysResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/gateways", req.GetParent()) -// CreateApiOperation returns a new CreateApiOperation from a given name. -// The name must be that of a previously created CreateApiOperation, possibly from a different process. -func (c *gRPCClient) CreateApiOperation(name string) *CreateApiOperation { - return &CreateApiOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetGateways(), resp.GetNextPageToken(), nil } -} -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *CreateApiOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*apigatewaypb.Api, error) { - var resp apigatewaypb.Api - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { - return nil, err + 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 } - return &resp, nil + + it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it } -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *CreateApiOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*apigatewaypb.Api, error) { - var resp apigatewaypb.Api - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { +// GetGateway gets details of a single Gateway. +func (c *restClient) GetGateway(ctx context.Context, req *apigatewaypb.GetGatewayRequest, opts ...gax.CallOption) (*apigatewaypb.Gateway, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - if !op.Done() { - return nil, nil + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetGateway[0:len((*c.CallOptions).GetGateway):len((*c.CallOptions).GetGateway)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &apigatewaypb.Gateway{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e } - return &resp, nil + return resp, nil } -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *CreateApiOperation) Metadata() (*apigatewaypb.OperationMetadata, error) { - var meta apigatewaypb.OperationMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { +// CreateGateway creates a new Gateway in a given project and location. +func (c *restClient) CreateGateway(ctx context.Context, req *apigatewaypb.CreateGatewayRequest, opts ...gax.CallOption) (*CreateGatewayOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetGateway() + jsonReq, err := m.Marshal(body) + if err != nil { return nil, err } - return &meta, nil -} -// Done reports whether the long-running operation has completed. -func (op *CreateApiOperation) Done() bool { - return op.lro.Done() -} + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/gateways", req.GetParent()) -// 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 *CreateApiOperation) Name() string { - return op.lro.Name() -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("gatewayId", fmt.Sprintf("%v", req.GetGatewayId())) -// CreateApiConfigOperation manages a long-running operation from CreateApiConfig. -type CreateApiConfigOperation struct { - lro *longrunning.Operation -} + baseUrl.RawQuery = params.Encode() -// CreateApiConfigOperation returns a new CreateApiConfigOperation from a given name. -// The name must be that of a previously created CreateApiConfigOperation, possibly from a different process. -func (c *gRPCClient) CreateApiConfigOperation(name string) *CreateApiConfigOperation { - return &CreateApiConfigOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateGatewayOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateGateway updates the parameters of a single Gateway. +func (c *restClient) UpdateGateway(ctx context.Context, req *apigatewaypb.UpdateGatewayRequest, opts ...gax.CallOption) (*UpdateGatewayOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetGateway() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetGateway().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "gateway.name", url.QueryEscape(req.GetGateway().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateGatewayOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteGateway deletes a single Gateway. +func (c *restClient) DeleteGateway(ctx context.Context, req *apigatewaypb.DeleteGatewayRequest, opts ...gax.CallOption) (*DeleteGatewayOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteGatewayOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListApis lists Apis in a given project and location. +func (c *restClient) ListApis(ctx context.Context, req *apigatewaypb.ListApisRequest, opts ...gax.CallOption) *ApiIterator { + it := &ApiIterator{} + req = proto.Clone(req).(*apigatewaypb.ListApisRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*apigatewaypb.Api, string, error) { + resp := &apigatewaypb.ListApisResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/apis", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetApis(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetApi gets details of a single Api. +func (c *restClient) GetApi(ctx context.Context, req *apigatewaypb.GetApiRequest, opts ...gax.CallOption) (*apigatewaypb.Api, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetApi[0:len((*c.CallOptions).GetApi):len((*c.CallOptions).GetApi)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &apigatewaypb.Api{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateApi creates a new Api in a given project and location. +func (c *restClient) CreateApi(ctx context.Context, req *apigatewaypb.CreateApiRequest, opts ...gax.CallOption) (*CreateApiOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetApi() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/apis", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("apiId", fmt.Sprintf("%v", req.GetApiId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateApiOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateApi updates the parameters of a single Api. +func (c *restClient) UpdateApi(ctx context.Context, req *apigatewaypb.UpdateApiRequest, opts ...gax.CallOption) (*UpdateApiOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetApi() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetApi().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "api.name", url.QueryEscape(req.GetApi().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateApiOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteApi deletes a single Api. +func (c *restClient) DeleteApi(ctx context.Context, req *apigatewaypb.DeleteApiRequest, opts ...gax.CallOption) (*DeleteApiOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteApiOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListApiConfigs lists ApiConfigs in a given project and location. +func (c *restClient) ListApiConfigs(ctx context.Context, req *apigatewaypb.ListApiConfigsRequest, opts ...gax.CallOption) *ApiConfigIterator { + it := &ApiConfigIterator{} + req = proto.Clone(req).(*apigatewaypb.ListApiConfigsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*apigatewaypb.ApiConfig, string, error) { + resp := &apigatewaypb.ListApiConfigsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/configs", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetApiConfigs(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetApiConfig gets details of a single ApiConfig. +func (c *restClient) GetApiConfig(ctx context.Context, req *apigatewaypb.GetApiConfigRequest, opts ...gax.CallOption) (*apigatewaypb.ApiConfig, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetView() != 0 { + params.Add("view", fmt.Sprintf("%v", req.GetView())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetApiConfig[0:len((*c.CallOptions).GetApiConfig):len((*c.CallOptions).GetApiConfig)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &apigatewaypb.ApiConfig{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateApiConfig creates a new ApiConfig in a given project and location. +func (c *restClient) CreateApiConfig(ctx context.Context, req *apigatewaypb.CreateApiConfigRequest, opts ...gax.CallOption) (*CreateApiConfigOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetApiConfig() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/configs", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("apiConfigId", fmt.Sprintf("%v", req.GetApiConfigId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateApiConfigOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateApiConfig updates the parameters of a single ApiConfig. +func (c *restClient) UpdateApiConfig(ctx context.Context, req *apigatewaypb.UpdateApiConfigRequest, opts ...gax.CallOption) (*UpdateApiConfigOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetApiConfig() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetApiConfig().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "api_config.name", url.QueryEscape(req.GetApiConfig().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateApiConfigOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteApiConfig deletes a single ApiConfig. +func (c *restClient) DeleteApiConfig(ctx context.Context, req *apigatewaypb.DeleteApiConfigRequest, opts ...gax.CallOption) (*DeleteApiConfigOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteApiConfigOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// CreateApiOperation manages a long-running operation from CreateApi. +type CreateApiOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateApiOperation returns a new CreateApiOperation from a given name. +// The name must be that of a previously created CreateApiOperation, possibly from a different process. +func (c *gRPCClient) CreateApiOperation(name string) *CreateApiOperation { + return &CreateApiOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateApiOperation returns a new CreateApiOperation from a given name. +// The name must be that of a previously created CreateApiOperation, possibly from a different process. +func (c *restClient) CreateApiOperation(name string) *CreateApiOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateApiOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CreateApiOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*apigatewaypb.Api, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp apigatewaypb.Api + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *CreateApiOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*apigatewaypb.Api, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp apigatewaypb.Api + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *CreateApiOperation) Metadata() (*apigatewaypb.OperationMetadata, error) { + var meta apigatewaypb.OperationMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *CreateApiOperation) Done() bool { + return op.lro.Done() +} + +// 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 *CreateApiOperation) Name() string { + return op.lro.Name() +} + +// CreateApiConfigOperation manages a long-running operation from CreateApiConfig. +type CreateApiConfigOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateApiConfigOperation returns a new CreateApiConfigOperation from a given name. +// The name must be that of a previously created CreateApiConfigOperation, possibly from a different process. +func (c *gRPCClient) CreateApiConfigOperation(name string) *CreateApiConfigOperation { + return &CreateApiConfigOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateApiConfigOperation returns a new CreateApiConfigOperation from a given name. +// The name must be that of a previously created CreateApiConfigOperation, possibly from a different process. +func (c *restClient) CreateApiConfigOperation(name string) *CreateApiConfigOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateApiConfigOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } } // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateApiConfigOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*apigatewaypb.ApiConfig, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp apigatewaypb.ApiConfig if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -992,6 +2299,7 @@ func (op *CreateApiConfigOperation) Wait(ctx context.Context, opts ...gax.CallOp // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateApiConfigOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*apigatewaypb.ApiConfig, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp apigatewaypb.ApiConfig if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1029,7 +2337,8 @@ func (op *CreateApiConfigOperation) Name() string { // CreateGatewayOperation manages a long-running operation from CreateGateway. type CreateGatewayOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateGatewayOperation returns a new CreateGatewayOperation from a given name. @@ -1040,10 +2349,21 @@ func (c *gRPCClient) CreateGatewayOperation(name string) *CreateGatewayOperation } } +// CreateGatewayOperation returns a new CreateGatewayOperation from a given name. +// The name must be that of a previously created CreateGatewayOperation, possibly from a different process. +func (c *restClient) CreateGatewayOperation(name string) *CreateGatewayOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateGatewayOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateGatewayOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*apigatewaypb.Gateway, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp apigatewaypb.Gateway if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1061,6 +2381,7 @@ func (op *CreateGatewayOperation) Wait(ctx context.Context, opts ...gax.CallOpti // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateGatewayOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*apigatewaypb.Gateway, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp apigatewaypb.Gateway if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1098,7 +2419,8 @@ func (op *CreateGatewayOperation) Name() string { // DeleteApiOperation manages a long-running operation from DeleteApi. type DeleteApiOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteApiOperation returns a new DeleteApiOperation from a given name. @@ -1109,10 +2431,21 @@ func (c *gRPCClient) DeleteApiOperation(name string) *DeleteApiOperation { } } +// DeleteApiOperation returns a new DeleteApiOperation from a given name. +// The name must be that of a previously created DeleteApiOperation, possibly from a different process. +func (c *restClient) DeleteApiOperation(name string) *DeleteApiOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteApiOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteApiOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -1126,6 +2459,7 @@ func (op *DeleteApiOperation) Wait(ctx context.Context, opts ...gax.CallOption) // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteApiOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -1156,7 +2490,8 @@ func (op *DeleteApiOperation) Name() string { // DeleteApiConfigOperation manages a long-running operation from DeleteApiConfig. type DeleteApiConfigOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteApiConfigOperation returns a new DeleteApiConfigOperation from a given name. @@ -1167,10 +2502,21 @@ func (c *gRPCClient) DeleteApiConfigOperation(name string) *DeleteApiConfigOpera } } +// DeleteApiConfigOperation returns a new DeleteApiConfigOperation from a given name. +// The name must be that of a previously created DeleteApiConfigOperation, possibly from a different process. +func (c *restClient) DeleteApiConfigOperation(name string) *DeleteApiConfigOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteApiConfigOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteApiConfigOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -1184,6 +2530,7 @@ func (op *DeleteApiConfigOperation) Wait(ctx context.Context, opts ...gax.CallOp // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteApiConfigOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -1214,7 +2561,8 @@ func (op *DeleteApiConfigOperation) Name() string { // DeleteGatewayOperation manages a long-running operation from DeleteGateway. type DeleteGatewayOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteGatewayOperation returns a new DeleteGatewayOperation from a given name. @@ -1225,10 +2573,21 @@ func (c *gRPCClient) DeleteGatewayOperation(name string) *DeleteGatewayOperation } } +// DeleteGatewayOperation returns a new DeleteGatewayOperation from a given name. +// The name must be that of a previously created DeleteGatewayOperation, possibly from a different process. +func (c *restClient) DeleteGatewayOperation(name string) *DeleteGatewayOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteGatewayOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteGatewayOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -1242,6 +2601,7 @@ func (op *DeleteGatewayOperation) Wait(ctx context.Context, opts ...gax.CallOpti // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteGatewayOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -1272,7 +2632,8 @@ func (op *DeleteGatewayOperation) Name() string { // UpdateApiOperation manages a long-running operation from UpdateApi. type UpdateApiOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateApiOperation returns a new UpdateApiOperation from a given name. @@ -1283,10 +2644,21 @@ func (c *gRPCClient) UpdateApiOperation(name string) *UpdateApiOperation { } } +// UpdateApiOperation returns a new UpdateApiOperation from a given name. +// The name must be that of a previously created UpdateApiOperation, possibly from a different process. +func (c *restClient) UpdateApiOperation(name string) *UpdateApiOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateApiOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateApiOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*apigatewaypb.Api, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp apigatewaypb.Api if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1304,6 +2676,7 @@ func (op *UpdateApiOperation) Wait(ctx context.Context, opts ...gax.CallOption) // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateApiOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*apigatewaypb.Api, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp apigatewaypb.Api if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1341,7 +2714,8 @@ func (op *UpdateApiOperation) Name() string { // UpdateApiConfigOperation manages a long-running operation from UpdateApiConfig. type UpdateApiConfigOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateApiConfigOperation returns a new UpdateApiConfigOperation from a given name. @@ -1352,10 +2726,21 @@ func (c *gRPCClient) UpdateApiConfigOperation(name string) *UpdateApiConfigOpera } } +// UpdateApiConfigOperation returns a new UpdateApiConfigOperation from a given name. +// The name must be that of a previously created UpdateApiConfigOperation, possibly from a different process. +func (c *restClient) UpdateApiConfigOperation(name string) *UpdateApiConfigOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateApiConfigOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateApiConfigOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*apigatewaypb.ApiConfig, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp apigatewaypb.ApiConfig if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1373,6 +2758,7 @@ func (op *UpdateApiConfigOperation) Wait(ctx context.Context, opts ...gax.CallOp // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateApiConfigOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*apigatewaypb.ApiConfig, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp apigatewaypb.ApiConfig if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1410,7 +2796,8 @@ func (op *UpdateApiConfigOperation) Name() string { // UpdateGatewayOperation manages a long-running operation from UpdateGateway. type UpdateGatewayOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateGatewayOperation returns a new UpdateGatewayOperation from a given name. @@ -1421,10 +2808,21 @@ func (c *gRPCClient) UpdateGatewayOperation(name string) *UpdateGatewayOperation } } +// UpdateGatewayOperation returns a new UpdateGatewayOperation from a given name. +// The name must be that of a previously created UpdateGatewayOperation, possibly from a different process. +func (c *restClient) UpdateGatewayOperation(name string) *UpdateGatewayOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateGatewayOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateGatewayOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*apigatewaypb.Gateway, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp apigatewaypb.Gateway if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1442,6 +2840,7 @@ func (op *UpdateGatewayOperation) Wait(ctx context.Context, opts ...gax.CallOpti // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateGatewayOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*apigatewaypb.Gateway, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp apigatewaypb.Gateway if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/apigateway/apiv1/api_gateway_client_example_test.go b/apigateway/apiv1/api_gateway_client_example_test.go index fbbab8eccd59..4cd690ff7616 100644 --- a/apigateway/apiv1/api_gateway_client_example_test.go +++ b/apigateway/apiv1/api_gateway_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := apigateway.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_ListGateways() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/apigateway/apiv1/apigatewaypb/apigateway.pb.go b/apigateway/apiv1/apigatewaypb/apigateway.pb.go index db3898997005..796e9dbbd800 100644 --- a/apigateway/apiv1/apigatewaypb/apigateway.pb.go +++ b/apigateway/apiv1/apigatewaypb/apigateway.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/apigateway/v1/apigateway.proto package apigatewaypb diff --git a/apigateway/apiv1/apigatewaypb/apigateway_service.pb.go b/apigateway/apiv1/apigatewaypb/apigateway_service.pb.go index ca49e9a1ce0d..4e8b2914aba4 100644 --- a/apigateway/apiv1/apigatewaypb/apigateway_service.pb.go +++ b/apigateway/apiv1/apigatewaypb/apigateway_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/apigateway/v1/apigateway_service.proto package apigatewaypb diff --git a/apigateway/apiv1/doc.go b/apigateway/apiv1/doc.go index 5a85210984af..4888701e918f 100644 --- a/apigateway/apiv1/doc.go +++ b/apigateway/apiv1/doc.go @@ -84,6 +84,8 @@ package apigateway // import "cloud.google.com/go/apigateway/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -172,3 +174,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/apigateway/apiv1/gapic_metadata.json b/apigateway/apiv1/gapic_metadata.json index 80e7cec7f006..ae47a429673f 100644 --- a/apigateway/apiv1/gapic_metadata.json +++ b/apigateway/apiv1/gapic_metadata.json @@ -86,6 +86,86 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "CreateApi": { + "methods": [ + "CreateApi" + ] + }, + "CreateApiConfig": { + "methods": [ + "CreateApiConfig" + ] + }, + "CreateGateway": { + "methods": [ + "CreateGateway" + ] + }, + "DeleteApi": { + "methods": [ + "DeleteApi" + ] + }, + "DeleteApiConfig": { + "methods": [ + "DeleteApiConfig" + ] + }, + "DeleteGateway": { + "methods": [ + "DeleteGateway" + ] + }, + "GetApi": { + "methods": [ + "GetApi" + ] + }, + "GetApiConfig": { + "methods": [ + "GetApiConfig" + ] + }, + "GetGateway": { + "methods": [ + "GetGateway" + ] + }, + "ListApiConfigs": { + "methods": [ + "ListApiConfigs" + ] + }, + "ListApis": { + "methods": [ + "ListApis" + ] + }, + "ListGateways": { + "methods": [ + "ListGateways" + ] + }, + "UpdateApi": { + "methods": [ + "UpdateApi" + ] + }, + "UpdateApiConfig": { + "methods": [ + "UpdateApiConfig" + ] + }, + "UpdateGateway": { + "methods": [ + "UpdateGateway" + ] + } + } } } } diff --git a/apigeeconnect/apiv1/apigeeconnectpb/connection.pb.go b/apigeeconnect/apiv1/apigeeconnectpb/connection.pb.go index 0374c4423b01..48f935af1c4a 100644 --- a/apigeeconnect/apiv1/apigeeconnectpb/connection.pb.go +++ b/apigeeconnect/apiv1/apigeeconnectpb/connection.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/apigeeconnect/v1/connection.proto package apigeeconnectpb @@ -47,8 +47,7 @@ type ListConnectionsRequest struct { unknownFields protoimpl.UnknownFields // Required. Parent name of the form: - // - // `projects/{project_number or project_id}/endpoints/{endpoint}`. + // `projects/{project_number or project_id}/endpoints/{endpoint}`. Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // The maximum number of connections to return. The service may return fewer // than this value. If unspecified, at most 100 connections will be returned. diff --git a/apigeeconnect/apiv1/apigeeconnectpb/tether.pb.go b/apigeeconnect/apiv1/apigeeconnectpb/tether.pb.go index 861bee81bdd3..b0fbc7726447 100644 --- a/apigeeconnect/apiv1/apigeeconnectpb/tether.pb.go +++ b/apigeeconnect/apiv1/apigeeconnectpb/tether.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/apigeeconnect/v1/tether.proto package apigeeconnectpb @@ -301,7 +301,6 @@ type Payload struct { // The kind of payload. // // Types that are assignable to Kind: - // // *Payload_HttpRequest // *Payload_StreamInfo // *Payload_Action diff --git a/apigeeconnect/apiv1/connection_client.go b/apigeeconnect/apiv1/connection_client.go index 5726b4601544..8003d8daa604 100644 --- a/apigeeconnect/apiv1/connection_client.go +++ b/apigeeconnect/apiv1/connection_client.go @@ -19,19 +19,24 @@ package apigeeconnect import ( "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" apigeeconnectpb "cloud.google.com/go/apigeeconnect/apiv1/apigeeconnectpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -71,6 +76,22 @@ func defaultConnectionCallOptions() *ConnectionCallOptions { } } +func defaultConnectionRESTCallOptions() *ConnectionCallOptions { + return &ConnectionCallOptions{ + ListConnections: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusInternalServerError) + }), + }, + } +} + // internalConnectionClient is an interface that defines the methods available from Apigee Connect API. type internalConnectionClient interface { Close() error @@ -201,6 +222,74 @@ func (c *connectionGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type connectionRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing ConnectionClient + CallOptions **ConnectionCallOptions +} + +// NewConnectionRESTClient creates a new connection service rest client. +// +// Service Interface for the Apigee Connect connection management APIs. +func NewConnectionRESTClient(ctx context.Context, opts ...option.ClientOption) (*ConnectionClient, error) { + clientOpts := append(defaultConnectionRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultConnectionRESTCallOptions() + c := &connectionRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &ConnectionClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultConnectionRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://apigeeconnect.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://apigeeconnect.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://apigeeconnect.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *connectionRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *connectionRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *connectionRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *connectionGRPCClient) ListConnections(ctx context.Context, req *apigeeconnectpb.ListConnectionsRequest, opts ...gax.CallOption) *ConnectionIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -246,6 +335,95 @@ func (c *connectionGRPCClient) ListConnections(ctx context.Context, req *apigeec return it } +// ListConnections lists connections that are currently active for the given Apigee Connect +// endpoint. +func (c *connectionRESTClient) ListConnections(ctx context.Context, req *apigeeconnectpb.ListConnectionsRequest, opts ...gax.CallOption) *ConnectionIterator { + it := &ConnectionIterator{} + req = proto.Clone(req).(*apigeeconnectpb.ListConnectionsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*apigeeconnectpb.Connection, string, error) { + resp := &apigeeconnectpb.ListConnectionsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/connections", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetConnections(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + // ConnectionIterator manages a stream of *apigeeconnectpb.Connection. type ConnectionIterator struct { items []*apigeeconnectpb.Connection diff --git a/apigeeconnect/apiv1/connection_client_example_test.go b/apigeeconnect/apiv1/connection_client_example_test.go index 6d090333e8b4..2c3a59eda19d 100644 --- a/apigeeconnect/apiv1/connection_client_example_test.go +++ b/apigeeconnect/apiv1/connection_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewConnectionClient() { _ = c } +func ExampleNewConnectionRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := apigeeconnect.NewConnectionRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleConnectionClient_ListConnections() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/apigeeconnect/apiv1/doc.go b/apigeeconnect/apiv1/doc.go index 2a50dccc8575..3c7fc3be0127 100644 --- a/apigeeconnect/apiv1/doc.go +++ b/apigeeconnect/apiv1/doc.go @@ -84,6 +84,8 @@ package apigeeconnect // import "cloud.google.com/go/apigeeconnect/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -172,3 +174,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/apigeeconnect/apiv1/gapic_metadata.json b/apigeeconnect/apiv1/gapic_metadata.json index 9840b14ee63e..6d18198601df 100644 --- a/apigeeconnect/apiv1/gapic_metadata.json +++ b/apigeeconnect/apiv1/gapic_metadata.json @@ -16,6 +16,16 @@ ] } } + }, + "rest": { + "libraryClient": "ConnectionClient", + "rpcs": { + "ListConnections": { + "methods": [ + "ListConnections" + ] + } + } } } }, @@ -30,6 +40,16 @@ ] } } + }, + "rest": { + "libraryClient": "TetherClient", + "rpcs": { + "Egress": { + "methods": [ + "Egress" + ] + } + } } } } diff --git a/apigeeconnect/apiv1/tether_client.go b/apigeeconnect/apiv1/tether_client.go index 73ae3c366423..69597db4532f 100644 --- a/apigeeconnect/apiv1/tether_client.go +++ b/apigeeconnect/apiv1/tether_client.go @@ -18,13 +18,16 @@ package apigeeconnect import ( "context" + "fmt" "math" + "net/http" apigeeconnectpb "cloud.google.com/go/apigeeconnect/apiv1/apigeeconnectpb" gax "github.com/googleapis/gax-go/v2" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" "google.golang.org/grpc" "google.golang.org/grpc/metadata" ) @@ -54,6 +57,12 @@ func defaultTetherCallOptions() *TetherCallOptions { } } +func defaultTetherRESTCallOptions() *TetherCallOptions { + return &TetherCallOptions{ + Egress: []gax.CallOption{}, + } +} + // internalTetherClient is an interface that defines the methods available from Apigee Connect API. type internalTetherClient interface { Close() error @@ -106,6 +115,8 @@ func (c *TetherClient) Connection() *grpc.ClientConn { // The listener, the RPC server, accepts connections from the dialer, // the RPC client. // The listener streams http requests and the dialer streams http responses. +// +// This method is not supported for the REST transport. func (c *TetherClient) Egress(ctx context.Context, opts ...gax.CallOption) (apigeeconnectpb.Tether_EgressClient, error) { return c.internalClient.Egress(ctx, opts...) } @@ -193,6 +204,76 @@ func (c *tetherGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type tetherRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing TetherClient + CallOptions **TetherCallOptions +} + +// NewTetherRESTClient creates a new tether rest client. +// +// Tether provides a way for the control plane to send HTTP API requests to +// services in data planes that runs in a remote datacenter without +// requiring customers to open firewalls on their runtime plane. +func NewTetherRESTClient(ctx context.Context, opts ...option.ClientOption) (*TetherClient, error) { + clientOpts := append(defaultTetherRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultTetherRESTCallOptions() + c := &tetherRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &TetherClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultTetherRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://apigeeconnect.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://apigeeconnect.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://apigeeconnect.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *tetherRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *tetherRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *tetherRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *tetherGRPCClient) Egress(ctx context.Context, opts ...gax.CallOption) (apigeeconnectpb.Tether_EgressClient, error) { ctx = insertMetadata(ctx, c.xGoogMetadata) var resp apigeeconnectpb.Tether_EgressClient @@ -207,3 +288,16 @@ func (c *tetherGRPCClient) Egress(ctx context.Context, opts ...gax.CallOption) ( } return resp, nil } + +// Egress egress streams egress requests and responses. Logically, this is not +// actually a streaming request, but uses streaming as a mechanism to flip +// the client-server relationship of gRPC so that the server can act as a +// client. +// The listener, the RPC server, accepts connections from the dialer, +// the RPC client. +// The listener streams http requests and the dialer streams http responses. +// +// This method is not supported for the REST transport. +func (c *tetherRESTClient) Egress(ctx context.Context, opts ...gax.CallOption) (apigeeconnectpb.Tether_EgressClient, error) { + return nil, fmt.Errorf("Egress not yet supported for REST clients") +} diff --git a/apigeeconnect/apiv1/tether_client_example_test.go b/apigeeconnect/apiv1/tether_client_example_test.go index ead1726c046f..5b5b6fb98cf3 100644 --- a/apigeeconnect/apiv1/tether_client_example_test.go +++ b/apigeeconnect/apiv1/tether_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewTetherClient() { _ = c } +func ExampleNewTetherRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := apigeeconnect.NewTetherRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleTetherClient_Egress() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/apigeeregistry/apiv1/doc.go b/apigeeregistry/apiv1/doc.go index de5cb3edfee3..1d8df91eb572 100644 --- a/apigeeregistry/apiv1/doc.go +++ b/apigeeregistry/apiv1/doc.go @@ -85,6 +85,8 @@ package apigeeregistry // import "cloud.google.com/go/apigeeregistry/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -173,3 +175,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/apigeeregistry/apiv1/gapic_metadata.json b/apigeeregistry/apiv1/gapic_metadata.json index 6bad74acdc91..3dad421c53b6 100644 --- a/apigeeregistry/apiv1/gapic_metadata.json +++ b/apigeeregistry/apiv1/gapic_metadata.json @@ -71,6 +71,71 @@ ] } } + }, + "rest": { + "libraryClient": "ProvisioningClient", + "rpcs": { + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "CreateInstance": { + "methods": [ + "CreateInstance" + ] + }, + "DeleteInstance": { + "methods": [ + "DeleteInstance" + ] + }, + "DeleteOperation": { + "methods": [ + "DeleteOperation" + ] + }, + "GetIamPolicy": { + "methods": [ + "GetIamPolicy" + ] + }, + "GetInstance": { + "methods": [ + "GetInstance" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "SetIamPolicy": { + "methods": [ + "SetIamPolicy" + ] + }, + "TestIamPermissions": { + "methods": [ + "TestIamPermissions" + ] + } + } } } }, @@ -300,6 +365,231 @@ ] } } + }, + "rest": { + "libraryClient": "RegistryClient", + "rpcs": { + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "CreateApi": { + "methods": [ + "CreateApi" + ] + }, + "CreateApiDeployment": { + "methods": [ + "CreateApiDeployment" + ] + }, + "CreateApiSpec": { + "methods": [ + "CreateApiSpec" + ] + }, + "CreateApiVersion": { + "methods": [ + "CreateApiVersion" + ] + }, + "CreateArtifact": { + "methods": [ + "CreateArtifact" + ] + }, + "DeleteApi": { + "methods": [ + "DeleteApi" + ] + }, + "DeleteApiDeployment": { + "methods": [ + "DeleteApiDeployment" + ] + }, + "DeleteApiDeploymentRevision": { + "methods": [ + "DeleteApiDeploymentRevision" + ] + }, + "DeleteApiSpec": { + "methods": [ + "DeleteApiSpec" + ] + }, + "DeleteApiSpecRevision": { + "methods": [ + "DeleteApiSpecRevision" + ] + }, + "DeleteApiVersion": { + "methods": [ + "DeleteApiVersion" + ] + }, + "DeleteArtifact": { + "methods": [ + "DeleteArtifact" + ] + }, + "DeleteOperation": { + "methods": [ + "DeleteOperation" + ] + }, + "GetApi": { + "methods": [ + "GetApi" + ] + }, + "GetApiDeployment": { + "methods": [ + "GetApiDeployment" + ] + }, + "GetApiSpec": { + "methods": [ + "GetApiSpec" + ] + }, + "GetApiSpecContents": { + "methods": [ + "GetApiSpecContents" + ] + }, + "GetApiVersion": { + "methods": [ + "GetApiVersion" + ] + }, + "GetArtifact": { + "methods": [ + "GetArtifact" + ] + }, + "GetArtifactContents": { + "methods": [ + "GetArtifactContents" + ] + }, + "GetIamPolicy": { + "methods": [ + "GetIamPolicy" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ListApiDeploymentRevisions": { + "methods": [ + "ListApiDeploymentRevisions" + ] + }, + "ListApiDeployments": { + "methods": [ + "ListApiDeployments" + ] + }, + "ListApiSpecRevisions": { + "methods": [ + "ListApiSpecRevisions" + ] + }, + "ListApiSpecs": { + "methods": [ + "ListApiSpecs" + ] + }, + "ListApiVersions": { + "methods": [ + "ListApiVersions" + ] + }, + "ListApis": { + "methods": [ + "ListApis" + ] + }, + "ListArtifacts": { + "methods": [ + "ListArtifacts" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "ReplaceArtifact": { + "methods": [ + "ReplaceArtifact" + ] + }, + "RollbackApiDeployment": { + "methods": [ + "RollbackApiDeployment" + ] + }, + "RollbackApiSpec": { + "methods": [ + "RollbackApiSpec" + ] + }, + "SetIamPolicy": { + "methods": [ + "SetIamPolicy" + ] + }, + "TagApiDeploymentRevision": { + "methods": [ + "TagApiDeploymentRevision" + ] + }, + "TagApiSpecRevision": { + "methods": [ + "TagApiSpecRevision" + ] + }, + "TestIamPermissions": { + "methods": [ + "TestIamPermissions" + ] + }, + "UpdateApi": { + "methods": [ + "UpdateApi" + ] + }, + "UpdateApiDeployment": { + "methods": [ + "UpdateApiDeployment" + ] + }, + "UpdateApiSpec": { + "methods": [ + "UpdateApiSpec" + ] + }, + "UpdateApiVersion": { + "methods": [ + "UpdateApiVersion" + ] + } + } } } } diff --git a/apigeeregistry/apiv1/provisioning_client.go b/apigeeregistry/apiv1/provisioning_client.go index 63159a0e1f17..039e2e4a4507 100644 --- a/apigeeregistry/apiv1/provisioning_client.go +++ b/apigeeregistry/apiv1/provisioning_client.go @@ -17,25 +17,31 @@ package apigeeregistry import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" apigeeregistrypb "google.golang.org/genproto/googleapis/cloud/apigeeregistry/v1" locationpb "google.golang.org/genproto/googleapis/cloud/location" iampb "google.golang.org/genproto/googleapis/iam/v1" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -86,6 +92,23 @@ func defaultProvisioningCallOptions() *ProvisioningCallOptions { } } +func defaultProvisioningRESTCallOptions() *ProvisioningCallOptions { + return &ProvisioningCallOptions{ + CreateInstance: []gax.CallOption{}, + DeleteInstance: []gax.CallOption{}, + GetInstance: []gax.CallOption{}, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + GetIamPolicy: []gax.CallOption{}, + SetIamPolicy: []gax.CallOption{}, + TestIamPermissions: []gax.CallOption{}, + CancelOperation: []gax.CallOption{}, + DeleteOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalProvisioningClient is an interface that defines the methods available from Apigee Registry API. type internalProvisioningClient interface { Close() error @@ -338,6 +361,90 @@ func (c *provisioningGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type provisioningRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing ProvisioningClient + CallOptions **ProvisioningCallOptions +} + +// NewProvisioningRESTClient creates a new provisioning rest client. +// +// The service that is used for managing the data plane provisioning of the +// Registry. +func NewProvisioningRESTClient(ctx context.Context, opts ...option.ClientOption) (*ProvisioningClient, error) { + clientOpts := append(defaultProvisioningRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultProvisioningRESTCallOptions() + c := &provisioningRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &ProvisioningClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultProvisioningRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://apigeeregistry.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://apigeeregistry.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://apigeeregistry.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *provisioningRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *provisioningRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *provisioningRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *provisioningGRPCClient) CreateInstance(ctx context.Context, req *apigeeregistrypb.CreateInstanceRequest, opts ...gax.CallOption) (*CreateInstanceOperation, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -594,9 +701,784 @@ func (c *provisioningGRPCClient) ListOperations(ctx context.Context, req *longru return it } +// CreateInstance provisions instance resources for the Registry. +func (c *provisioningRESTClient) CreateInstance(ctx context.Context, req *apigeeregistrypb.CreateInstanceRequest, opts ...gax.CallOption) (*CreateInstanceOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetInstance() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/instances", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("instanceId", fmt.Sprintf("%v", req.GetInstanceId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteInstance deletes the Registry instance. +func (c *provisioningRESTClient) DeleteInstance(ctx context.Context, req *apigeeregistrypb.DeleteInstanceRequest, opts ...gax.CallOption) (*DeleteInstanceOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetInstance gets details of a single Instance. +func (c *provisioningRESTClient) GetInstance(ctx context.Context, req *apigeeregistrypb.GetInstanceRequest, opts ...gax.CallOption) (*apigeeregistrypb.Instance, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetInstance[0:len((*c.CallOptions).GetInstance):len((*c.CallOptions).GetInstance)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &apigeeregistrypb.Instance{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetLocation gets information about a location. +func (c *provisioningRESTClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *provisioningRESTClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetIamPolicy gets the access control policy for a resource. Returns an empty policy +// if the resource exists and does not have a policy set. +func (c *provisioningRESTClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:getIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetOptions().GetRequestedPolicyVersion() != 0 { + params.Add("options.requestedPolicyVersion", fmt.Sprintf("%v", req.GetOptions().GetRequestedPolicyVersion())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SetIamPolicy sets the access control policy on the specified resource. Replaces +// any existing policy. +// +// Can return NOT_FOUND, INVALID_ARGUMENT, and PERMISSION_DENIED +// errors. +func (c *provisioningRESTClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:setIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// TestIamPermissions returns permissions that a caller has on the specified resource. If the +// resource does not exist, this will return an empty set of +// permissions, not a NOT_FOUND error. +// +// Note: This operation is designed to be used for building +// permission-aware UIs and command-line tools, not for authorization +// checking. This operation may “fail open” without warning. +func (c *provisioningRESTClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:testIamPermissions", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.TestIamPermissionsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *provisioningRESTClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// DeleteOperation is a utility method from google.longrunning.Operations. +func (c *provisioningRESTClient) DeleteOperation(ctx context.Context, req *longrunningpb.DeleteOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *provisioningRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *provisioningRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + // CreateInstanceOperation manages a long-running operation from CreateInstance. type CreateInstanceOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateInstanceOperation returns a new CreateInstanceOperation from a given name. @@ -607,10 +1489,21 @@ func (c *provisioningGRPCClient) CreateInstanceOperation(name string) *CreateIns } } +// CreateInstanceOperation returns a new CreateInstanceOperation from a given name. +// The name must be that of a previously created CreateInstanceOperation, possibly from a different process. +func (c *provisioningRESTClient) CreateInstanceOperation(name string) *CreateInstanceOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*apigeeregistrypb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp apigeeregistrypb.Instance if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -628,6 +1521,7 @@ func (op *CreateInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOpt // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateInstanceOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*apigeeregistrypb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp apigeeregistrypb.Instance if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -665,7 +1559,8 @@ func (op *CreateInstanceOperation) Name() string { // DeleteInstanceOperation manages a long-running operation from DeleteInstance. type DeleteInstanceOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteInstanceOperation returns a new DeleteInstanceOperation from a given name. @@ -676,10 +1571,21 @@ func (c *provisioningGRPCClient) DeleteInstanceOperation(name string) *DeleteIns } } +// DeleteInstanceOperation returns a new DeleteInstanceOperation from a given name. +// The name must be that of a previously created DeleteInstanceOperation, possibly from a different process. +func (c *provisioningRESTClient) DeleteInstanceOperation(name string) *DeleteInstanceOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -693,6 +1599,7 @@ func (op *DeleteInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOpt // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteInstanceOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } diff --git a/apigeeregistry/apiv1/provisioning_client_example_test.go b/apigeeregistry/apiv1/provisioning_client_example_test.go index d2f94534293f..a07135c184f2 100644 --- a/apigeeregistry/apiv1/provisioning_client_example_test.go +++ b/apigeeregistry/apiv1/provisioning_client_example_test.go @@ -44,6 +44,23 @@ func ExampleNewProvisioningClient() { _ = c } +func ExampleNewProvisioningRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := apigeeregistry.NewProvisioningRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleProvisioningClient_CreateInstance() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/apigeeregistry/apiv1/registry_client.go b/apigeeregistry/apiv1/registry_client.go index 2b702151c6d3..db90f53f4952 100644 --- a/apigeeregistry/apiv1/registry_client.go +++ b/apigeeregistry/apiv1/registry_client.go @@ -17,17 +17,22 @@ package apigeeregistry import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" httpbodypb "google.golang.org/genproto/googleapis/api/httpbody" apigeeregistrypb "google.golang.org/genproto/googleapis/cloud/apigeeregistry/v1" locationpb "google.golang.org/genproto/googleapis/cloud/location" @@ -36,6 +41,7 @@ import ( "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -579,6 +585,451 @@ func defaultRegistryCallOptions() *RegistryCallOptions { } } +func defaultRegistryRESTCallOptions() *RegistryCallOptions { + return &RegistryCallOptions{ + ListApis: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 200 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusConflict, + 499, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + GetApi: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 200 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusConflict, + 499, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + CreateApi: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 200 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusConflict, + 499, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + UpdateApi: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 200 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusConflict, + 499, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + DeleteApi: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 200 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusConflict, + 499, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + ListApiVersions: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 200 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusConflict, + 499, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + GetApiVersion: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 200 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusConflict, + 499, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + CreateApiVersion: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 200 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusConflict, + 499, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + UpdateApiVersion: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 200 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusConflict, + 499, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + DeleteApiVersion: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 200 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusConflict, + 499, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + ListApiSpecs: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 200 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusConflict, + 499, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + GetApiSpec: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 200 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusConflict, + 499, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + GetApiSpecContents: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 200 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusConflict, + 499, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + CreateApiSpec: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 200 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusConflict, + 499, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + UpdateApiSpec: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 200 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusConflict, + 499, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + DeleteApiSpec: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 200 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusConflict, + 499, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + TagApiSpecRevision: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 200 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusConflict, + 499, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + ListApiSpecRevisions: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 200 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusConflict, + 499, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + RollbackApiSpec: []gax.CallOption{}, + DeleteApiSpecRevision: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 200 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusConflict, + 499, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + ListApiDeployments: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 200 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusConflict, + 499, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + GetApiDeployment: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 200 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusConflict, + 499, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + CreateApiDeployment: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 200 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusConflict, + 499, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + UpdateApiDeployment: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 200 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusConflict, + 499, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + DeleteApiDeployment: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 200 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusConflict, + 499, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + TagApiDeploymentRevision: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 200 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusConflict, + 499, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + ListApiDeploymentRevisions: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 200 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusConflict, + 499, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + RollbackApiDeployment: []gax.CallOption{}, + DeleteApiDeploymentRevision: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 200 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusConflict, + 499, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + ListArtifacts: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 200 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusConflict, + 499, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + GetArtifact: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 200 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusConflict, + 499, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + GetArtifactContents: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 200 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusConflict, + 499, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + CreateArtifact: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 200 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusConflict, + 499, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + ReplaceArtifact: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 200 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusConflict, + 499, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + DeleteArtifact: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 200 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusConflict, + 499, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + GetIamPolicy: []gax.CallOption{}, + SetIamPolicy: []gax.CallOption{}, + TestIamPermissions: []gax.CallOption{}, + CancelOperation: []gax.CallOption{}, + DeleteOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalRegistryClient is an interface that defines the methods available from Apigee Registry API. type internalRegistryClient interface { Close() error @@ -1001,16 +1452,84 @@ func (c *registryGRPCClient) Close() error { return c.connPool.Close() } -func (c *registryGRPCClient) ListApis(ctx context.Context, req *apigeeregistrypb.ListApisRequest, opts ...gax.CallOption) *ApiIterator { - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type registryRESTClient struct { + // The http endpoint to connect to. + endpoint string - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).ListApis[0:len((*c.CallOptions).ListApis):len((*c.CallOptions).ListApis)], opts...) - it := &ApiIterator{} - req = proto.Clone(req).(*apigeeregistrypb.ListApisRequest) - it.InternalFetch = func(pageSize int, pageToken string) ([]*apigeeregistrypb.Api, string, error) { - resp := &apigeeregistrypb.ListApisResponse{} - if pageToken != "" { + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing RegistryClient + CallOptions **RegistryCallOptions +} + +// NewRegistryRESTClient creates a new registry rest client. +// +// The Registry service allows teams to manage descriptions of APIs. +func NewRegistryRESTClient(ctx context.Context, opts ...option.ClientOption) (*RegistryClient, error) { + clientOpts := append(defaultRegistryRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRegistryRESTCallOptions() + c := ®istryRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &RegistryClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRegistryRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://apigeeregistry.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://apigeeregistry.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://apigeeregistry.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *registryRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *registryRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *registryRESTClient) Connection() *grpc.ClientConn { + return nil +} +func (c *registryGRPCClient) ListApis(ctx context.Context, req *apigeeregistrypb.ListApisRequest, opts ...gax.CallOption) *ApiIterator { + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).ListApis[0:len((*c.CallOptions).ListApis):len((*c.CallOptions).ListApis)], opts...) + it := &ApiIterator{} + req = proto.Clone(req).(*apigeeregistrypb.ListApisRequest) + it.InternalFetch = func(pageSize int, pageToken string) ([]*apigeeregistrypb.Api, string, error) { + resp := &apigeeregistrypb.ListApisResponse{} + if pageToken != "" { req.PageToken = pageToken } if pageSize > math.MaxInt32 { @@ -2113,6 +2632,2921 @@ func (c *registryGRPCClient) ListOperations(ctx context.Context, req *longrunnin return it } +// ListApis returns matching APIs. +func (c *registryRESTClient) ListApis(ctx context.Context, req *apigeeregistrypb.ListApisRequest, opts ...gax.CallOption) *ApiIterator { + it := &ApiIterator{} + req = proto.Clone(req).(*apigeeregistrypb.ListApisRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*apigeeregistrypb.Api, string, error) { + resp := &apigeeregistrypb.ListApisResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/apis", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetApis(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetApi returns a specified API. +func (c *registryRESTClient) GetApi(ctx context.Context, req *apigeeregistrypb.GetApiRequest, opts ...gax.CallOption) (*apigeeregistrypb.Api, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetApi[0:len((*c.CallOptions).GetApi):len((*c.CallOptions).GetApi)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &apigeeregistrypb.Api{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateApi creates a specified API. +func (c *registryRESTClient) CreateApi(ctx context.Context, req *apigeeregistrypb.CreateApiRequest, opts ...gax.CallOption) (*apigeeregistrypb.Api, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetApi() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/apis", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("apiId", fmt.Sprintf("%v", req.GetApiId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateApi[0:len((*c.CallOptions).CreateApi):len((*c.CallOptions).CreateApi)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &apigeeregistrypb.Api{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateApi used to modify a specified API. +func (c *registryRESTClient) UpdateApi(ctx context.Context, req *apigeeregistrypb.UpdateApiRequest, opts ...gax.CallOption) (*apigeeregistrypb.Api, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetApi() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetApi().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetAllowMissing() { + params.Add("allowMissing", fmt.Sprintf("%v", req.GetAllowMissing())) + } + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "api.name", url.QueryEscape(req.GetApi().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateApi[0:len((*c.CallOptions).UpdateApi):len((*c.CallOptions).UpdateApi)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &apigeeregistrypb.Api{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteApi removes a specified API and all of the resources that it +// owns. +func (c *registryRESTClient) DeleteApi(ctx context.Context, req *apigeeregistrypb.DeleteApiRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetForce() { + params.Add("force", fmt.Sprintf("%v", req.GetForce())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// ListApiVersions returns matching versions. +func (c *registryRESTClient) ListApiVersions(ctx context.Context, req *apigeeregistrypb.ListApiVersionsRequest, opts ...gax.CallOption) *ApiVersionIterator { + it := &ApiVersionIterator{} + req = proto.Clone(req).(*apigeeregistrypb.ListApiVersionsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*apigeeregistrypb.ApiVersion, string, error) { + resp := &apigeeregistrypb.ListApiVersionsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/versions", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetApiVersions(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetApiVersion returns a specified version. +func (c *registryRESTClient) GetApiVersion(ctx context.Context, req *apigeeregistrypb.GetApiVersionRequest, opts ...gax.CallOption) (*apigeeregistrypb.ApiVersion, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetApiVersion[0:len((*c.CallOptions).GetApiVersion):len((*c.CallOptions).GetApiVersion)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &apigeeregistrypb.ApiVersion{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateApiVersion creates a specified version. +func (c *registryRESTClient) CreateApiVersion(ctx context.Context, req *apigeeregistrypb.CreateApiVersionRequest, opts ...gax.CallOption) (*apigeeregistrypb.ApiVersion, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetApiVersion() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/versions", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("apiVersionId", fmt.Sprintf("%v", req.GetApiVersionId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateApiVersion[0:len((*c.CallOptions).CreateApiVersion):len((*c.CallOptions).CreateApiVersion)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &apigeeregistrypb.ApiVersion{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateApiVersion used to modify a specified version. +func (c *registryRESTClient) UpdateApiVersion(ctx context.Context, req *apigeeregistrypb.UpdateApiVersionRequest, opts ...gax.CallOption) (*apigeeregistrypb.ApiVersion, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetApiVersion() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetApiVersion().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetAllowMissing() { + params.Add("allowMissing", fmt.Sprintf("%v", req.GetAllowMissing())) + } + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "api_version.name", url.QueryEscape(req.GetApiVersion().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateApiVersion[0:len((*c.CallOptions).UpdateApiVersion):len((*c.CallOptions).UpdateApiVersion)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &apigeeregistrypb.ApiVersion{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteApiVersion removes a specified version and all of the resources that +// it owns. +func (c *registryRESTClient) DeleteApiVersion(ctx context.Context, req *apigeeregistrypb.DeleteApiVersionRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetForce() { + params.Add("force", fmt.Sprintf("%v", req.GetForce())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// ListApiSpecs returns matching specs. +func (c *registryRESTClient) ListApiSpecs(ctx context.Context, req *apigeeregistrypb.ListApiSpecsRequest, opts ...gax.CallOption) *ApiSpecIterator { + it := &ApiSpecIterator{} + req = proto.Clone(req).(*apigeeregistrypb.ListApiSpecsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*apigeeregistrypb.ApiSpec, string, error) { + resp := &apigeeregistrypb.ListApiSpecsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/specs", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetApiSpecs(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetApiSpec returns a specified spec. +func (c *registryRESTClient) GetApiSpec(ctx context.Context, req *apigeeregistrypb.GetApiSpecRequest, opts ...gax.CallOption) (*apigeeregistrypb.ApiSpec, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetApiSpec[0:len((*c.CallOptions).GetApiSpec):len((*c.CallOptions).GetApiSpec)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &apigeeregistrypb.ApiSpec{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetApiSpecContents returns the contents of a specified spec. +// If specs are stored with GZip compression, the default behavior +// is to return the spec uncompressed (the mime_type response field +// indicates the exact format returned). +func (c *registryRESTClient) GetApiSpecContents(ctx context.Context, req *apigeeregistrypb.GetApiSpecContentsRequest, opts ...gax.CallOption) (*httpbodypb.HttpBody, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:getContents", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetApiSpecContents[0:len((*c.CallOptions).GetApiSpecContents):len((*c.CallOptions).GetApiSpecContents)], opts...) + resp := &httpbodypb.HttpBody{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + resp.Data = buf + if headers := httpRsp.Header; len(headers["Content-Type"]) > 0 { + resp.ContentType = headers["Content-Type"][0] + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateApiSpec creates a specified spec. +func (c *registryRESTClient) CreateApiSpec(ctx context.Context, req *apigeeregistrypb.CreateApiSpecRequest, opts ...gax.CallOption) (*apigeeregistrypb.ApiSpec, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetApiSpec() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/specs", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("apiSpecId", fmt.Sprintf("%v", req.GetApiSpecId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateApiSpec[0:len((*c.CallOptions).CreateApiSpec):len((*c.CallOptions).CreateApiSpec)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &apigeeregistrypb.ApiSpec{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateApiSpec used to modify a specified spec. +func (c *registryRESTClient) UpdateApiSpec(ctx context.Context, req *apigeeregistrypb.UpdateApiSpecRequest, opts ...gax.CallOption) (*apigeeregistrypb.ApiSpec, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetApiSpec() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetApiSpec().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetAllowMissing() { + params.Add("allowMissing", fmt.Sprintf("%v", req.GetAllowMissing())) + } + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "api_spec.name", url.QueryEscape(req.GetApiSpec().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateApiSpec[0:len((*c.CallOptions).UpdateApiSpec):len((*c.CallOptions).UpdateApiSpec)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &apigeeregistrypb.ApiSpec{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteApiSpec removes a specified spec, all revisions, and all child +// resources (e.g., artifacts). +func (c *registryRESTClient) DeleteApiSpec(ctx context.Context, req *apigeeregistrypb.DeleteApiSpecRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetForce() { + params.Add("force", fmt.Sprintf("%v", req.GetForce())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// TagApiSpecRevision adds a tag to a specified revision of a spec. +func (c *registryRESTClient) TagApiSpecRevision(ctx context.Context, req *apigeeregistrypb.TagApiSpecRevisionRequest, opts ...gax.CallOption) (*apigeeregistrypb.ApiSpec, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:tagRevision", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).TagApiSpecRevision[0:len((*c.CallOptions).TagApiSpecRevision):len((*c.CallOptions).TagApiSpecRevision)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &apigeeregistrypb.ApiSpec{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListApiSpecRevisions lists all revisions of a spec. +// Revisions are returned in descending order of revision creation time. +func (c *registryRESTClient) ListApiSpecRevisions(ctx context.Context, req *apigeeregistrypb.ListApiSpecRevisionsRequest, opts ...gax.CallOption) *ApiSpecIterator { + it := &ApiSpecIterator{} + req = proto.Clone(req).(*apigeeregistrypb.ListApiSpecRevisionsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*apigeeregistrypb.ApiSpec, string, error) { + resp := &apigeeregistrypb.ListApiSpecRevisionsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:listRevisions", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetApiSpecs(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// RollbackApiSpec sets the current revision to a specified prior revision. +// Note that this creates a new revision with a new revision ID. +func (c *registryRESTClient) RollbackApiSpec(ctx context.Context, req *apigeeregistrypb.RollbackApiSpecRequest, opts ...gax.CallOption) (*apigeeregistrypb.ApiSpec, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:rollback", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).RollbackApiSpec[0:len((*c.CallOptions).RollbackApiSpec):len((*c.CallOptions).RollbackApiSpec)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &apigeeregistrypb.ApiSpec{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteApiSpecRevision deletes a revision of a spec. +func (c *registryRESTClient) DeleteApiSpecRevision(ctx context.Context, req *apigeeregistrypb.DeleteApiSpecRevisionRequest, opts ...gax.CallOption) (*apigeeregistrypb.ApiSpec, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:deleteRevision", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).DeleteApiSpecRevision[0:len((*c.CallOptions).DeleteApiSpecRevision):len((*c.CallOptions).DeleteApiSpecRevision)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &apigeeregistrypb.ApiSpec{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListApiDeployments returns matching deployments. +func (c *registryRESTClient) ListApiDeployments(ctx context.Context, req *apigeeregistrypb.ListApiDeploymentsRequest, opts ...gax.CallOption) *ApiDeploymentIterator { + it := &ApiDeploymentIterator{} + req = proto.Clone(req).(*apigeeregistrypb.ListApiDeploymentsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*apigeeregistrypb.ApiDeployment, string, error) { + resp := &apigeeregistrypb.ListApiDeploymentsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/deployments", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetApiDeployments(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetApiDeployment returns a specified deployment. +func (c *registryRESTClient) GetApiDeployment(ctx context.Context, req *apigeeregistrypb.GetApiDeploymentRequest, opts ...gax.CallOption) (*apigeeregistrypb.ApiDeployment, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetApiDeployment[0:len((*c.CallOptions).GetApiDeployment):len((*c.CallOptions).GetApiDeployment)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &apigeeregistrypb.ApiDeployment{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateApiDeployment creates a specified deployment. +func (c *registryRESTClient) CreateApiDeployment(ctx context.Context, req *apigeeregistrypb.CreateApiDeploymentRequest, opts ...gax.CallOption) (*apigeeregistrypb.ApiDeployment, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetApiDeployment() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/deployments", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("apiDeploymentId", fmt.Sprintf("%v", req.GetApiDeploymentId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateApiDeployment[0:len((*c.CallOptions).CreateApiDeployment):len((*c.CallOptions).CreateApiDeployment)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &apigeeregistrypb.ApiDeployment{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateApiDeployment used to modify a specified deployment. +func (c *registryRESTClient) UpdateApiDeployment(ctx context.Context, req *apigeeregistrypb.UpdateApiDeploymentRequest, opts ...gax.CallOption) (*apigeeregistrypb.ApiDeployment, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetApiDeployment() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetApiDeployment().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetAllowMissing() { + params.Add("allowMissing", fmt.Sprintf("%v", req.GetAllowMissing())) + } + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "api_deployment.name", url.QueryEscape(req.GetApiDeployment().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateApiDeployment[0:len((*c.CallOptions).UpdateApiDeployment):len((*c.CallOptions).UpdateApiDeployment)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &apigeeregistrypb.ApiDeployment{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteApiDeployment removes a specified deployment, all revisions, and all +// child resources (e.g., artifacts). +func (c *registryRESTClient) DeleteApiDeployment(ctx context.Context, req *apigeeregistrypb.DeleteApiDeploymentRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetForce() { + params.Add("force", fmt.Sprintf("%v", req.GetForce())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// TagApiDeploymentRevision adds a tag to a specified revision of a +// deployment. +func (c *registryRESTClient) TagApiDeploymentRevision(ctx context.Context, req *apigeeregistrypb.TagApiDeploymentRevisionRequest, opts ...gax.CallOption) (*apigeeregistrypb.ApiDeployment, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:tagRevision", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).TagApiDeploymentRevision[0:len((*c.CallOptions).TagApiDeploymentRevision):len((*c.CallOptions).TagApiDeploymentRevision)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &apigeeregistrypb.ApiDeployment{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListApiDeploymentRevisions lists all revisions of a deployment. +// Revisions are returned in descending order of revision creation time. +func (c *registryRESTClient) ListApiDeploymentRevisions(ctx context.Context, req *apigeeregistrypb.ListApiDeploymentRevisionsRequest, opts ...gax.CallOption) *ApiDeploymentIterator { + it := &ApiDeploymentIterator{} + req = proto.Clone(req).(*apigeeregistrypb.ListApiDeploymentRevisionsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*apigeeregistrypb.ApiDeployment, string, error) { + resp := &apigeeregistrypb.ListApiDeploymentRevisionsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:listRevisions", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetApiDeployments(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// RollbackApiDeployment sets the current revision to a specified prior +// revision. Note that this creates a new revision with a new revision ID. +func (c *registryRESTClient) RollbackApiDeployment(ctx context.Context, req *apigeeregistrypb.RollbackApiDeploymentRequest, opts ...gax.CallOption) (*apigeeregistrypb.ApiDeployment, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:rollback", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).RollbackApiDeployment[0:len((*c.CallOptions).RollbackApiDeployment):len((*c.CallOptions).RollbackApiDeployment)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &apigeeregistrypb.ApiDeployment{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteApiDeploymentRevision deletes a revision of a deployment. +func (c *registryRESTClient) DeleteApiDeploymentRevision(ctx context.Context, req *apigeeregistrypb.DeleteApiDeploymentRevisionRequest, opts ...gax.CallOption) (*apigeeregistrypb.ApiDeployment, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:deleteRevision", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).DeleteApiDeploymentRevision[0:len((*c.CallOptions).DeleteApiDeploymentRevision):len((*c.CallOptions).DeleteApiDeploymentRevision)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &apigeeregistrypb.ApiDeployment{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListArtifacts returns matching artifacts. +func (c *registryRESTClient) ListArtifacts(ctx context.Context, req *apigeeregistrypb.ListArtifactsRequest, opts ...gax.CallOption) *ArtifactIterator { + it := &ArtifactIterator{} + req = proto.Clone(req).(*apigeeregistrypb.ListArtifactsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*apigeeregistrypb.Artifact, string, error) { + resp := &apigeeregistrypb.ListArtifactsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/artifacts", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetArtifacts(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetArtifact returns a specified artifact. +func (c *registryRESTClient) GetArtifact(ctx context.Context, req *apigeeregistrypb.GetArtifactRequest, opts ...gax.CallOption) (*apigeeregistrypb.Artifact, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetArtifact[0:len((*c.CallOptions).GetArtifact):len((*c.CallOptions).GetArtifact)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &apigeeregistrypb.Artifact{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetArtifactContents returns the contents of a specified artifact. +// If artifacts are stored with GZip compression, the default behavior +// is to return the artifact uncompressed (the mime_type response field +// indicates the exact format returned). +func (c *registryRESTClient) GetArtifactContents(ctx context.Context, req *apigeeregistrypb.GetArtifactContentsRequest, opts ...gax.CallOption) (*httpbodypb.HttpBody, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:getContents", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetArtifactContents[0:len((*c.CallOptions).GetArtifactContents):len((*c.CallOptions).GetArtifactContents)], opts...) + resp := &httpbodypb.HttpBody{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + resp.Data = buf + if headers := httpRsp.Header; len(headers["Content-Type"]) > 0 { + resp.ContentType = headers["Content-Type"][0] + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateArtifact creates a specified artifact. +func (c *registryRESTClient) CreateArtifact(ctx context.Context, req *apigeeregistrypb.CreateArtifactRequest, opts ...gax.CallOption) (*apigeeregistrypb.Artifact, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetArtifact() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/artifacts", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("artifactId", fmt.Sprintf("%v", req.GetArtifactId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateArtifact[0:len((*c.CallOptions).CreateArtifact):len((*c.CallOptions).CreateArtifact)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &apigeeregistrypb.Artifact{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ReplaceArtifact used to replace a specified artifact. +func (c *registryRESTClient) ReplaceArtifact(ctx context.Context, req *apigeeregistrypb.ReplaceArtifactRequest, opts ...gax.CallOption) (*apigeeregistrypb.Artifact, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetArtifact() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetArtifact().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "artifact.name", url.QueryEscape(req.GetArtifact().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).ReplaceArtifact[0:len((*c.CallOptions).ReplaceArtifact):len((*c.CallOptions).ReplaceArtifact)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &apigeeregistrypb.Artifact{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PUT", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteArtifact removes a specified artifact. +func (c *registryRESTClient) DeleteArtifact(ctx context.Context, req *apigeeregistrypb.DeleteArtifactRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetLocation gets information about a location. +func (c *registryRESTClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *registryRESTClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetIamPolicy gets the access control policy for a resource. Returns an empty policy +// if the resource exists and does not have a policy set. +func (c *registryRESTClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:getIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetOptions().GetRequestedPolicyVersion() != 0 { + params.Add("options.requestedPolicyVersion", fmt.Sprintf("%v", req.GetOptions().GetRequestedPolicyVersion())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SetIamPolicy sets the access control policy on the specified resource. Replaces +// any existing policy. +// +// Can return NOT_FOUND, INVALID_ARGUMENT, and PERMISSION_DENIED +// errors. +func (c *registryRESTClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:setIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// TestIamPermissions returns permissions that a caller has on the specified resource. If the +// resource does not exist, this will return an empty set of +// permissions, not a NOT_FOUND error. +// +// Note: This operation is designed to be used for building +// permission-aware UIs and command-line tools, not for authorization +// checking. This operation may “fail open” without warning. +func (c *registryRESTClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:testIamPermissions", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.TestIamPermissionsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *registryRESTClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// DeleteOperation is a utility method from google.longrunning.Operations. +func (c *registryRESTClient) DeleteOperation(ctx context.Context, req *longrunningpb.DeleteOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *registryRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *registryRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + // ApiDeploymentIterator manages a stream of *apigeeregistrypb.ApiDeployment. type ApiDeploymentIterator struct { items []*apigeeregistrypb.ApiDeployment diff --git a/apigeeregistry/apiv1/registry_client_example_test.go b/apigeeregistry/apiv1/registry_client_example_test.go index db3a8405bb27..ee4895458292 100644 --- a/apigeeregistry/apiv1/registry_client_example_test.go +++ b/apigeeregistry/apiv1/registry_client_example_test.go @@ -44,6 +44,23 @@ func ExampleNewRegistryClient() { _ = c } +func ExampleNewRegistryRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := apigeeregistry.NewRegistryRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleRegistryClient_ListApis() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/apikeys/apiv2/api_keys_client.go b/apikeys/apiv2/api_keys_client.go index c27003011909..c0a8664119ba 100644 --- a/apikeys/apiv2/api_keys_client.go +++ b/apikeys/apiv2/api_keys_client.go @@ -17,23 +17,29 @@ package apikeys import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" apikeyspb "google.golang.org/genproto/googleapis/api/apikeys/v2" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" emptypb "google.golang.org/protobuf/types/known/emptypb" ) @@ -79,6 +85,20 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + CreateKey: []gax.CallOption{}, + ListKeys: []gax.CallOption{}, + GetKey: []gax.CallOption{}, + GetKeyString: []gax.CallOption{}, + UpdateKey: []gax.CallOption{}, + DeleteKey: []gax.CallOption{}, + UndeleteKey: []gax.CallOption{}, + LookupKey: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + } +} + // internalClient is an interface that defines the methods available from API Keys API. type internalClient interface { Close() error @@ -337,6 +357,89 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new api keys rest client. +// +// Manages the API keys associated with projects. +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://apikeys.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://apikeys.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://apikeys.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) CreateKey(ctx context.Context, req *apikeyspb.CreateKeyRequest, opts ...gax.CallOption) (*CreateKeyOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 10000*time.Millisecond) @@ -559,9 +662,642 @@ func (c *gRPCClient) GetOperation(ctx context.Context, req *longrunningpb.GetOpe return resp, nil } +// CreateKey creates a new API key. +// +// NOTE: Key is a global resource; hence the only supported value for +// location is global. +func (c *restClient) CreateKey(ctx context.Context, req *apikeyspb.CreateKeyRequest, opts ...gax.CallOption) (*CreateKeyOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetKey() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/keys", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetKeyId() != "" { + params.Add("keyId", fmt.Sprintf("%v", req.GetKeyId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &CreateKeyOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListKeys lists the API keys owned by a project. The key string of the API key +// isn’t included in the response. +// +// NOTE: Key is a global resource; hence the only supported value for +// location is global. +func (c *restClient) ListKeys(ctx context.Context, req *apikeyspb.ListKeysRequest, opts ...gax.CallOption) *KeyIterator { + it := &KeyIterator{} + req = proto.Clone(req).(*apikeyspb.ListKeysRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*apikeyspb.Key, string, error) { + resp := &apikeyspb.ListKeysResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/keys", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + if req.GetShowDeleted() { + params.Add("showDeleted", fmt.Sprintf("%v", req.GetShowDeleted())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetKeys(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetKey gets the metadata for an API key. The key string of the API key +// isn’t included in the response. +// +// NOTE: Key is a global resource; hence the only supported value for +// location is global. +func (c *restClient) GetKey(ctx context.Context, req *apikeyspb.GetKeyRequest, opts ...gax.CallOption) (*apikeyspb.Key, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetKey[0:len((*c.CallOptions).GetKey):len((*c.CallOptions).GetKey)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &apikeyspb.Key{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetKeyString get the key string for an API key. +// +// NOTE: Key is a global resource; hence the only supported value for +// location is global. +func (c *restClient) GetKeyString(ctx context.Context, req *apikeyspb.GetKeyStringRequest, opts ...gax.CallOption) (*apikeyspb.GetKeyStringResponse, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/keyString", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetKeyString[0:len((*c.CallOptions).GetKeyString):len((*c.CallOptions).GetKeyString)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &apikeyspb.GetKeyStringResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateKey patches the modifiable fields of an API key. +// The key string of the API key isn’t included in the response. +// +// NOTE: Key is a global resource; hence the only supported value for +// location is global. +func (c *restClient) UpdateKey(ctx context.Context, req *apikeyspb.UpdateKeyRequest, opts ...gax.CallOption) (*UpdateKeyOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetKey() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetKey().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "key.name", url.QueryEscape(req.GetKey().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &UpdateKeyOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteKey deletes an API key. Deleted key can be retrieved within 30 days of +// deletion. Afterward, key will be purged from the project. +// +// NOTE: Key is a global resource; hence the only supported value for +// location is global. +func (c *restClient) DeleteKey(ctx context.Context, req *apikeyspb.DeleteKeyRequest, opts ...gax.CallOption) (*DeleteKeyOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetEtag() != "" { + params.Add("etag", fmt.Sprintf("%v", req.GetEtag())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &DeleteKeyOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UndeleteKey undeletes an API key which was deleted within 30 days. +// +// NOTE: Key is a global resource; hence the only supported value for +// location is global. +func (c *restClient) UndeleteKey(ctx context.Context, req *apikeyspb.UndeleteKeyRequest, opts ...gax.CallOption) (*UndeleteKeyOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:undelete", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &UndeleteKeyOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// LookupKey find the parent project and resource name of the API +// key that matches the key string in the request. If the API key has been +// purged, resource name will not be set. +// The service account must have the apikeys.keys.lookup permission +// on the parent project. +func (c *restClient) LookupKey(ctx context.Context, req *apikeyspb.LookupKeyRequest, opts ...gax.CallOption) (*apikeyspb.LookupKeyResponse, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/keys:lookupKey") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("keyString", fmt.Sprintf("%v", req.GetKeyString())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).LookupKey[0:len((*c.CallOptions).LookupKey):len((*c.CallOptions).LookupKey)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &apikeyspb.LookupKeyResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *restClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + // CreateKeyOperation manages a long-running operation from CreateKey. type CreateKeyOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateKeyOperation returns a new CreateKeyOperation from a given name. @@ -572,10 +1308,21 @@ func (c *gRPCClient) CreateKeyOperation(name string) *CreateKeyOperation { } } +// CreateKeyOperation returns a new CreateKeyOperation from a given name. +// The name must be that of a previously created CreateKeyOperation, possibly from a different process. +func (c *restClient) CreateKeyOperation(name string) *CreateKeyOperation { + override := fmt.Sprintf("/v2/%s", name) + return &CreateKeyOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateKeyOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*apikeyspb.Key, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp apikeyspb.Key if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -593,6 +1340,7 @@ func (op *CreateKeyOperation) Wait(ctx context.Context, opts ...gax.CallOption) // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateKeyOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*apikeyspb.Key, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp apikeyspb.Key if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -630,7 +1378,8 @@ func (op *CreateKeyOperation) Name() string { // DeleteKeyOperation manages a long-running operation from DeleteKey. type DeleteKeyOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteKeyOperation returns a new DeleteKeyOperation from a given name. @@ -641,10 +1390,21 @@ func (c *gRPCClient) DeleteKeyOperation(name string) *DeleteKeyOperation { } } +// DeleteKeyOperation returns a new DeleteKeyOperation from a given name. +// The name must be that of a previously created DeleteKeyOperation, possibly from a different process. +func (c *restClient) DeleteKeyOperation(name string) *DeleteKeyOperation { + override := fmt.Sprintf("/v2/%s", name) + return &DeleteKeyOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteKeyOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*apikeyspb.Key, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp apikeyspb.Key if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -662,6 +1422,7 @@ func (op *DeleteKeyOperation) Wait(ctx context.Context, opts ...gax.CallOption) // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteKeyOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*apikeyspb.Key, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp apikeyspb.Key if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -699,7 +1460,8 @@ func (op *DeleteKeyOperation) Name() string { // UndeleteKeyOperation manages a long-running operation from UndeleteKey. type UndeleteKeyOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UndeleteKeyOperation returns a new UndeleteKeyOperation from a given name. @@ -710,10 +1472,21 @@ func (c *gRPCClient) UndeleteKeyOperation(name string) *UndeleteKeyOperation { } } +// UndeleteKeyOperation returns a new UndeleteKeyOperation from a given name. +// The name must be that of a previously created UndeleteKeyOperation, possibly from a different process. +func (c *restClient) UndeleteKeyOperation(name string) *UndeleteKeyOperation { + override := fmt.Sprintf("/v2/%s", name) + return &UndeleteKeyOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UndeleteKeyOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*apikeyspb.Key, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp apikeyspb.Key if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -731,6 +1504,7 @@ func (op *UndeleteKeyOperation) Wait(ctx context.Context, opts ...gax.CallOption // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UndeleteKeyOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*apikeyspb.Key, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp apikeyspb.Key if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -768,7 +1542,8 @@ func (op *UndeleteKeyOperation) Name() string { // UpdateKeyOperation manages a long-running operation from UpdateKey. type UpdateKeyOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateKeyOperation returns a new UpdateKeyOperation from a given name. @@ -779,10 +1554,21 @@ func (c *gRPCClient) UpdateKeyOperation(name string) *UpdateKeyOperation { } } +// UpdateKeyOperation returns a new UpdateKeyOperation from a given name. +// The name must be that of a previously created UpdateKeyOperation, possibly from a different process. +func (c *restClient) UpdateKeyOperation(name string) *UpdateKeyOperation { + override := fmt.Sprintf("/v2/%s", name) + return &UpdateKeyOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateKeyOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*apikeyspb.Key, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp apikeyspb.Key if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -800,6 +1586,7 @@ func (op *UpdateKeyOperation) Wait(ctx context.Context, opts ...gax.CallOption) // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateKeyOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*apikeyspb.Key, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp apikeyspb.Key if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/apikeys/apiv2/api_keys_client_example_test.go b/apikeys/apiv2/api_keys_client_example_test.go index 240c32554c71..71435f37a0fe 100644 --- a/apikeys/apiv2/api_keys_client_example_test.go +++ b/apikeys/apiv2/api_keys_client_example_test.go @@ -42,6 +42,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := apikeys.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_CreateKey() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/apikeys/apiv2/doc.go b/apikeys/apiv2/doc.go index 7dccd3d485a5..c7500d3d2ae4 100644 --- a/apikeys/apiv2/doc.go +++ b/apikeys/apiv2/doc.go @@ -87,6 +87,8 @@ package apikeys // import "cloud.google.com/go/apikeys/apiv2" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -176,3 +178,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/apikeys/apiv2/gapic_metadata.json b/apikeys/apiv2/gapic_metadata.json index 3915363f5880..5daf7986b994 100644 --- a/apikeys/apiv2/gapic_metadata.json +++ b/apikeys/apiv2/gapic_metadata.json @@ -56,6 +56,56 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "CreateKey": { + "methods": [ + "CreateKey" + ] + }, + "DeleteKey": { + "methods": [ + "DeleteKey" + ] + }, + "GetKey": { + "methods": [ + "GetKey" + ] + }, + "GetKeyString": { + "methods": [ + "GetKeyString" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ListKeys": { + "methods": [ + "ListKeys" + ] + }, + "LookupKey": { + "methods": [ + "LookupKey" + ] + }, + "UndeleteKey": { + "methods": [ + "UndeleteKey" + ] + }, + "UpdateKey": { + "methods": [ + "UpdateKey" + ] + } + } } } } diff --git a/appengine/apiv1/appenginepb/app_yaml.pb.go b/appengine/apiv1/appenginepb/app_yaml.pb.go index a0320135201f..13df98248042 100644 --- a/appengine/apiv1/appenginepb/app_yaml.pb.go +++ b/appengine/apiv1/appenginepb/app_yaml.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/appengine/v1/app_yaml.proto package appenginepb @@ -515,7 +515,6 @@ type UrlMap struct { // Type of handler for this URL pattern. // // Types that are assignable to HandlerType: - // // *UrlMap_StaticFiles // *UrlMap_Script // *UrlMap_ApiEndpoint diff --git a/appengine/apiv1/appenginepb/appengine.pb.go b/appengine/apiv1/appenginepb/appengine.pb.go index 2f84124322a7..1c62fbe03f41 100644 --- a/appengine/apiv1/appenginepb/appengine.pb.go +++ b/appengine/apiv1/appenginepb/appengine.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/appengine/v1/appengine.proto package appenginepb diff --git a/appengine/apiv1/appenginepb/application.pb.go b/appengine/apiv1/appenginepb/application.pb.go index 55ae5dccf2db..43c747414933 100644 --- a/appengine/apiv1/appenginepb/application.pb.go +++ b/appengine/apiv1/appenginepb/application.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/appengine/v1/application.proto package appenginepb diff --git a/appengine/apiv1/appenginepb/audit_data.pb.go b/appengine/apiv1/appenginepb/audit_data.pb.go index 7bcae1821664..c608db5ba8d5 100644 --- a/appengine/apiv1/appenginepb/audit_data.pb.go +++ b/appengine/apiv1/appenginepb/audit_data.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/appengine/v1/audit_data.proto package appenginepb @@ -47,7 +47,6 @@ type AuditData struct { // included in parent audit log message. // // Types that are assignable to Method: - // // *AuditData_UpdateService // *AuditData_CreateVersion Method isAuditData_Method `protobuf_oneof:"method"` diff --git a/appengine/apiv1/appenginepb/certificate.pb.go b/appengine/apiv1/appenginepb/certificate.pb.go index 29bbbdeec38b..493d189d9b97 100644 --- a/appengine/apiv1/appenginepb/certificate.pb.go +++ b/appengine/apiv1/appenginepb/certificate.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/appengine/v1/certificate.proto package appenginepb diff --git a/appengine/apiv1/appenginepb/deploy.pb.go b/appengine/apiv1/appenginepb/deploy.pb.go index 26295bf511f9..0a49ff314f68 100644 --- a/appengine/apiv1/appenginepb/deploy.pb.go +++ b/appengine/apiv1/appenginepb/deploy.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/appengine/v1/deploy.proto package appenginepb diff --git a/appengine/apiv1/appenginepb/deployed_files.pb.go b/appengine/apiv1/appenginepb/deployed_files.pb.go index 4853822d56e2..54e5b07e521c 100644 --- a/appengine/apiv1/appenginepb/deployed_files.pb.go +++ b/appengine/apiv1/appenginepb/deployed_files.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/appengine/v1/deployed_files.proto package appenginepb diff --git a/appengine/apiv1/appenginepb/domain.pb.go b/appengine/apiv1/appenginepb/domain.pb.go index fbcae354e4dd..4975b58437bd 100644 --- a/appengine/apiv1/appenginepb/domain.pb.go +++ b/appengine/apiv1/appenginepb/domain.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/appengine/v1/domain.proto package appenginepb diff --git a/appengine/apiv1/appenginepb/domain_mapping.pb.go b/appengine/apiv1/appenginepb/domain_mapping.pb.go index 7a12ed764e87..19598b265918 100644 --- a/appengine/apiv1/appenginepb/domain_mapping.pb.go +++ b/appengine/apiv1/appenginepb/domain_mapping.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/appengine/v1/domain_mapping.proto package appenginepb diff --git a/appengine/apiv1/appenginepb/firewall.pb.go b/appengine/apiv1/appenginepb/firewall.pb.go index fc691170f6dd..09ae5bddad7c 100644 --- a/appengine/apiv1/appenginepb/firewall.pb.go +++ b/appengine/apiv1/appenginepb/firewall.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/appengine/v1/firewall.proto package appenginepb @@ -107,8 +107,8 @@ type FirewallRule struct { // rule applies to. You can use the wildcard character "*" to match all IPs // equivalent to "0/0" and "::/0" together. // Examples: `192.168.1.1` or `192.168.0.0/16` or `2001:db8::/32` + // or `2001:0db8:0000:0042:0000:8a2e:0370:7334`. // - // or `2001:0db8:0000:0042:0000:8a2e:0370:7334`. // //

Truncation will be silently performed on addresses which are not // properly truncated. For example, `1.2.3.4/24` is accepted as the same diff --git a/appengine/apiv1/appenginepb/instance.pb.go b/appengine/apiv1/appenginepb/instance.pb.go index b017f342378d..2b19e644ff47 100644 --- a/appengine/apiv1/appenginepb/instance.pb.go +++ b/appengine/apiv1/appenginepb/instance.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/appengine/v1/instance.proto package appenginepb diff --git a/appengine/apiv1/appenginepb/location.pb.go b/appengine/apiv1/appenginepb/location.pb.go index c5c86257206b..3b393ab88c57 100644 --- a/appengine/apiv1/appenginepb/location.pb.go +++ b/appengine/apiv1/appenginepb/location.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/appengine/v1/location.proto package appenginepb diff --git a/appengine/apiv1/appenginepb/network_settings.pb.go b/appengine/apiv1/appenginepb/network_settings.pb.go index 36fe4dd40911..ece822372de7 100644 --- a/appengine/apiv1/appenginepb/network_settings.pb.go +++ b/appengine/apiv1/appenginepb/network_settings.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/appengine/v1/network_settings.proto package appenginepb diff --git a/appengine/apiv1/appenginepb/operation.pb.go b/appengine/apiv1/appenginepb/operation.pb.go index a00503ae1e4f..915e9518012d 100644 --- a/appengine/apiv1/appenginepb/operation.pb.go +++ b/appengine/apiv1/appenginepb/operation.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/appengine/v1/operation.proto package appenginepb @@ -74,7 +74,6 @@ type OperationMetadataV1 struct { // @OutputOnly // // Types that are assignable to MethodMetadata: - // // *OperationMetadataV1_CreateVersionMetadata MethodMetadata isOperationMetadataV1_MethodMetadata `protobuf_oneof:"method_metadata"` } diff --git a/appengine/apiv1/appenginepb/service.pb.go b/appengine/apiv1/appenginepb/service.pb.go index 65e8a4f6305a..70e88838b981 100644 --- a/appengine/apiv1/appenginepb/service.pb.go +++ b/appengine/apiv1/appenginepb/service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/appengine/v1/service.proto package appenginepb diff --git a/appengine/apiv1/appenginepb/version.pb.go b/appengine/apiv1/appenginepb/version.pb.go index 82f70ae8063f..fd67400d78f3 100644 --- a/appengine/apiv1/appenginepb/version.pb.go +++ b/appengine/apiv1/appenginepb/version.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/appengine/v1/version.proto package appenginepb @@ -301,7 +301,6 @@ type Version struct { // Defaults to `AutomaticScaling`. // // Types that are assignable to Scaling: - // // *Version_AutomaticScaling // *Version_BasicScaling // *Version_ManualScaling @@ -1866,7 +1865,6 @@ type Entrypoint struct { // The command to run. // // Types that are assignable to Command: - // // *Entrypoint_Shell Command isEntrypoint_Command `protobuf_oneof:"command"` } diff --git a/appengine/apiv1/applications_client.go b/appengine/apiv1/applications_client.go index 6bbb3c65bfb3..0d1ee8db2db4 100644 --- a/appengine/apiv1/applications_client.go +++ b/appengine/apiv1/applications_client.go @@ -17,9 +17,12 @@ package appengine import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,12 +30,15 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" ) var newApplicationsClientHook clientHook @@ -66,6 +72,15 @@ func defaultApplicationsCallOptions() *ApplicationsCallOptions { } } +func defaultApplicationsRESTCallOptions() *ApplicationsCallOptions { + return &ApplicationsCallOptions{ + GetApplication: []gax.CallOption{}, + CreateApplication: []gax.CallOption{}, + UpdateApplication: []gax.CallOption{}, + RepairApplication: []gax.CallOption{}, + } +} + // internalApplicationsClient is an interface that defines the methods available from App Engine Admin API. type internalApplicationsClient interface { Close() error @@ -278,6 +293,89 @@ func (c *applicationsGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type applicationsRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing ApplicationsClient + CallOptions **ApplicationsCallOptions +} + +// NewApplicationsRESTClient creates a new applications rest client. +// +// Manages App Engine applications. +func NewApplicationsRESTClient(ctx context.Context, opts ...option.ClientOption) (*ApplicationsClient, error) { + clientOpts := append(defaultApplicationsRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultApplicationsRESTCallOptions() + c := &applicationsRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &ApplicationsClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultApplicationsRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://appengine.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://appengine.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://appengine.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *applicationsRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *applicationsRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *applicationsRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *applicationsGRPCClient) GetApplication(ctx context.Context, req *appenginepb.GetApplicationRequest, opts ...gax.CallOption) (*appenginepb.Application, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -350,9 +448,302 @@ func (c *applicationsGRPCClient) RepairApplication(ctx context.Context, req *app }, nil } +// GetApplication gets information about an application. +func (c *applicationsRESTClient) GetApplication(ctx context.Context, req *appenginepb.GetApplicationRequest, opts ...gax.CallOption) (*appenginepb.Application, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetApplication[0:len((*c.CallOptions).GetApplication):len((*c.CallOptions).GetApplication)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &appenginepb.Application{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateApplication creates an App Engine application for a Google Cloud Platform project. +// Required fields: +// +// id - The ID of the target Cloud Platform project. +// +// location - The region (at https://cloud.google.com/appengine/docs/locations) where you want the App Engine application located. +// +// For more information about App Engine applications, see Managing Projects, Applications, and Billing (at https://cloud.google.com/appengine/docs/standard/python/console/). +func (c *applicationsRESTClient) CreateApplication(ctx context.Context, req *appenginepb.CreateApplicationRequest, opts ...gax.CallOption) (*CreateApplicationOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetApplication() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/apps") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateApplicationOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateApplication updates the specified Application resource. +// You can update the following fields: +// +// auth_domain - Google authentication domain for controlling user access to the application. +// +// default_cookie_expiration - Cookie expiration policy for the application. +// +// iap - Identity-Aware Proxy properties for the application. +func (c *applicationsRESTClient) UpdateApplication(ctx context.Context, req *appenginepb.UpdateApplicationRequest, opts ...gax.CallOption) (*UpdateApplicationOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetApplication() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateApplicationOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// RepairApplication recreates the required App Engine features for the specified App Engine +// application, for example a Cloud Storage bucket or App Engine service +// account. +// Use this method if you receive an error message about a missing feature, +// for example, Error retrieving the App Engine service account. +// If you have deleted your App Engine service account, this will +// not be able to recreate it. Instead, you should attempt to use the +// IAM undelete API if possible at https://cloud.google.com/iam/reference/rest/v1/projects.serviceAccounts/undelete?apix_params={ (at https://cloud.google.com/iam/reference/rest/v1/projects.serviceAccounts/undelete?apix_params=%7B)“name”%3A"projects%2F-%2FserviceAccounts%2Funique_id"%2C"resource"%3A%7B%7D%7D . +// If the deletion was recent, the numeric ID can be found in the Cloud +// Console Activity Log. +func (c *applicationsRESTClient) RepairApplication(ctx context.Context, req *appenginepb.RepairApplicationRequest, opts ...gax.CallOption) (*RepairApplicationOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:repair", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &RepairApplicationOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + // CreateApplicationOperation manages a long-running operation from CreateApplication. type CreateApplicationOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateApplicationOperation returns a new CreateApplicationOperation from a given name. @@ -363,10 +754,21 @@ func (c *applicationsGRPCClient) CreateApplicationOperation(name string) *Create } } +// CreateApplicationOperation returns a new CreateApplicationOperation from a given name. +// The name must be that of a previously created CreateApplicationOperation, possibly from a different process. +func (c *applicationsRESTClient) CreateApplicationOperation(name string) *CreateApplicationOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateApplicationOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateApplicationOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*appenginepb.Application, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp appenginepb.Application if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -384,6 +786,7 @@ func (op *CreateApplicationOperation) Wait(ctx context.Context, opts ...gax.Call // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateApplicationOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*appenginepb.Application, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp appenginepb.Application if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -421,7 +824,8 @@ func (op *CreateApplicationOperation) Name() string { // RepairApplicationOperation manages a long-running operation from RepairApplication. type RepairApplicationOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // RepairApplicationOperation returns a new RepairApplicationOperation from a given name. @@ -432,10 +836,21 @@ func (c *applicationsGRPCClient) RepairApplicationOperation(name string) *Repair } } +// RepairApplicationOperation returns a new RepairApplicationOperation from a given name. +// The name must be that of a previously created RepairApplicationOperation, possibly from a different process. +func (c *applicationsRESTClient) RepairApplicationOperation(name string) *RepairApplicationOperation { + override := fmt.Sprintf("/v1/%s", name) + return &RepairApplicationOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *RepairApplicationOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*appenginepb.Application, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp appenginepb.Application if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -453,6 +868,7 @@ func (op *RepairApplicationOperation) Wait(ctx context.Context, opts ...gax.Call // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *RepairApplicationOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*appenginepb.Application, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp appenginepb.Application if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -490,7 +906,8 @@ func (op *RepairApplicationOperation) Name() string { // UpdateApplicationOperation manages a long-running operation from UpdateApplication. type UpdateApplicationOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateApplicationOperation returns a new UpdateApplicationOperation from a given name. @@ -501,10 +918,21 @@ func (c *applicationsGRPCClient) UpdateApplicationOperation(name string) *Update } } +// UpdateApplicationOperation returns a new UpdateApplicationOperation from a given name. +// The name must be that of a previously created UpdateApplicationOperation, possibly from a different process. +func (c *applicationsRESTClient) UpdateApplicationOperation(name string) *UpdateApplicationOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateApplicationOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateApplicationOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*appenginepb.Application, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp appenginepb.Application if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -522,6 +950,7 @@ func (op *UpdateApplicationOperation) Wait(ctx context.Context, opts ...gax.Call // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateApplicationOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*appenginepb.Application, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp appenginepb.Application if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/appengine/apiv1/applications_client_example_test.go b/appengine/apiv1/applications_client_example_test.go index f60856408478..8513465ae280 100644 --- a/appengine/apiv1/applications_client_example_test.go +++ b/appengine/apiv1/applications_client_example_test.go @@ -40,6 +40,23 @@ func ExampleNewApplicationsClient() { _ = c } +func ExampleNewApplicationsRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := appengine.NewApplicationsRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleApplicationsClient_GetApplication() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/appengine/apiv1/authorized_certificates_client.go b/appengine/apiv1/authorized_certificates_client.go index bd3abbd1836d..863cfd3ef7b4 100644 --- a/appengine/apiv1/authorized_certificates_client.go +++ b/appengine/apiv1/authorized_certificates_client.go @@ -17,19 +17,25 @@ package appengine import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" appenginepb "cloud.google.com/go/appengine/apiv1/appenginepb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -66,6 +72,16 @@ func defaultAuthorizedCertificatesCallOptions() *AuthorizedCertificatesCallOptio } } +func defaultAuthorizedCertificatesRESTCallOptions() *AuthorizedCertificatesCallOptions { + return &AuthorizedCertificatesCallOptions{ + ListAuthorizedCertificates: []gax.CallOption{}, + GetAuthorizedCertificate: []gax.CallOption{}, + CreateAuthorizedCertificate: []gax.CallOption{}, + UpdateAuthorizedCertificate: []gax.CallOption{}, + DeleteAuthorizedCertificate: []gax.CallOption{}, + } +} + // internalAuthorizedCertificatesClient is an interface that defines the methods available from App Engine Admin API. type internalAuthorizedCertificatesClient interface { Close() error @@ -225,6 +241,75 @@ func (c *authorizedCertificatesGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type authorizedCertificatesRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing AuthorizedCertificatesClient + CallOptions **AuthorizedCertificatesCallOptions +} + +// NewAuthorizedCertificatesRESTClient creates a new authorized certificates rest client. +// +// Manages SSL certificates a user is authorized to administer. A user can +// administer any SSL certificates applicable to their authorized domains. +func NewAuthorizedCertificatesRESTClient(ctx context.Context, opts ...option.ClientOption) (*AuthorizedCertificatesClient, error) { + clientOpts := append(defaultAuthorizedCertificatesRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultAuthorizedCertificatesRESTCallOptions() + c := &authorizedCertificatesRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &AuthorizedCertificatesClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultAuthorizedCertificatesRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://appengine.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://appengine.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://appengine.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *authorizedCertificatesRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *authorizedCertificatesRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *authorizedCertificatesRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *authorizedCertificatesGRPCClient) ListAuthorizedCertificates(ctx context.Context, req *appenginepb.ListAuthorizedCertificatesRequest, opts ...gax.CallOption) *AuthorizedCertificateIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -334,6 +419,339 @@ func (c *authorizedCertificatesGRPCClient) DeleteAuthorizedCertificate(ctx conte return err } +// ListAuthorizedCertificates lists all SSL certificates the user is authorized to administer. +func (c *authorizedCertificatesRESTClient) ListAuthorizedCertificates(ctx context.Context, req *appenginepb.ListAuthorizedCertificatesRequest, opts ...gax.CallOption) *AuthorizedCertificateIterator { + it := &AuthorizedCertificateIterator{} + req = proto.Clone(req).(*appenginepb.ListAuthorizedCertificatesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*appenginepb.AuthorizedCertificate, string, error) { + resp := &appenginepb.ListAuthorizedCertificatesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/authorizedCertificates", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + if req.GetView() != 0 { + params.Add("view", fmt.Sprintf("%v", req.GetView())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetCertificates(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetAuthorizedCertificate gets the specified SSL certificate. +func (c *authorizedCertificatesRESTClient) GetAuthorizedCertificate(ctx context.Context, req *appenginepb.GetAuthorizedCertificateRequest, opts ...gax.CallOption) (*appenginepb.AuthorizedCertificate, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetView() != 0 { + params.Add("view", fmt.Sprintf("%v", req.GetView())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetAuthorizedCertificate[0:len((*c.CallOptions).GetAuthorizedCertificate):len((*c.CallOptions).GetAuthorizedCertificate)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &appenginepb.AuthorizedCertificate{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateAuthorizedCertificate uploads the specified SSL certificate. +func (c *authorizedCertificatesRESTClient) CreateAuthorizedCertificate(ctx context.Context, req *appenginepb.CreateAuthorizedCertificateRequest, opts ...gax.CallOption) (*appenginepb.AuthorizedCertificate, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetCertificate() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/authorizedCertificates", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateAuthorizedCertificate[0:len((*c.CallOptions).CreateAuthorizedCertificate):len((*c.CallOptions).CreateAuthorizedCertificate)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &appenginepb.AuthorizedCertificate{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateAuthorizedCertificate updates the specified SSL certificate. To renew a certificate and maintain +// its existing domain mappings, update certificate_data with a new +// certificate. The new certificate must be applicable to the same domains as +// the original certificate. The certificate display_name may also be +// updated. +func (c *authorizedCertificatesRESTClient) UpdateAuthorizedCertificate(ctx context.Context, req *appenginepb.UpdateAuthorizedCertificateRequest, opts ...gax.CallOption) (*appenginepb.AuthorizedCertificate, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetCertificate() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateAuthorizedCertificate[0:len((*c.CallOptions).UpdateAuthorizedCertificate):len((*c.CallOptions).UpdateAuthorizedCertificate)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &appenginepb.AuthorizedCertificate{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteAuthorizedCertificate deletes the specified SSL certificate. +func (c *authorizedCertificatesRESTClient) DeleteAuthorizedCertificate(ctx context.Context, req *appenginepb.DeleteAuthorizedCertificateRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + // AuthorizedCertificateIterator manages a stream of *appenginepb.AuthorizedCertificate. type AuthorizedCertificateIterator struct { items []*appenginepb.AuthorizedCertificate diff --git a/appengine/apiv1/authorized_certificates_client_example_test.go b/appengine/apiv1/authorized_certificates_client_example_test.go index da97ce2a0c03..2a2cb840c5ad 100644 --- a/appengine/apiv1/authorized_certificates_client_example_test.go +++ b/appengine/apiv1/authorized_certificates_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewAuthorizedCertificatesClient() { _ = c } +func ExampleNewAuthorizedCertificatesRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := appengine.NewAuthorizedCertificatesRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleAuthorizedCertificatesClient_ListAuthorizedCertificates() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/appengine/apiv1/authorized_domains_client.go b/appengine/apiv1/authorized_domains_client.go index 031ac932c614..46061149231d 100644 --- a/appengine/apiv1/authorized_domains_client.go +++ b/appengine/apiv1/authorized_domains_client.go @@ -19,17 +19,22 @@ package appengine import ( "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" appenginepb "cloud.google.com/go/appengine/apiv1/appenginepb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -58,6 +63,12 @@ func defaultAuthorizedDomainsCallOptions() *AuthorizedDomainsCallOptions { } } +func defaultAuthorizedDomainsRESTCallOptions() *AuthorizedDomainsCallOptions { + return &AuthorizedDomainsCallOptions{ + ListAuthorizedDomains: []gax.CallOption{}, + } +} + // internalAuthorizedDomainsClient is an interface that defines the methods available from App Engine Admin API. type internalAuthorizedDomainsClient interface { Close() error @@ -191,6 +202,76 @@ func (c *authorizedDomainsGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type authorizedDomainsRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing AuthorizedDomainsClient + CallOptions **AuthorizedDomainsCallOptions +} + +// NewAuthorizedDomainsRESTClient creates a new authorized domains rest client. +// +// Manages domains a user is authorized to administer. To authorize use of a +// domain, verify ownership via +// Webmaster Central (at https://www.google.com/webmasters/verification/home). +func NewAuthorizedDomainsRESTClient(ctx context.Context, opts ...option.ClientOption) (*AuthorizedDomainsClient, error) { + clientOpts := append(defaultAuthorizedDomainsRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultAuthorizedDomainsRESTCallOptions() + c := &authorizedDomainsRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &AuthorizedDomainsClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultAuthorizedDomainsRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://appengine.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://appengine.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://appengine.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *authorizedDomainsRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *authorizedDomainsRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *authorizedDomainsRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *authorizedDomainsGRPCClient) ListAuthorizedDomains(ctx context.Context, req *appenginepb.ListAuthorizedDomainsRequest, opts ...gax.CallOption) *AuthorizedDomainIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -236,6 +317,94 @@ func (c *authorizedDomainsGRPCClient) ListAuthorizedDomains(ctx context.Context, return it } +// ListAuthorizedDomains lists all domains the user is authorized to administer. +func (c *authorizedDomainsRESTClient) ListAuthorizedDomains(ctx context.Context, req *appenginepb.ListAuthorizedDomainsRequest, opts ...gax.CallOption) *AuthorizedDomainIterator { + it := &AuthorizedDomainIterator{} + req = proto.Clone(req).(*appenginepb.ListAuthorizedDomainsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*appenginepb.AuthorizedDomain, string, error) { + resp := &appenginepb.ListAuthorizedDomainsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/authorizedDomains", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetDomains(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + // AuthorizedDomainIterator manages a stream of *appenginepb.AuthorizedDomain. type AuthorizedDomainIterator struct { items []*appenginepb.AuthorizedDomain diff --git a/appengine/apiv1/authorized_domains_client_example_test.go b/appengine/apiv1/authorized_domains_client_example_test.go index 7bfec02db537..cbe5250df126 100644 --- a/appengine/apiv1/authorized_domains_client_example_test.go +++ b/appengine/apiv1/authorized_domains_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewAuthorizedDomainsClient() { _ = c } +func ExampleNewAuthorizedDomainsRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := appengine.NewAuthorizedDomainsRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleAuthorizedDomainsClient_ListAuthorizedDomains() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/appengine/apiv1/doc.go b/appengine/apiv1/doc.go index 6daae70f2bda..b775e38f9c63 100644 --- a/appengine/apiv1/doc.go +++ b/appengine/apiv1/doc.go @@ -80,6 +80,8 @@ package appengine // import "cloud.google.com/go/appengine/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -170,3 +172,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/appengine/apiv1/domain_mappings_client.go b/appengine/apiv1/domain_mappings_client.go index b5c8ec150056..3b695ec4640e 100644 --- a/appengine/apiv1/domain_mappings_client.go +++ b/appengine/apiv1/domain_mappings_client.go @@ -17,9 +17,12 @@ package appengine import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,13 +30,16 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -70,6 +76,16 @@ func defaultDomainMappingsCallOptions() *DomainMappingsCallOptions { } } +func defaultDomainMappingsRESTCallOptions() *DomainMappingsCallOptions { + return &DomainMappingsCallOptions{ + ListDomainMappings: []gax.CallOption{}, + GetDomainMapping: []gax.CallOption{}, + CreateDomainMapping: []gax.CallOption{}, + UpdateDomainMapping: []gax.CallOption{}, + DeleteDomainMapping: []gax.CallOption{}, + } +} + // internalDomainMappingsClient is an interface that defines the methods available from App Engine Admin API. type internalDomainMappingsClient interface { Close() error @@ -272,6 +288,89 @@ func (c *domainMappingsGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type domainMappingsRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing DomainMappingsClient + CallOptions **DomainMappingsCallOptions +} + +// NewDomainMappingsRESTClient creates a new domain mappings rest client. +// +// Manages domains serving an application. +func NewDomainMappingsRESTClient(ctx context.Context, opts ...option.ClientOption) (*DomainMappingsClient, error) { + clientOpts := append(defaultDomainMappingsRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultDomainMappingsRESTCallOptions() + c := &domainMappingsRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &DomainMappingsClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultDomainMappingsRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://appengine.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://appengine.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://appengine.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *domainMappingsRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *domainMappingsRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *domainMappingsRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *domainMappingsGRPCClient) ListDomainMappings(ctx context.Context, req *appenginepb.ListDomainMappingsRequest, opts ...gax.CallOption) *DomainMappingIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -391,9 +490,373 @@ func (c *domainMappingsGRPCClient) DeleteDomainMapping(ctx context.Context, req }, nil } +// ListDomainMappings lists the domain mappings on an application. +func (c *domainMappingsRESTClient) ListDomainMappings(ctx context.Context, req *appenginepb.ListDomainMappingsRequest, opts ...gax.CallOption) *DomainMappingIterator { + it := &DomainMappingIterator{} + req = proto.Clone(req).(*appenginepb.ListDomainMappingsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*appenginepb.DomainMapping, string, error) { + resp := &appenginepb.ListDomainMappingsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/domainMappings", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetDomainMappings(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetDomainMapping gets the specified domain mapping. +func (c *domainMappingsRESTClient) GetDomainMapping(ctx context.Context, req *appenginepb.GetDomainMappingRequest, opts ...gax.CallOption) (*appenginepb.DomainMapping, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetDomainMapping[0:len((*c.CallOptions).GetDomainMapping):len((*c.CallOptions).GetDomainMapping)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &appenginepb.DomainMapping{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateDomainMapping maps a domain to an application. A user must be authorized to administer a +// domain in order to map it to an application. For a list of available +// authorized domains, see AuthorizedDomains.ListAuthorizedDomains (at ). +func (c *domainMappingsRESTClient) CreateDomainMapping(ctx context.Context, req *appenginepb.CreateDomainMappingRequest, opts ...gax.CallOption) (*CreateDomainMappingOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetDomainMapping() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/domainMappings", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetOverrideStrategy() != 0 { + params.Add("overrideStrategy", fmt.Sprintf("%v", req.GetOverrideStrategy())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateDomainMappingOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateDomainMapping updates the specified domain mapping. To map an SSL certificate to a +// domain mapping, update certificate_id to point to an AuthorizedCertificate +// resource. A user must be authorized to administer the associated domain +// in order to update a DomainMapping resource. +func (c *domainMappingsRESTClient) UpdateDomainMapping(ctx context.Context, req *appenginepb.UpdateDomainMappingRequest, opts ...gax.CallOption) (*UpdateDomainMappingOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetDomainMapping() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateDomainMappingOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteDomainMapping deletes the specified domain mapping. A user must be authorized to +// administer the associated domain in order to delete a DomainMapping +// resource. +func (c *domainMappingsRESTClient) DeleteDomainMapping(ctx context.Context, req *appenginepb.DeleteDomainMappingRequest, opts ...gax.CallOption) (*DeleteDomainMappingOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteDomainMappingOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + // CreateDomainMappingOperation manages a long-running operation from CreateDomainMapping. type CreateDomainMappingOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateDomainMappingOperation returns a new CreateDomainMappingOperation from a given name. @@ -404,10 +867,21 @@ func (c *domainMappingsGRPCClient) CreateDomainMappingOperation(name string) *Cr } } +// CreateDomainMappingOperation returns a new CreateDomainMappingOperation from a given name. +// The name must be that of a previously created CreateDomainMappingOperation, possibly from a different process. +func (c *domainMappingsRESTClient) CreateDomainMappingOperation(name string) *CreateDomainMappingOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateDomainMappingOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateDomainMappingOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*appenginepb.DomainMapping, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp appenginepb.DomainMapping if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -425,6 +899,7 @@ func (op *CreateDomainMappingOperation) Wait(ctx context.Context, opts ...gax.Ca // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateDomainMappingOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*appenginepb.DomainMapping, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp appenginepb.DomainMapping if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -462,7 +937,8 @@ func (op *CreateDomainMappingOperation) Name() string { // DeleteDomainMappingOperation manages a long-running operation from DeleteDomainMapping. type DeleteDomainMappingOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteDomainMappingOperation returns a new DeleteDomainMappingOperation from a given name. @@ -473,10 +949,21 @@ func (c *domainMappingsGRPCClient) DeleteDomainMappingOperation(name string) *De } } +// DeleteDomainMappingOperation returns a new DeleteDomainMappingOperation from a given name. +// The name must be that of a previously created DeleteDomainMappingOperation, possibly from a different process. +func (c *domainMappingsRESTClient) DeleteDomainMappingOperation(name string) *DeleteDomainMappingOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteDomainMappingOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteDomainMappingOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -490,6 +977,7 @@ func (op *DeleteDomainMappingOperation) Wait(ctx context.Context, opts ...gax.Ca // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteDomainMappingOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -520,7 +1008,8 @@ func (op *DeleteDomainMappingOperation) Name() string { // UpdateDomainMappingOperation manages a long-running operation from UpdateDomainMapping. type UpdateDomainMappingOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateDomainMappingOperation returns a new UpdateDomainMappingOperation from a given name. @@ -531,10 +1020,21 @@ func (c *domainMappingsGRPCClient) UpdateDomainMappingOperation(name string) *Up } } +// UpdateDomainMappingOperation returns a new UpdateDomainMappingOperation from a given name. +// The name must be that of a previously created UpdateDomainMappingOperation, possibly from a different process. +func (c *domainMappingsRESTClient) UpdateDomainMappingOperation(name string) *UpdateDomainMappingOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateDomainMappingOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateDomainMappingOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*appenginepb.DomainMapping, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp appenginepb.DomainMapping if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -552,6 +1052,7 @@ func (op *UpdateDomainMappingOperation) Wait(ctx context.Context, opts ...gax.Ca // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateDomainMappingOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*appenginepb.DomainMapping, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp appenginepb.DomainMapping if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/appengine/apiv1/domain_mappings_client_example_test.go b/appengine/apiv1/domain_mappings_client_example_test.go index a357f7a05d8f..55277684a493 100644 --- a/appengine/apiv1/domain_mappings_client_example_test.go +++ b/appengine/apiv1/domain_mappings_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewDomainMappingsClient() { _ = c } +func ExampleNewDomainMappingsRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := appengine.NewDomainMappingsRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleDomainMappingsClient_ListDomainMappings() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/appengine/apiv1/firewall_client.go b/appengine/apiv1/firewall_client.go index d6ab31507d6e..976d550e1d79 100644 --- a/appengine/apiv1/firewall_client.go +++ b/appengine/apiv1/firewall_client.go @@ -17,19 +17,25 @@ package appengine import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" appenginepb "cloud.google.com/go/appengine/apiv1/appenginepb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -68,6 +74,17 @@ func defaultFirewallCallOptions() *FirewallCallOptions { } } +func defaultFirewallRESTCallOptions() *FirewallCallOptions { + return &FirewallCallOptions{ + ListIngressRules: []gax.CallOption{}, + BatchUpdateIngressRules: []gax.CallOption{}, + CreateIngressRule: []gax.CallOption{}, + GetIngressRule: []gax.CallOption{}, + UpdateIngressRule: []gax.CallOption{}, + DeleteIngressRule: []gax.CallOption{}, + } +} + // internalFirewallClient is an interface that defines the methods available from App Engine Admin API. type internalFirewallClient interface { Close() error @@ -249,6 +266,83 @@ func (c *firewallGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type firewallRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing FirewallClient + CallOptions **FirewallCallOptions +} + +// NewFirewallRESTClient creates a new firewall rest client. +// +// Firewall resources are used to define a collection of access control rules +// for an Application. Each rule is defined with a position which specifies +// the rule’s order in the sequence of rules, an IP range to be matched against +// requests, and an action to take upon matching requests. +// +// Every request is evaluated against the Firewall rules in priority order. +// Processesing stops at the first rule which matches the request’s IP address. +// A final rule always specifies an action that applies to all remaining +// IP addresses. The default final rule for a newly-created application will be +// set to “allow” if not otherwise specified by the user. +func NewFirewallRESTClient(ctx context.Context, opts ...option.ClientOption) (*FirewallClient, error) { + clientOpts := append(defaultFirewallRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultFirewallRESTCallOptions() + c := &firewallRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &FirewallClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultFirewallRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://appengine.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://appengine.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://appengine.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *firewallRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *firewallRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *firewallRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *firewallGRPCClient) ListIngressRules(ctx context.Context, req *appenginepb.ListIngressRulesRequest, opts ...gax.CallOption) *FirewallRuleIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -375,6 +469,400 @@ func (c *firewallGRPCClient) DeleteIngressRule(ctx context.Context, req *appengi return err } +// ListIngressRules lists the firewall rules of an application. +func (c *firewallRESTClient) ListIngressRules(ctx context.Context, req *appenginepb.ListIngressRulesRequest, opts ...gax.CallOption) *FirewallRuleIterator { + it := &FirewallRuleIterator{} + req = proto.Clone(req).(*appenginepb.ListIngressRulesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*appenginepb.FirewallRule, string, error) { + resp := &appenginepb.ListIngressRulesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/firewall/ingressRules", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetMatchingAddress() != "" { + params.Add("matchingAddress", fmt.Sprintf("%v", req.GetMatchingAddress())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetIngressRules(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// BatchUpdateIngressRules replaces the entire firewall ruleset in one bulk operation. This overrides +// and replaces the rules of an existing firewall with the new rules. +// +// If the final rule does not match traffic with the ‘*’ wildcard IP range, +// then an “allow all” rule is explicitly added to the end of the list. +func (c *firewallRESTClient) BatchUpdateIngressRules(ctx context.Context, req *appenginepb.BatchUpdateIngressRulesRequest, opts ...gax.CallOption) (*appenginepb.BatchUpdateIngressRulesResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:batchUpdate", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).BatchUpdateIngressRules[0:len((*c.CallOptions).BatchUpdateIngressRules):len((*c.CallOptions).BatchUpdateIngressRules)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &appenginepb.BatchUpdateIngressRulesResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateIngressRule creates a firewall rule for the application. +func (c *firewallRESTClient) CreateIngressRule(ctx context.Context, req *appenginepb.CreateIngressRuleRequest, opts ...gax.CallOption) (*appenginepb.FirewallRule, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetRule() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/firewall/ingressRules", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateIngressRule[0:len((*c.CallOptions).CreateIngressRule):len((*c.CallOptions).CreateIngressRule)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &appenginepb.FirewallRule{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetIngressRule gets the specified firewall rule. +func (c *firewallRESTClient) GetIngressRule(ctx context.Context, req *appenginepb.GetIngressRuleRequest, opts ...gax.CallOption) (*appenginepb.FirewallRule, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetIngressRule[0:len((*c.CallOptions).GetIngressRule):len((*c.CallOptions).GetIngressRule)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &appenginepb.FirewallRule{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateIngressRule updates the specified firewall rule. +func (c *firewallRESTClient) UpdateIngressRule(ctx context.Context, req *appenginepb.UpdateIngressRuleRequest, opts ...gax.CallOption) (*appenginepb.FirewallRule, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetRule() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateIngressRule[0:len((*c.CallOptions).UpdateIngressRule):len((*c.CallOptions).UpdateIngressRule)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &appenginepb.FirewallRule{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteIngressRule deletes the specified firewall rule. +func (c *firewallRESTClient) DeleteIngressRule(ctx context.Context, req *appenginepb.DeleteIngressRuleRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + // FirewallRuleIterator manages a stream of *appenginepb.FirewallRule. type FirewallRuleIterator struct { items []*appenginepb.FirewallRule diff --git a/appengine/apiv1/firewall_client_example_test.go b/appengine/apiv1/firewall_client_example_test.go index b593015e4e8f..5eff26dfbe04 100644 --- a/appengine/apiv1/firewall_client_example_test.go +++ b/appengine/apiv1/firewall_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewFirewallClient() { _ = c } +func ExampleNewFirewallRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := appengine.NewFirewallRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleFirewallClient_ListIngressRules() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/appengine/apiv1/gapic_metadata.json b/appengine/apiv1/gapic_metadata.json index c8dde65ebcc2..e76001b75e4e 100644 --- a/appengine/apiv1/gapic_metadata.json +++ b/appengine/apiv1/gapic_metadata.json @@ -31,6 +31,31 @@ ] } } + }, + "rest": { + "libraryClient": "ApplicationsClient", + "rpcs": { + "CreateApplication": { + "methods": [ + "CreateApplication" + ] + }, + "GetApplication": { + "methods": [ + "GetApplication" + ] + }, + "RepairApplication": { + "methods": [ + "RepairApplication" + ] + }, + "UpdateApplication": { + "methods": [ + "UpdateApplication" + ] + } + } } } }, @@ -65,6 +90,36 @@ ] } } + }, + "rest": { + "libraryClient": "AuthorizedCertificatesClient", + "rpcs": { + "CreateAuthorizedCertificate": { + "methods": [ + "CreateAuthorizedCertificate" + ] + }, + "DeleteAuthorizedCertificate": { + "methods": [ + "DeleteAuthorizedCertificate" + ] + }, + "GetAuthorizedCertificate": { + "methods": [ + "GetAuthorizedCertificate" + ] + }, + "ListAuthorizedCertificates": { + "methods": [ + "ListAuthorizedCertificates" + ] + }, + "UpdateAuthorizedCertificate": { + "methods": [ + "UpdateAuthorizedCertificate" + ] + } + } } } }, @@ -79,6 +134,16 @@ ] } } + }, + "rest": { + "libraryClient": "AuthorizedDomainsClient", + "rpcs": { + "ListAuthorizedDomains": { + "methods": [ + "ListAuthorizedDomains" + ] + } + } } } }, @@ -113,6 +178,36 @@ ] } } + }, + "rest": { + "libraryClient": "DomainMappingsClient", + "rpcs": { + "CreateDomainMapping": { + "methods": [ + "CreateDomainMapping" + ] + }, + "DeleteDomainMapping": { + "methods": [ + "DeleteDomainMapping" + ] + }, + "GetDomainMapping": { + "methods": [ + "GetDomainMapping" + ] + }, + "ListDomainMappings": { + "methods": [ + "ListDomainMappings" + ] + }, + "UpdateDomainMapping": { + "methods": [ + "UpdateDomainMapping" + ] + } + } } } }, @@ -152,6 +247,41 @@ ] } } + }, + "rest": { + "libraryClient": "FirewallClient", + "rpcs": { + "BatchUpdateIngressRules": { + "methods": [ + "BatchUpdateIngressRules" + ] + }, + "CreateIngressRule": { + "methods": [ + "CreateIngressRule" + ] + }, + "DeleteIngressRule": { + "methods": [ + "DeleteIngressRule" + ] + }, + "GetIngressRule": { + "methods": [ + "GetIngressRule" + ] + }, + "ListIngressRules": { + "methods": [ + "ListIngressRules" + ] + }, + "UpdateIngressRule": { + "methods": [ + "UpdateIngressRule" + ] + } + } } } }, @@ -181,6 +311,31 @@ ] } } + }, + "rest": { + "libraryClient": "InstancesClient", + "rpcs": { + "DebugInstance": { + "methods": [ + "DebugInstance" + ] + }, + "DeleteInstance": { + "methods": [ + "DeleteInstance" + ] + }, + "GetInstance": { + "methods": [ + "GetInstance" + ] + }, + "ListInstances": { + "methods": [ + "ListInstances" + ] + } + } } } }, @@ -210,6 +365,31 @@ ] } } + }, + "rest": { + "libraryClient": "ServicesClient", + "rpcs": { + "DeleteService": { + "methods": [ + "DeleteService" + ] + }, + "GetService": { + "methods": [ + "GetService" + ] + }, + "ListServices": { + "methods": [ + "ListServices" + ] + }, + "UpdateService": { + "methods": [ + "UpdateService" + ] + } + } } } }, @@ -244,6 +424,36 @@ ] } } + }, + "rest": { + "libraryClient": "VersionsClient", + "rpcs": { + "CreateVersion": { + "methods": [ + "CreateVersion" + ] + }, + "DeleteVersion": { + "methods": [ + "DeleteVersion" + ] + }, + "GetVersion": { + "methods": [ + "GetVersion" + ] + }, + "ListVersions": { + "methods": [ + "ListVersions" + ] + }, + "UpdateVersion": { + "methods": [ + "UpdateVersion" + ] + } + } } } } diff --git a/appengine/apiv1/instances_client.go b/appengine/apiv1/instances_client.go index b25f9396a895..9bf6ab199ce7 100644 --- a/appengine/apiv1/instances_client.go +++ b/appengine/apiv1/instances_client.go @@ -17,9 +17,12 @@ package appengine import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,13 +30,16 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -68,6 +74,15 @@ func defaultInstancesCallOptions() *InstancesCallOptions { } } +func defaultInstancesRESTCallOptions() *InstancesCallOptions { + return &InstancesCallOptions{ + ListInstances: []gax.CallOption{}, + GetInstance: []gax.CallOption{}, + DeleteInstance: []gax.CallOption{}, + DebugInstance: []gax.CallOption{}, + } +} + // internalInstancesClient is an interface that defines the methods available from App Engine Admin API. type internalInstancesClient interface { Close() error @@ -271,6 +286,89 @@ func (c *instancesGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type instancesRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing InstancesClient + CallOptions **InstancesCallOptions +} + +// NewInstancesRESTClient creates a new instances rest client. +// +// Manages instances of a version. +func NewInstancesRESTClient(ctx context.Context, opts ...option.ClientOption) (*InstancesClient, error) { + clientOpts := append(defaultInstancesRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultInstancesRESTCallOptions() + c := &instancesRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &InstancesClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultInstancesRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://appengine.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://appengine.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://appengine.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *instancesRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *instancesRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *instancesRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *instancesGRPCClient) ListInstances(ctx context.Context, req *appenginepb.ListInstancesRequest, opts ...gax.CallOption) *InstanceIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -371,9 +469,307 @@ func (c *instancesGRPCClient) DebugInstance(ctx context.Context, req *appenginep }, nil } +// ListInstances lists the instances of a version. +// +// Tip: To aggregate details about instances over time, see the +// Stackdriver Monitoring API (at https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.timeSeries/list). +func (c *instancesRESTClient) ListInstances(ctx context.Context, req *appenginepb.ListInstancesRequest, opts ...gax.CallOption) *InstanceIterator { + it := &InstanceIterator{} + req = proto.Clone(req).(*appenginepb.ListInstancesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*appenginepb.Instance, string, error) { + resp := &appenginepb.ListInstancesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/instances", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetInstances(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetInstance gets instance information. +func (c *instancesRESTClient) GetInstance(ctx context.Context, req *appenginepb.GetInstanceRequest, opts ...gax.CallOption) (*appenginepb.Instance, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetInstance[0:len((*c.CallOptions).GetInstance):len((*c.CallOptions).GetInstance)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &appenginepb.Instance{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteInstance stops a running instance. +// +// The instance might be automatically recreated based on the scaling settings +// of the version. For more information, see “How Instances are Managed” +// (standard environment (at https://cloud.google.com/appengine/docs/standard/python/how-instances-are-managed) | +// flexible environment (at https://cloud.google.com/appengine/docs/flexible/python/how-instances-are-managed)). +// +// To ensure that instances are not re-created and avoid getting billed, you +// can stop all instances within the target version by changing the serving +// status of the version to STOPPED with the +// apps.services.versions.patch (at https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions/patch) +// method. +func (c *instancesRESTClient) DeleteInstance(ctx context.Context, req *appenginepb.DeleteInstanceRequest, opts ...gax.CallOption) (*DeleteInstanceOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DebugInstance enables debugging on a VM instance. This allows you to use the SSH +// command to connect to the virtual machine where the instance lives. +// While in “debug mode”, the instance continues to serve live traffic. +// You should delete the instance when you are done debugging and then +// allow the system to take over and determine if another instance +// should be started. +// +// Only applicable for instances in App Engine flexible environment. +func (c *instancesRESTClient) DebugInstance(ctx context.Context, req *appenginepb.DebugInstanceRequest, opts ...gax.CallOption) (*DebugInstanceOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:debug", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DebugInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + // DebugInstanceOperation manages a long-running operation from DebugInstance. type DebugInstanceOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DebugInstanceOperation returns a new DebugInstanceOperation from a given name. @@ -384,10 +780,21 @@ func (c *instancesGRPCClient) DebugInstanceOperation(name string) *DebugInstance } } +// DebugInstanceOperation returns a new DebugInstanceOperation from a given name. +// The name must be that of a previously created DebugInstanceOperation, possibly from a different process. +func (c *instancesRESTClient) DebugInstanceOperation(name string) *DebugInstanceOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DebugInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DebugInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*appenginepb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp appenginepb.Instance if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -405,6 +812,7 @@ func (op *DebugInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOpti // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DebugInstanceOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*appenginepb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp appenginepb.Instance if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -442,7 +850,8 @@ func (op *DebugInstanceOperation) Name() string { // DeleteInstanceOperation manages a long-running operation from DeleteInstance. type DeleteInstanceOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteInstanceOperation returns a new DeleteInstanceOperation from a given name. @@ -453,10 +862,21 @@ func (c *instancesGRPCClient) DeleteInstanceOperation(name string) *DeleteInstan } } +// DeleteInstanceOperation returns a new DeleteInstanceOperation from a given name. +// The name must be that of a previously created DeleteInstanceOperation, possibly from a different process. +func (c *instancesRESTClient) DeleteInstanceOperation(name string) *DeleteInstanceOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -470,6 +890,7 @@ func (op *DeleteInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOpt // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteInstanceOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } diff --git a/appengine/apiv1/instances_client_example_test.go b/appengine/apiv1/instances_client_example_test.go index 52b11d28f00e..ff490cdb4d81 100644 --- a/appengine/apiv1/instances_client_example_test.go +++ b/appengine/apiv1/instances_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewInstancesClient() { _ = c } +func ExampleNewInstancesRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := appengine.NewInstancesRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleInstancesClient_ListInstances() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/appengine/apiv1/services_client.go b/appengine/apiv1/services_client.go index d614b3cf7db6..a6cb249dbc7d 100644 --- a/appengine/apiv1/services_client.go +++ b/appengine/apiv1/services_client.go @@ -17,9 +17,12 @@ package appengine import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,13 +30,16 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -68,6 +74,15 @@ func defaultServicesCallOptions() *ServicesCallOptions { } } +func defaultServicesRESTCallOptions() *ServicesCallOptions { + return &ServicesCallOptions{ + ListServices: []gax.CallOption{}, + GetService: []gax.CallOption{}, + UpdateService: []gax.CallOption{}, + DeleteService: []gax.CallOption{}, + } +} + // internalServicesClient is an interface that defines the methods available from App Engine Admin API. type internalServicesClient interface { Close() error @@ -250,6 +265,89 @@ func (c *servicesGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type servicesRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing ServicesClient + CallOptions **ServicesCallOptions +} + +// NewServicesRESTClient creates a new services rest client. +// +// Manages services of an application. +func NewServicesRESTClient(ctx context.Context, opts ...option.ClientOption) (*ServicesClient, error) { + clientOpts := append(defaultServicesRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultServicesRESTCallOptions() + c := &servicesRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &ServicesClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultServicesRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://appengine.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://appengine.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://appengine.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *servicesRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *servicesRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *servicesRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *servicesGRPCClient) ListServices(ctx context.Context, req *appenginepb.ListServicesRequest, opts ...gax.CallOption) *ServiceIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -350,9 +448,297 @@ func (c *servicesGRPCClient) DeleteService(ctx context.Context, req *appenginepb }, nil } +// ListServices lists all the services in the application. +func (c *servicesRESTClient) ListServices(ctx context.Context, req *appenginepb.ListServicesRequest, opts ...gax.CallOption) *ServiceIterator { + it := &ServiceIterator{} + req = proto.Clone(req).(*appenginepb.ListServicesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*appenginepb.Service, string, error) { + resp := &appenginepb.ListServicesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/services", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetServices(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetService gets the current configuration of the specified service. +func (c *servicesRESTClient) GetService(ctx context.Context, req *appenginepb.GetServiceRequest, opts ...gax.CallOption) (*appenginepb.Service, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetService[0:len((*c.CallOptions).GetService):len((*c.CallOptions).GetService)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &appenginepb.Service{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateService updates the configuration of the specified service. +func (c *servicesRESTClient) UpdateService(ctx context.Context, req *appenginepb.UpdateServiceRequest, opts ...gax.CallOption) (*UpdateServiceOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetService() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetMigrateTraffic() { + params.Add("migrateTraffic", fmt.Sprintf("%v", req.GetMigrateTraffic())) + } + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateServiceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteService deletes the specified service and all enclosed versions. +func (c *servicesRESTClient) DeleteService(ctx context.Context, req *appenginepb.DeleteServiceRequest, opts ...gax.CallOption) (*DeleteServiceOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteServiceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + // DeleteServiceOperation manages a long-running operation from DeleteService. type DeleteServiceOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteServiceOperation returns a new DeleteServiceOperation from a given name. @@ -363,10 +749,21 @@ func (c *servicesGRPCClient) DeleteServiceOperation(name string) *DeleteServiceO } } +// DeleteServiceOperation returns a new DeleteServiceOperation from a given name. +// The name must be that of a previously created DeleteServiceOperation, possibly from a different process. +func (c *servicesRESTClient) DeleteServiceOperation(name string) *DeleteServiceOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteServiceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteServiceOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -380,6 +777,7 @@ func (op *DeleteServiceOperation) Wait(ctx context.Context, opts ...gax.CallOpti // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteServiceOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -410,7 +808,8 @@ func (op *DeleteServiceOperation) Name() string { // UpdateServiceOperation manages a long-running operation from UpdateService. type UpdateServiceOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateServiceOperation returns a new UpdateServiceOperation from a given name. @@ -421,10 +820,21 @@ func (c *servicesGRPCClient) UpdateServiceOperation(name string) *UpdateServiceO } } +// UpdateServiceOperation returns a new UpdateServiceOperation from a given name. +// The name must be that of a previously created UpdateServiceOperation, possibly from a different process. +func (c *servicesRESTClient) UpdateServiceOperation(name string) *UpdateServiceOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateServiceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateServiceOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*appenginepb.Service, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp appenginepb.Service if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -442,6 +852,7 @@ func (op *UpdateServiceOperation) Wait(ctx context.Context, opts ...gax.CallOpti // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateServiceOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*appenginepb.Service, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp appenginepb.Service if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/appengine/apiv1/services_client_example_test.go b/appengine/apiv1/services_client_example_test.go index 3fead76ee946..29b78540bfe2 100644 --- a/appengine/apiv1/services_client_example_test.go +++ b/appengine/apiv1/services_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewServicesClient() { _ = c } +func ExampleNewServicesRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := appengine.NewServicesRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleServicesClient_ListServices() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/appengine/apiv1/versions_client.go b/appengine/apiv1/versions_client.go index 1f647b8084b4..b812fed6403d 100644 --- a/appengine/apiv1/versions_client.go +++ b/appengine/apiv1/versions_client.go @@ -17,9 +17,12 @@ package appengine import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,13 +30,16 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -70,6 +76,16 @@ func defaultVersionsCallOptions() *VersionsCallOptions { } } +func defaultVersionsRESTCallOptions() *VersionsCallOptions { + return &VersionsCallOptions{ + ListVersions: []gax.CallOption{}, + GetVersion: []gax.CallOption{}, + CreateVersion: []gax.CallOption{}, + UpdateVersion: []gax.CallOption{}, + DeleteVersion: []gax.CallOption{}, + } +} + // internalVersionsClient is an interface that defines the methods available from App Engine Admin API. type internalVersionsClient interface { Close() error @@ -311,6 +327,89 @@ func (c *versionsGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type versionsRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing VersionsClient + CallOptions **VersionsCallOptions +} + +// NewVersionsRESTClient creates a new versions rest client. +// +// Manages versions of a service. +func NewVersionsRESTClient(ctx context.Context, opts ...option.ClientOption) (*VersionsClient, error) { + clientOpts := append(defaultVersionsRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultVersionsRESTCallOptions() + c := &versionsRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &VersionsClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultVersionsRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://appengine.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://appengine.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://appengine.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *versionsRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *versionsRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *versionsRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *versionsGRPCClient) ListVersions(ctx context.Context, req *appenginepb.ListVersionsRequest, opts ...gax.CallOption) *VersionIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -430,9 +529,415 @@ func (c *versionsGRPCClient) DeleteVersion(ctx context.Context, req *appenginepb }, nil } +// ListVersions lists the versions of a service. +func (c *versionsRESTClient) ListVersions(ctx context.Context, req *appenginepb.ListVersionsRequest, opts ...gax.CallOption) *VersionIterator { + it := &VersionIterator{} + req = proto.Clone(req).(*appenginepb.ListVersionsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*appenginepb.Version, string, error) { + resp := &appenginepb.ListVersionsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/versions", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + if req.GetView() != 0 { + params.Add("view", fmt.Sprintf("%v", req.GetView())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetVersions(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetVersion gets the specified Version resource. +// By default, only a BASIC_VIEW will be returned. +// Specify the FULL_VIEW parameter to get the full resource. +func (c *versionsRESTClient) GetVersion(ctx context.Context, req *appenginepb.GetVersionRequest, opts ...gax.CallOption) (*appenginepb.Version, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetView() != 0 { + params.Add("view", fmt.Sprintf("%v", req.GetView())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetVersion[0:len((*c.CallOptions).GetVersion):len((*c.CallOptions).GetVersion)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &appenginepb.Version{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateVersion deploys code and resource files to a new version. +func (c *versionsRESTClient) CreateVersion(ctx context.Context, req *appenginepb.CreateVersionRequest, opts ...gax.CallOption) (*CreateVersionOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetVersion() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/versions", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateVersionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateVersion updates the specified Version resource. +// You can specify the following fields depending on the App Engine +// environment and type of scaling that the version resource uses: +// +// Standard environment +// +// instance_class (at https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions#Version.FIELDS.instance_class) +// +// automatic scaling in the standard environment: +// +// automatic_scaling.min_idle_instances (at https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions#Version.FIELDS.automatic_scaling) +// +// automatic_scaling.max_idle_instances (at https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions#Version.FIELDS.automatic_scaling) +// +// automaticScaling.standard_scheduler_settings.max_instances (at https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions#StandardSchedulerSettings) +// +// automaticScaling.standard_scheduler_settings.min_instances (at https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions#StandardSchedulerSettings) +// +// automaticScaling.standard_scheduler_settings.target_cpu_utilization (at https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions#StandardSchedulerSettings) +// +// automaticScaling.standard_scheduler_settings.target_throughput_utilization (at https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions#StandardSchedulerSettings) +// +// basic scaling or manual scaling in the standard environment: +// +// serving_status (at https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions#Version.FIELDS.serving_status) +// +// manual_scaling.instances (at https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions#manualscaling) +// +// Flexible environment +// +// serving_status (at https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions#Version.FIELDS.serving_status) +// +// automatic scaling in the flexible environment: +// +// automatic_scaling.min_total_instances (at https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions#Version.FIELDS.automatic_scaling) +// +// automatic_scaling.max_total_instances (at https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions#Version.FIELDS.automatic_scaling) +// +// automatic_scaling.cool_down_period_sec (at https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions#Version.FIELDS.automatic_scaling) +// +// automatic_scaling.cpu_utilization.target_utilization (at https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions#Version.FIELDS.automatic_scaling) +// +// manual scaling in the flexible environment: +// +// manual_scaling.instances (at https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions#manualscaling) +func (c *versionsRESTClient) UpdateVersion(ctx context.Context, req *appenginepb.UpdateVersionRequest, opts ...gax.CallOption) (*UpdateVersionOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetVersion() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateVersionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteVersion deletes an existing Version resource. +func (c *versionsRESTClient) DeleteVersion(ctx context.Context, req *appenginepb.DeleteVersionRequest, opts ...gax.CallOption) (*DeleteVersionOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteVersionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + // CreateVersionOperation manages a long-running operation from CreateVersion. type CreateVersionOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateVersionOperation returns a new CreateVersionOperation from a given name. @@ -443,10 +948,21 @@ func (c *versionsGRPCClient) CreateVersionOperation(name string) *CreateVersionO } } +// CreateVersionOperation returns a new CreateVersionOperation from a given name. +// The name must be that of a previously created CreateVersionOperation, possibly from a different process. +func (c *versionsRESTClient) CreateVersionOperation(name string) *CreateVersionOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateVersionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateVersionOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*appenginepb.Version, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp appenginepb.Version if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -464,6 +980,7 @@ func (op *CreateVersionOperation) Wait(ctx context.Context, opts ...gax.CallOpti // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateVersionOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*appenginepb.Version, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp appenginepb.Version if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -501,7 +1018,8 @@ func (op *CreateVersionOperation) Name() string { // DeleteVersionOperation manages a long-running operation from DeleteVersion. type DeleteVersionOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteVersionOperation returns a new DeleteVersionOperation from a given name. @@ -512,10 +1030,21 @@ func (c *versionsGRPCClient) DeleteVersionOperation(name string) *DeleteVersionO } } +// DeleteVersionOperation returns a new DeleteVersionOperation from a given name. +// The name must be that of a previously created DeleteVersionOperation, possibly from a different process. +func (c *versionsRESTClient) DeleteVersionOperation(name string) *DeleteVersionOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteVersionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteVersionOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -529,6 +1058,7 @@ func (op *DeleteVersionOperation) Wait(ctx context.Context, opts ...gax.CallOpti // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteVersionOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -559,7 +1089,8 @@ func (op *DeleteVersionOperation) Name() string { // UpdateVersionOperation manages a long-running operation from UpdateVersion. type UpdateVersionOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateVersionOperation returns a new UpdateVersionOperation from a given name. @@ -570,10 +1101,21 @@ func (c *versionsGRPCClient) UpdateVersionOperation(name string) *UpdateVersionO } } +// UpdateVersionOperation returns a new UpdateVersionOperation from a given name. +// The name must be that of a previously created UpdateVersionOperation, possibly from a different process. +func (c *versionsRESTClient) UpdateVersionOperation(name string) *UpdateVersionOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateVersionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateVersionOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*appenginepb.Version, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp appenginepb.Version if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -591,6 +1133,7 @@ func (op *UpdateVersionOperation) Wait(ctx context.Context, opts ...gax.CallOpti // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateVersionOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*appenginepb.Version, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp appenginepb.Version if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/appengine/apiv1/versions_client_example_test.go b/appengine/apiv1/versions_client_example_test.go index d011384373a0..ab566585a121 100644 --- a/appengine/apiv1/versions_client_example_test.go +++ b/appengine/apiv1/versions_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewVersionsClient() { _ = c } +func ExampleNewVersionsRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := appengine.NewVersionsRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleVersionsClient_ListVersions() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/area120/tables/apiv1alpha1/tables_client.go b/area120/tables/apiv1alpha1/tables_client.go index 810e463b4f67..3c4c190d2388 100644 --- a/area120/tables/apiv1alpha1/tables_client.go +++ b/area120/tables/apiv1alpha1/tables_client.go @@ -729,6 +729,11 @@ func (c *restClient) GetTable(ctx context.Context, req *tablespb.GetTableRequest } baseUrl.Path += fmt.Sprintf("/v1alpha1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -796,6 +801,7 @@ func (c *restClient) ListTables(ctx context.Context, req *tablespb.ListTablesReq baseUrl.Path += fmt.Sprintf("/v1alpha1/tables") params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -869,6 +875,11 @@ func (c *restClient) GetWorkspace(ctx context.Context, req *tablespb.GetWorkspac } baseUrl.Path += fmt.Sprintf("/v1alpha1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -936,6 +947,7 @@ func (c *restClient) ListWorkspaces(ctx context.Context, req *tablespb.ListWorks baseUrl.Path += fmt.Sprintf("/v1alpha1/workspaces") params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -1010,6 +1022,7 @@ func (c *restClient) GetRow(ctx context.Context, req *tablespb.GetRowRequest, op baseUrl.Path += fmt.Sprintf("/v1alpha1/%v", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetView() != 0 { params.Add("view", fmt.Sprintf("%v", req.GetView())) } @@ -1083,6 +1096,7 @@ func (c *restClient) ListRows(ctx context.Context, req *tablespb.ListRowsRequest baseUrl.Path += fmt.Sprintf("/v1alpha1/%v/rows", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1170,6 +1184,7 @@ func (c *restClient) CreateRow(ctx context.Context, req *tablespb.CreateRowReque baseUrl.Path += fmt.Sprintf("/v1alpha1/%v/rows", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetView() != 0 { params.Add("view", fmt.Sprintf("%v", req.GetView())) } @@ -1235,6 +1250,11 @@ func (c *restClient) BatchCreateRows(ctx context.Context, req *tablespb.BatchCre } baseUrl.Path += fmt.Sprintf("/v1alpha1/%v/rows:batchCreate", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1296,6 +1316,7 @@ func (c *restClient) UpdateRow(ctx context.Context, req *tablespb.UpdateRowReque baseUrl.Path += fmt.Sprintf("/v1alpha1/%v", req.GetRow().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -1368,6 +1389,11 @@ func (c *restClient) BatchUpdateRows(ctx context.Context, req *tablespb.BatchUpd } baseUrl.Path += fmt.Sprintf("/v1alpha1/%v/rows:batchUpdate", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1421,6 +1447,11 @@ func (c *restClient) DeleteRow(ctx context.Context, req *tablespb.DeleteRowReque } baseUrl.Path += fmt.Sprintf("/v1alpha1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1462,6 +1493,11 @@ func (c *restClient) BatchDeleteRows(ctx context.Context, req *tablespb.BatchDel } baseUrl.Path += fmt.Sprintf("/v1alpha1/%v/rows:batchDelete", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) diff --git a/area120/tables/apiv1alpha1/tablespb/tables.pb.go b/area120/tables/apiv1alpha1/tablespb/tables.pb.go index b70af17c2134..349f77ed1f7f 100644 --- a/area120/tables/apiv1alpha1/tablespb/tables.pb.go +++ b/area120/tables/apiv1alpha1/tablespb/tables.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/area120/tables/v1alpha1/tables.proto package tablespb diff --git a/artifactregistry/apiv1/artifact_registry_client.go b/artifactregistry/apiv1/artifact_registry_client.go index 58fad80046bd..21b384ad35f7 100644 --- a/artifactregistry/apiv1/artifact_registry_client.go +++ b/artifactregistry/apiv1/artifact_registry_client.go @@ -17,9 +17,12 @@ package artifactregistry import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,14 +30,17 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" iampb "google.golang.org/genproto/googleapis/iam/v1" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -115,6 +121,38 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + ListDockerImages: []gax.CallOption{}, + GetDockerImage: []gax.CallOption{}, + ImportAptArtifacts: []gax.CallOption{}, + ImportYumArtifacts: []gax.CallOption{}, + ListRepositories: []gax.CallOption{}, + GetRepository: []gax.CallOption{}, + CreateRepository: []gax.CallOption{}, + UpdateRepository: []gax.CallOption{}, + DeleteRepository: []gax.CallOption{}, + ListPackages: []gax.CallOption{}, + GetPackage: []gax.CallOption{}, + DeletePackage: []gax.CallOption{}, + ListVersions: []gax.CallOption{}, + GetVersion: []gax.CallOption{}, + DeleteVersion: []gax.CallOption{}, + ListFiles: []gax.CallOption{}, + GetFile: []gax.CallOption{}, + ListTags: []gax.CallOption{}, + GetTag: []gax.CallOption{}, + CreateTag: []gax.CallOption{}, + UpdateTag: []gax.CallOption{}, + DeleteTag: []gax.CallOption{}, + SetIamPolicy: []gax.CallOption{}, + GetIamPolicy: []gax.CallOption{}, + TestIamPermissions: []gax.CallOption{}, + GetProjectSettings: []gax.CallOption{}, + UpdateProjectSettings: []gax.CallOption{}, + } +} + // internalClient is an interface that defines the methods available from Artifact Registry API. type internalClient interface { Close() error @@ -506,6 +544,105 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new artifact registry rest client. +// +// The Artifact Registry API service. +// +// Artifact Registry is an artifact management system for storing artifacts +// from different package management systems. +// +// The resources managed by this API are: +// +// Repositories, which group packages and their data. +// +// Packages, which group versions and their tags. +// +// Versions, which are specific forms of a package. +// +// Tags, which represent alternative names for versions. +// +// Files, which contain content and are optionally associated with a Package +// or Version. +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://artifactregistry.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://artifactregistry.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://artifactregistry.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) ListDockerImages(ctx context.Context, req *artifactregistrypb.ListDockerImagesRequest, opts ...gax.CallOption) *DockerImageIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1246,123 +1383,2022 @@ func (c *gRPCClient) UpdateProjectSettings(ctx context.Context, req *artifactreg return resp, nil } -// CreateRepositoryOperation manages a long-running operation from CreateRepository. -type CreateRepositoryOperation struct { - lro *longrunning.Operation -} +// ListDockerImages lists docker images. +func (c *restClient) ListDockerImages(ctx context.Context, req *artifactregistrypb.ListDockerImagesRequest, opts ...gax.CallOption) *DockerImageIterator { + it := &DockerImageIterator{} + req = proto.Clone(req).(*artifactregistrypb.ListDockerImagesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*artifactregistrypb.DockerImage, string, error) { + resp := &artifactregistrypb.ListDockerImagesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/dockerImages", req.GetParent()) -// CreateRepositoryOperation returns a new CreateRepositoryOperation from a given name. -// The name must be that of a previously created CreateRepositoryOperation, possibly from a different process. -func (c *gRPCClient) CreateRepositoryOperation(name string) *CreateRepositoryOperation { - return &CreateRepositoryOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *CreateRepositoryOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*artifactregistrypb.Repository, error) { - var resp artifactregistrypb.Repository - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { - return nil, err + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetDockerImages(), resp.GetNextPageToken(), nil } - return &resp, nil -} -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *CreateRepositoryOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*artifactregistrypb.Repository, error) { - var resp artifactregistrypb.Repository - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { - return nil, err - } - if !op.Done() { - return nil, 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 } - return &resp, nil + + it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it } -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *CreateRepositoryOperation) Metadata() (*artifactregistrypb.OperationMetadata, error) { - var meta artifactregistrypb.OperationMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { +// GetDockerImage gets a docker image. +func (c *restClient) GetDockerImage(ctx context.Context, req *artifactregistrypb.GetDockerImageRequest, opts ...gax.CallOption) (*artifactregistrypb.DockerImage, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - return &meta, nil -} + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) -// Done reports whether the long-running operation has completed. -func (op *CreateRepositoryOperation) Done() bool { - return op.lro.Done() -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") -// 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 *CreateRepositoryOperation) Name() string { - return op.lro.Name() -} + baseUrl.RawQuery = params.Encode() -// DeletePackageOperation manages a long-running operation from DeletePackage. -type DeletePackageOperation struct { - lro *longrunning.Operation -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) -// DeletePackageOperation returns a new DeletePackageOperation from a given name. -// The name must be that of a previously created DeletePackageOperation, possibly from a different process. -func (c *gRPCClient) DeletePackageOperation(name string) *DeletePackageOperation { - return &DeletePackageOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetDockerImage[0:len((*c.CallOptions).GetDockerImage):len((*c.CallOptions).GetDockerImage)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &artifactregistrypb.DockerImage{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *DeletePackageOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { - return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) -} + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *DeletePackageOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { - return op.lro.Poll(ctx, nil, opts...) + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil } -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *DeletePackageOperation) Metadata() (*artifactregistrypb.OperationMetadata, error) { - var meta artifactregistrypb.OperationMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { +// ImportAptArtifacts imports Apt artifacts. The returned Operation will complete once the +// resources are imported. Package, Version, and File resources are created +// based on the imported artifacts. Imported artifacts that conflict with +// existing resources are ignored. +func (c *restClient) ImportAptArtifacts(ctx context.Context, req *artifactregistrypb.ImportAptArtifactsRequest, opts ...gax.CallOption) (*ImportAptArtifactsOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { return nil, err } - return &meta, nil -} -// Done reports whether the long-running operation has completed. + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/aptArtifacts:import", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &ImportAptArtifactsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ImportYumArtifacts imports Yum (RPM) artifacts. The returned Operation will complete once the +// resources are imported. Package, Version, and File resources are created +// based on the imported artifacts. Imported artifacts that conflict with +// existing resources are ignored. +func (c *restClient) ImportYumArtifacts(ctx context.Context, req *artifactregistrypb.ImportYumArtifactsRequest, opts ...gax.CallOption) (*ImportYumArtifactsOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/yumArtifacts:import", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &ImportYumArtifactsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListRepositories lists repositories. +func (c *restClient) ListRepositories(ctx context.Context, req *artifactregistrypb.ListRepositoriesRequest, opts ...gax.CallOption) *RepositoryIterator { + it := &RepositoryIterator{} + req = proto.Clone(req).(*artifactregistrypb.ListRepositoriesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*artifactregistrypb.Repository, string, error) { + resp := &artifactregistrypb.ListRepositoriesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/repositories", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetRepositories(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetRepository gets a repository. +func (c *restClient) GetRepository(ctx context.Context, req *artifactregistrypb.GetRepositoryRequest, opts ...gax.CallOption) (*artifactregistrypb.Repository, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetRepository[0:len((*c.CallOptions).GetRepository):len((*c.CallOptions).GetRepository)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &artifactregistrypb.Repository{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateRepository creates a repository. The returned Operation will finish once the +// repository has been created. Its response will be the created Repository. +func (c *restClient) CreateRepository(ctx context.Context, req *artifactregistrypb.CreateRepositoryRequest, opts ...gax.CallOption) (*CreateRepositoryOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetRepository() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/repositories", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRepositoryId() != "" { + params.Add("repositoryId", fmt.Sprintf("%v", req.GetRepositoryId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateRepositoryOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateRepository updates a repository. +func (c *restClient) UpdateRepository(ctx context.Context, req *artifactregistrypb.UpdateRepositoryRequest, opts ...gax.CallOption) (*artifactregistrypb.Repository, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetRepository() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetRepository().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "repository.name", url.QueryEscape(req.GetRepository().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateRepository[0:len((*c.CallOptions).UpdateRepository):len((*c.CallOptions).UpdateRepository)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &artifactregistrypb.Repository{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteRepository deletes a repository and all of its contents. The returned Operation will +// finish once the repository has been deleted. It will not have any Operation +// metadata and will return a google.protobuf.Empty response. +func (c *restClient) DeleteRepository(ctx context.Context, req *artifactregistrypb.DeleteRepositoryRequest, opts ...gax.CallOption) (*DeleteRepositoryOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteRepositoryOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListPackages lists packages. +func (c *restClient) ListPackages(ctx context.Context, req *artifactregistrypb.ListPackagesRequest, opts ...gax.CallOption) *PackageIterator { + it := &PackageIterator{} + req = proto.Clone(req).(*artifactregistrypb.ListPackagesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*artifactregistrypb.Package, string, error) { + resp := &artifactregistrypb.ListPackagesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/packages", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetPackages(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetPackage gets a package. +func (c *restClient) GetPackage(ctx context.Context, req *artifactregistrypb.GetPackageRequest, opts ...gax.CallOption) (*artifactregistrypb.Package, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetPackage[0:len((*c.CallOptions).GetPackage):len((*c.CallOptions).GetPackage)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &artifactregistrypb.Package{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeletePackage deletes a package and all of its versions and tags. The returned operation +// will complete once the package has been deleted. +func (c *restClient) DeletePackage(ctx context.Context, req *artifactregistrypb.DeletePackageRequest, opts ...gax.CallOption) (*DeletePackageOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeletePackageOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListVersions lists versions. +func (c *restClient) ListVersions(ctx context.Context, req *artifactregistrypb.ListVersionsRequest, opts ...gax.CallOption) *VersionIterator { + it := &VersionIterator{} + req = proto.Clone(req).(*artifactregistrypb.ListVersionsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*artifactregistrypb.Version, string, error) { + resp := &artifactregistrypb.ListVersionsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/versions", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + if req.GetView() != 0 { + params.Add("view", fmt.Sprintf("%v", req.GetView())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetVersions(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetVersion gets a version +func (c *restClient) GetVersion(ctx context.Context, req *artifactregistrypb.GetVersionRequest, opts ...gax.CallOption) (*artifactregistrypb.Version, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetView() != 0 { + params.Add("view", fmt.Sprintf("%v", req.GetView())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetVersion[0:len((*c.CallOptions).GetVersion):len((*c.CallOptions).GetVersion)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &artifactregistrypb.Version{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteVersion deletes a version and all of its content. The returned operation will +// complete once the version has been deleted. +func (c *restClient) DeleteVersion(ctx context.Context, req *artifactregistrypb.DeleteVersionRequest, opts ...gax.CallOption) (*DeleteVersionOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetForce() { + params.Add("force", fmt.Sprintf("%v", req.GetForce())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteVersionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListFiles lists files. +func (c *restClient) ListFiles(ctx context.Context, req *artifactregistrypb.ListFilesRequest, opts ...gax.CallOption) *FileIterator { + it := &FileIterator{} + req = proto.Clone(req).(*artifactregistrypb.ListFilesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*artifactregistrypb.File, string, error) { + resp := &artifactregistrypb.ListFilesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/files", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetFiles(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetFile gets a file. +func (c *restClient) GetFile(ctx context.Context, req *artifactregistrypb.GetFileRequest, opts ...gax.CallOption) (*artifactregistrypb.File, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetFile[0:len((*c.CallOptions).GetFile):len((*c.CallOptions).GetFile)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &artifactregistrypb.File{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListTags lists tags. +func (c *restClient) ListTags(ctx context.Context, req *artifactregistrypb.ListTagsRequest, opts ...gax.CallOption) *TagIterator { + it := &TagIterator{} + req = proto.Clone(req).(*artifactregistrypb.ListTagsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*artifactregistrypb.Tag, string, error) { + resp := &artifactregistrypb.ListTagsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/tags", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetTags(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetTag gets a tag. +func (c *restClient) GetTag(ctx context.Context, req *artifactregistrypb.GetTagRequest, opts ...gax.CallOption) (*artifactregistrypb.Tag, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetTag[0:len((*c.CallOptions).GetTag):len((*c.CallOptions).GetTag)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &artifactregistrypb.Tag{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateTag creates a tag. +func (c *restClient) CreateTag(ctx context.Context, req *artifactregistrypb.CreateTagRequest, opts ...gax.CallOption) (*artifactregistrypb.Tag, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetTag() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/tags", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetTagId() != "" { + params.Add("tagId", fmt.Sprintf("%v", req.GetTagId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateTag[0:len((*c.CallOptions).CreateTag):len((*c.CallOptions).CreateTag)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &artifactregistrypb.Tag{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateTag updates a tag. +func (c *restClient) UpdateTag(ctx context.Context, req *artifactregistrypb.UpdateTagRequest, opts ...gax.CallOption) (*artifactregistrypb.Tag, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetTag() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetTag().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "tag.name", url.QueryEscape(req.GetTag().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateTag[0:len((*c.CallOptions).UpdateTag):len((*c.CallOptions).UpdateTag)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &artifactregistrypb.Tag{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteTag deletes a tag. +func (c *restClient) DeleteTag(ctx context.Context, req *artifactregistrypb.DeleteTagRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// SetIamPolicy updates the IAM policy for a given resource. +func (c *restClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:setIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetIamPolicy gets the IAM policy for a given resource. +func (c *restClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:getIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetOptions().GetRequestedPolicyVersion() != 0 { + params.Add("options.requestedPolicyVersion", fmt.Sprintf("%v", req.GetOptions().GetRequestedPolicyVersion())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// TestIamPermissions tests if the caller has a list of permissions on a resource. +func (c *restClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:testIamPermissions", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.TestIamPermissionsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetProjectSettings retrieves the Settings for the Project. +func (c *restClient) GetProjectSettings(ctx context.Context, req *artifactregistrypb.GetProjectSettingsRequest, opts ...gax.CallOption) (*artifactregistrypb.ProjectSettings, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetProjectSettings[0:len((*c.CallOptions).GetProjectSettings):len((*c.CallOptions).GetProjectSettings)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &artifactregistrypb.ProjectSettings{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateProjectSettings updates the Settings for the Project. +func (c *restClient) UpdateProjectSettings(ctx context.Context, req *artifactregistrypb.UpdateProjectSettingsRequest, opts ...gax.CallOption) (*artifactregistrypb.ProjectSettings, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetProjectSettings() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetProjectSettings().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "project_settings.name", url.QueryEscape(req.GetProjectSettings().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateProjectSettings[0:len((*c.CallOptions).UpdateProjectSettings):len((*c.CallOptions).UpdateProjectSettings)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &artifactregistrypb.ProjectSettings{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateRepositoryOperation manages a long-running operation from CreateRepository. +type CreateRepositoryOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateRepositoryOperation returns a new CreateRepositoryOperation from a given name. +// The name must be that of a previously created CreateRepositoryOperation, possibly from a different process. +func (c *gRPCClient) CreateRepositoryOperation(name string) *CreateRepositoryOperation { + return &CreateRepositoryOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateRepositoryOperation returns a new CreateRepositoryOperation from a given name. +// The name must be that of a previously created CreateRepositoryOperation, possibly from a different process. +func (c *restClient) CreateRepositoryOperation(name string) *CreateRepositoryOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateRepositoryOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CreateRepositoryOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*artifactregistrypb.Repository, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp artifactregistrypb.Repository + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *CreateRepositoryOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*artifactregistrypb.Repository, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp artifactregistrypb.Repository + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *CreateRepositoryOperation) Metadata() (*artifactregistrypb.OperationMetadata, error) { + var meta artifactregistrypb.OperationMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *CreateRepositoryOperation) Done() bool { + return op.lro.Done() +} + +// 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 *CreateRepositoryOperation) Name() string { + return op.lro.Name() +} + +// DeletePackageOperation manages a long-running operation from DeletePackage. +type DeletePackageOperation struct { + lro *longrunning.Operation + pollPath string +} + +// DeletePackageOperation returns a new DeletePackageOperation from a given name. +// The name must be that of a previously created DeletePackageOperation, possibly from a different process. +func (c *gRPCClient) DeletePackageOperation(name string) *DeletePackageOperation { + return &DeletePackageOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// DeletePackageOperation returns a new DeletePackageOperation from a given name. +// The name must be that of a previously created DeletePackageOperation, possibly from a different process. +func (c *restClient) DeletePackageOperation(name string) *DeletePackageOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeletePackageOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *DeletePackageOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *DeletePackageOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + return op.lro.Poll(ctx, nil, opts...) +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *DeletePackageOperation) Metadata() (*artifactregistrypb.OperationMetadata, error) { + var meta artifactregistrypb.OperationMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. func (op *DeletePackageOperation) Done() bool { return op.lro.Done() } @@ -1375,7 +3411,8 @@ func (op *DeletePackageOperation) Name() string { // DeleteRepositoryOperation manages a long-running operation from DeleteRepository. type DeleteRepositoryOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteRepositoryOperation returns a new DeleteRepositoryOperation from a given name. @@ -1386,10 +3423,21 @@ func (c *gRPCClient) DeleteRepositoryOperation(name string) *DeleteRepositoryOpe } } +// DeleteRepositoryOperation returns a new DeleteRepositoryOperation from a given name. +// The name must be that of a previously created DeleteRepositoryOperation, possibly from a different process. +func (c *restClient) DeleteRepositoryOperation(name string) *DeleteRepositoryOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteRepositoryOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteRepositoryOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -1403,6 +3451,7 @@ func (op *DeleteRepositoryOperation) Wait(ctx context.Context, opts ...gax.CallO // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteRepositoryOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -1433,7 +3482,8 @@ func (op *DeleteRepositoryOperation) Name() string { // DeleteVersionOperation manages a long-running operation from DeleteVersion. type DeleteVersionOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteVersionOperation returns a new DeleteVersionOperation from a given name. @@ -1444,10 +3494,21 @@ func (c *gRPCClient) DeleteVersionOperation(name string) *DeleteVersionOperation } } +// DeleteVersionOperation returns a new DeleteVersionOperation from a given name. +// The name must be that of a previously created DeleteVersionOperation, possibly from a different process. +func (c *restClient) DeleteVersionOperation(name string) *DeleteVersionOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteVersionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteVersionOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -1461,6 +3522,7 @@ func (op *DeleteVersionOperation) Wait(ctx context.Context, opts ...gax.CallOpti // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteVersionOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -1491,7 +3553,8 @@ func (op *DeleteVersionOperation) Name() string { // ImportAptArtifactsOperation manages a long-running operation from ImportAptArtifacts. type ImportAptArtifactsOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // ImportAptArtifactsOperation returns a new ImportAptArtifactsOperation from a given name. @@ -1502,10 +3565,21 @@ func (c *gRPCClient) ImportAptArtifactsOperation(name string) *ImportAptArtifact } } +// ImportAptArtifactsOperation returns a new ImportAptArtifactsOperation from a given name. +// The name must be that of a previously created ImportAptArtifactsOperation, possibly from a different process. +func (c *restClient) ImportAptArtifactsOperation(name string) *ImportAptArtifactsOperation { + override := fmt.Sprintf("/v1/%s", name) + return &ImportAptArtifactsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *ImportAptArtifactsOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*artifactregistrypb.ImportAptArtifactsResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp artifactregistrypb.ImportAptArtifactsResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1523,6 +3597,7 @@ func (op *ImportAptArtifactsOperation) Wait(ctx context.Context, opts ...gax.Cal // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *ImportAptArtifactsOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*artifactregistrypb.ImportAptArtifactsResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp artifactregistrypb.ImportAptArtifactsResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1560,7 +3635,8 @@ func (op *ImportAptArtifactsOperation) Name() string { // ImportYumArtifactsOperation manages a long-running operation from ImportYumArtifacts. type ImportYumArtifactsOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // ImportYumArtifactsOperation returns a new ImportYumArtifactsOperation from a given name. @@ -1571,10 +3647,21 @@ func (c *gRPCClient) ImportYumArtifactsOperation(name string) *ImportYumArtifact } } +// ImportYumArtifactsOperation returns a new ImportYumArtifactsOperation from a given name. +// The name must be that of a previously created ImportYumArtifactsOperation, possibly from a different process. +func (c *restClient) ImportYumArtifactsOperation(name string) *ImportYumArtifactsOperation { + override := fmt.Sprintf("/v1/%s", name) + return &ImportYumArtifactsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *ImportYumArtifactsOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*artifactregistrypb.ImportYumArtifactsResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp artifactregistrypb.ImportYumArtifactsResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1592,6 +3679,7 @@ func (op *ImportYumArtifactsOperation) Wait(ctx context.Context, opts ...gax.Cal // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *ImportYumArtifactsOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*artifactregistrypb.ImportYumArtifactsResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp artifactregistrypb.ImportYumArtifactsResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/artifactregistry/apiv1/artifact_registry_client_example_test.go b/artifactregistry/apiv1/artifact_registry_client_example_test.go index 5443a4927acc..b62ddf422f3d 100644 --- a/artifactregistry/apiv1/artifact_registry_client_example_test.go +++ b/artifactregistry/apiv1/artifact_registry_client_example_test.go @@ -42,6 +42,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := artifactregistry.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_ListDockerImages() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/artifactregistry/apiv1/artifactregistrypb/apt_artifact.pb.go b/artifactregistry/apiv1/artifactregistrypb/apt_artifact.pb.go index 3589ba0d1350..baec1a1cddc7 100644 --- a/artifactregistry/apiv1/artifactregistrypb/apt_artifact.pb.go +++ b/artifactregistry/apiv1/artifactregistrypb/apt_artifact.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/devtools/artifactregistry/v1/apt_artifact.proto package artifactregistrypb @@ -253,7 +253,6 @@ type ImportAptArtifactsRequest struct { // The source location of the package binaries. // // Types that are assignable to Source: - // // *ImportAptArtifactsRequest_GcsSource Source isImportAptArtifactsRequest_Source `protobuf_oneof:"source"` // The name of the parent resource where the artifacts will be imported. @@ -333,7 +332,6 @@ type ImportAptArtifactsErrorInfo struct { // The source that was not imported. // // Types that are assignable to Source: - // // *ImportAptArtifactsErrorInfo_GcsSource Source isImportAptArtifactsErrorInfo_Source `protobuf_oneof:"source"` // The detailed error status. diff --git a/artifactregistry/apiv1/artifactregistrypb/artifact.pb.go b/artifactregistry/apiv1/artifactregistrypb/artifact.pb.go index 69ad4b68c7dc..9130cb473f96 100644 --- a/artifactregistry/apiv1/artifactregistrypb/artifact.pb.go +++ b/artifactregistry/apiv1/artifactregistrypb/artifact.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/devtools/artifactregistry/v1/artifact.proto package artifactregistrypb diff --git a/artifactregistry/apiv1/artifactregistrypb/file.pb.go b/artifactregistry/apiv1/artifactregistrypb/file.pb.go index 7883afc4607f..7d493fee4675 100644 --- a/artifactregistry/apiv1/artifactregistrypb/file.pb.go +++ b/artifactregistry/apiv1/artifactregistrypb/file.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/devtools/artifactregistry/v1/file.proto package artifactregistrypb @@ -256,17 +256,15 @@ type ListFilesRequest struct { // An expression for filtering the results of the request. Filter rules are // case insensitive. The fields eligible for filtering are: // - // - `name` + // * `name` + // * `owner` // - // - `owner` + // An example of using a filter: // - // An example of using a filter: - // - // - `name="projects/p1/locations/us-central1/repositories/repo1/files/a/b/*"` --> Files with an - // ID starting with "a/b/". - // - // - `owner="projects/p1/locations/us-central1/repositories/repo1/packages/pkg1/versions/1.0"` --> - // Files owned by the version `1.0` in package `pkg1`. + // * `name="projects/p1/locations/us-central1/repositories/repo1/files/a/b/*"` --> Files with an + // ID starting with "a/b/". + // * `owner="projects/p1/locations/us-central1/repositories/repo1/packages/pkg1/versions/1.0"` --> + // Files owned by the version `1.0` in package `pkg1`. Filter string `protobuf:"bytes,4,opt,name=filter,proto3" json:"filter,omitempty"` // The maximum number of files to return. PageSize int32 `protobuf:"varint,2,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"` diff --git a/artifactregistry/apiv1/artifactregistrypb/package.pb.go b/artifactregistry/apiv1/artifactregistrypb/package.pb.go index 1ed1731b5f99..82857a9be7cd 100644 --- a/artifactregistry/apiv1/artifactregistrypb/package.pb.go +++ b/artifactregistry/apiv1/artifactregistrypb/package.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/devtools/artifactregistry/v1/package.proto package artifactregistrypb diff --git a/artifactregistry/apiv1/artifactregistrypb/repository.pb.go b/artifactregistry/apiv1/artifactregistrypb/repository.pb.go index 448803e2e245..a33f9a4c8b19 100644 --- a/artifactregistry/apiv1/artifactregistrypb/repository.pb.go +++ b/artifactregistry/apiv1/artifactregistrypb/repository.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/devtools/artifactregistry/v1/repository.proto package artifactregistrypb @@ -171,7 +171,6 @@ type Repository struct { // Repository-specific configurations. // // Types that are assignable to FormatConfig: - // // *Repository_MavenConfig FormatConfig isRepository_FormatConfig `protobuf_oneof:"format_config"` // The name of the repository, for example: diff --git a/artifactregistry/apiv1/artifactregistrypb/service.pb.go b/artifactregistry/apiv1/artifactregistrypb/service.pb.go index fa047027c4f4..6248dc27a787 100644 --- a/artifactregistry/apiv1/artifactregistrypb/service.pb.go +++ b/artifactregistry/apiv1/artifactregistrypb/service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/devtools/artifactregistry/v1/service.proto package artifactregistrypb diff --git a/artifactregistry/apiv1/artifactregistrypb/settings.pb.go b/artifactregistry/apiv1/artifactregistrypb/settings.pb.go index 24fde8134355..0dc5f4142788 100644 --- a/artifactregistry/apiv1/artifactregistrypb/settings.pb.go +++ b/artifactregistry/apiv1/artifactregistrypb/settings.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/devtools/artifactregistry/v1/settings.proto package artifactregistrypb diff --git a/artifactregistry/apiv1/artifactregistrypb/tag.pb.go b/artifactregistry/apiv1/artifactregistrypb/tag.pb.go index 0722fec0961c..1833c2a6d07d 100644 --- a/artifactregistry/apiv1/artifactregistrypb/tag.pb.go +++ b/artifactregistry/apiv1/artifactregistrypb/tag.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/devtools/artifactregistry/v1/tag.proto package artifactregistrypb @@ -114,12 +114,12 @@ type ListTagsRequest struct { // An expression for filtering the results of the request. Filter rules are // case insensitive. The fields eligible for filtering are: // - // - `version` + // * `version` // - // An example of using a filter: + // An example of using a filter: // - // - `version="projects/p1/locations/us-central1/repositories/repo1/packages/pkg1/versions/1.0"` - // --> Tags that are applied to the version `1.0` in package `pkg1`. + // * `version="projects/p1/locations/us-central1/repositories/repo1/packages/pkg1/versions/1.0"` + // --> Tags that are applied to the version `1.0` in package `pkg1`. Filter string `protobuf:"bytes,4,opt,name=filter,proto3" json:"filter,omitempty"` // The maximum number of tags to return. Maximum page size is 10,000. PageSize int32 `protobuf:"varint,2,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"` diff --git a/artifactregistry/apiv1/artifactregistrypb/version.pb.go b/artifactregistry/apiv1/artifactregistrypb/version.pb.go index 3e5331f2371d..369a2e47960a 100644 --- a/artifactregistry/apiv1/artifactregistrypb/version.pb.go +++ b/artifactregistry/apiv1/artifactregistrypb/version.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/devtools/artifactregistry/v1/version.proto package artifactregistrypb diff --git a/artifactregistry/apiv1/artifactregistrypb/yum_artifact.pb.go b/artifactregistry/apiv1/artifactregistrypb/yum_artifact.pb.go index c7c307bb4335..747c0d641c63 100644 --- a/artifactregistry/apiv1/artifactregistrypb/yum_artifact.pb.go +++ b/artifactregistry/apiv1/artifactregistrypb/yum_artifact.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/devtools/artifactregistry/v1/yum_artifact.proto package artifactregistrypb @@ -233,7 +233,6 @@ type ImportYumArtifactsRequest struct { // The source location of the package binaries. // // Types that are assignable to Source: - // // *ImportYumArtifactsRequest_GcsSource Source isImportYumArtifactsRequest_Source `protobuf_oneof:"source"` // The name of the parent resource where the artifacts will be imported. @@ -313,7 +312,6 @@ type ImportYumArtifactsErrorInfo struct { // The source that was not imported. // // Types that are assignable to Source: - // // *ImportYumArtifactsErrorInfo_GcsSource Source isImportYumArtifactsErrorInfo_Source `protobuf_oneof:"source"` // The detailed error status. diff --git a/artifactregistry/apiv1/doc.go b/artifactregistry/apiv1/doc.go index d072a40fcd3f..787818247be4 100644 --- a/artifactregistry/apiv1/doc.go +++ b/artifactregistry/apiv1/doc.go @@ -89,6 +89,8 @@ package artifactregistry // import "cloud.google.com/go/artifactregistry/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -178,3 +180,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/artifactregistry/apiv1/gapic_metadata.json b/artifactregistry/apiv1/gapic_metadata.json index a2a38b874a0a..61fed40479df 100644 --- a/artifactregistry/apiv1/gapic_metadata.json +++ b/artifactregistry/apiv1/gapic_metadata.json @@ -146,6 +146,146 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "CreateRepository": { + "methods": [ + "CreateRepository" + ] + }, + "CreateTag": { + "methods": [ + "CreateTag" + ] + }, + "DeletePackage": { + "methods": [ + "DeletePackage" + ] + }, + "DeleteRepository": { + "methods": [ + "DeleteRepository" + ] + }, + "DeleteTag": { + "methods": [ + "DeleteTag" + ] + }, + "DeleteVersion": { + "methods": [ + "DeleteVersion" + ] + }, + "GetDockerImage": { + "methods": [ + "GetDockerImage" + ] + }, + "GetFile": { + "methods": [ + "GetFile" + ] + }, + "GetIamPolicy": { + "methods": [ + "GetIamPolicy" + ] + }, + "GetPackage": { + "methods": [ + "GetPackage" + ] + }, + "GetProjectSettings": { + "methods": [ + "GetProjectSettings" + ] + }, + "GetRepository": { + "methods": [ + "GetRepository" + ] + }, + "GetTag": { + "methods": [ + "GetTag" + ] + }, + "GetVersion": { + "methods": [ + "GetVersion" + ] + }, + "ImportAptArtifacts": { + "methods": [ + "ImportAptArtifacts" + ] + }, + "ImportYumArtifacts": { + "methods": [ + "ImportYumArtifacts" + ] + }, + "ListDockerImages": { + "methods": [ + "ListDockerImages" + ] + }, + "ListFiles": { + "methods": [ + "ListFiles" + ] + }, + "ListPackages": { + "methods": [ + "ListPackages" + ] + }, + "ListRepositories": { + "methods": [ + "ListRepositories" + ] + }, + "ListTags": { + "methods": [ + "ListTags" + ] + }, + "ListVersions": { + "methods": [ + "ListVersions" + ] + }, + "SetIamPolicy": { + "methods": [ + "SetIamPolicy" + ] + }, + "TestIamPermissions": { + "methods": [ + "TestIamPermissions" + ] + }, + "UpdateProjectSettings": { + "methods": [ + "UpdateProjectSettings" + ] + }, + "UpdateRepository": { + "methods": [ + "UpdateRepository" + ] + }, + "UpdateTag": { + "methods": [ + "UpdateTag" + ] + } + } } } } diff --git a/artifactregistry/apiv1beta2/artifact_registry_client.go b/artifactregistry/apiv1beta2/artifact_registry_client.go index 44d93e7adb63..3e1cb22fa4a6 100644 --- a/artifactregistry/apiv1beta2/artifact_registry_client.go +++ b/artifactregistry/apiv1beta2/artifact_registry_client.go @@ -1576,6 +1576,11 @@ func (c *restClient) ImportAptArtifacts(ctx context.Context, req *artifactregist } baseUrl.Path += fmt.Sprintf("/v1beta2/%v/aptArtifacts:import", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1642,6 +1647,11 @@ func (c *restClient) ImportYumArtifacts(ctx context.Context, req *artifactregist } baseUrl.Path += fmt.Sprintf("/v1beta2/%v/yumArtifacts:import", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1713,6 +1723,7 @@ func (c *restClient) ListRepositories(ctx context.Context, req *artifactregistry baseUrl.Path += fmt.Sprintf("/v1beta2/%v/repositories", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -1786,6 +1797,11 @@ func (c *restClient) GetRepository(ctx context.Context, req *artifactregistrypb. } baseUrl.Path += fmt.Sprintf("/v1beta2/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1848,6 +1864,7 @@ func (c *restClient) CreateRepository(ctx context.Context, req *artifactregistry baseUrl.Path += fmt.Sprintf("/v1beta2/%v/repositories", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetRepositoryId() != "" { params.Add("repositoryId", fmt.Sprintf("%v", req.GetRepositoryId())) } @@ -1919,6 +1936,7 @@ func (c *restClient) UpdateRepository(ctx context.Context, req *artifactregistry baseUrl.Path += fmt.Sprintf("/v1beta2/%v", req.GetRepository().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -1984,6 +2002,11 @@ func (c *restClient) DeleteRepository(ctx context.Context, req *artifactregistry } baseUrl.Path += fmt.Sprintf("/v1beta2/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2055,6 +2078,7 @@ func (c *restClient) ListPackages(ctx context.Context, req *artifactregistrypb.L baseUrl.Path += fmt.Sprintf("/v1beta2/%v/packages", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -2128,6 +2152,11 @@ func (c *restClient) GetPackage(ctx context.Context, req *artifactregistrypb.Get } baseUrl.Path += fmt.Sprintf("/v1beta2/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2182,6 +2211,11 @@ func (c *restClient) DeletePackage(ctx context.Context, req *artifactregistrypb. } baseUrl.Path += fmt.Sprintf("/v1beta2/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2253,6 +2287,7 @@ func (c *restClient) ListVersions(ctx context.Context, req *artifactregistrypb.L baseUrl.Path += fmt.Sprintf("/v1beta2/%v/versions", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetOrderBy() != "" { params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) } @@ -2333,6 +2368,7 @@ func (c *restClient) GetVersion(ctx context.Context, req *artifactregistrypb.Get baseUrl.Path += fmt.Sprintf("/v1beta2/%v", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetView() != 0 { params.Add("view", fmt.Sprintf("%v", req.GetView())) } @@ -2394,6 +2430,7 @@ func (c *restClient) DeleteVersion(ctx context.Context, req *artifactregistrypb. baseUrl.Path += fmt.Sprintf("/v1beta2/%v", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetForce() { params.Add("force", fmt.Sprintf("%v", req.GetForce())) } @@ -2471,6 +2508,7 @@ func (c *restClient) ListFiles(ctx context.Context, req *artifactregistrypb.List baseUrl.Path += fmt.Sprintf("/v1beta2/%v/files", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -2547,6 +2585,11 @@ func (c *restClient) GetFile(ctx context.Context, req *artifactregistrypb.GetFil } baseUrl.Path += fmt.Sprintf("/v1beta2/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2614,6 +2657,7 @@ func (c *restClient) ListTags(ctx context.Context, req *artifactregistrypb.ListT baseUrl.Path += fmt.Sprintf("/v1beta2/%v/tags", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -2690,6 +2734,11 @@ func (c *restClient) GetTag(ctx context.Context, req *artifactregistrypb.GetTagR } baseUrl.Path += fmt.Sprintf("/v1beta2/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2751,6 +2800,7 @@ func (c *restClient) CreateTag(ctx context.Context, req *artifactregistrypb.Crea baseUrl.Path += fmt.Sprintf("/v1beta2/%v/tags", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetTagId() != "" { params.Add("tagId", fmt.Sprintf("%v", req.GetTagId())) } @@ -2818,6 +2868,7 @@ func (c *restClient) UpdateTag(ctx context.Context, req *artifactregistrypb.Upda baseUrl.Path += fmt.Sprintf("/v1beta2/%v", req.GetTag().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -2881,6 +2932,11 @@ func (c *restClient) DeleteTag(ctx context.Context, req *artifactregistrypb.Dele } baseUrl.Path += fmt.Sprintf("/v1beta2/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2922,6 +2978,11 @@ func (c *restClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRe } baseUrl.Path += fmt.Sprintf("/v1beta2/%v:setIamPolicy", req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) @@ -2976,6 +3037,7 @@ func (c *restClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRe baseUrl.Path += fmt.Sprintf("/v1beta2/%v:getIamPolicy", req.GetResource()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetOptions().GetRequestedPolicyVersion() != 0 { params.Add("options.requestedPolicyVersion", fmt.Sprintf("%v", req.GetOptions().GetRequestedPolicyVersion())) } @@ -3041,6 +3103,11 @@ func (c *restClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamP } baseUrl.Path += fmt.Sprintf("/v1beta2/%v:testIamPermissions", req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) @@ -3094,6 +3161,11 @@ func (c *restClient) GetProjectSettings(ctx context.Context, req *artifactregist } baseUrl.Path += fmt.Sprintf("/v1beta2/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -3155,6 +3227,7 @@ func (c *restClient) UpdateProjectSettings(ctx context.Context, req *artifactreg baseUrl.Path += fmt.Sprintf("/v1beta2/%v", req.GetProjectSettings().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { diff --git a/artifactregistry/apiv1beta2/artifactregistrypb/apt_artifact.pb.go b/artifactregistry/apiv1beta2/artifactregistrypb/apt_artifact.pb.go index bae0eb2e7695..1abcf9d5ebb0 100644 --- a/artifactregistry/apiv1beta2/artifactregistrypb/apt_artifact.pb.go +++ b/artifactregistry/apiv1beta2/artifactregistrypb/apt_artifact.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/devtools/artifactregistry/v1beta2/apt_artifact.proto package artifactregistrypb @@ -253,7 +253,6 @@ type ImportAptArtifactsRequest struct { // The source location of the package binaries. // // Types that are assignable to Source: - // // *ImportAptArtifactsRequest_GcsSource Source isImportAptArtifactsRequest_Source `protobuf_oneof:"source"` // The name of the parent resource where the artifacts will be imported. @@ -333,7 +332,6 @@ type ImportAptArtifactsErrorInfo struct { // The source that was not imported. // // Types that are assignable to Source: - // // *ImportAptArtifactsErrorInfo_GcsSource Source isImportAptArtifactsErrorInfo_Source `protobuf_oneof:"source"` // The detailed error status. diff --git a/artifactregistry/apiv1beta2/artifactregistrypb/file.pb.go b/artifactregistry/apiv1beta2/artifactregistrypb/file.pb.go index 9b440904f8b5..eab397b01679 100644 --- a/artifactregistry/apiv1beta2/artifactregistrypb/file.pb.go +++ b/artifactregistry/apiv1beta2/artifactregistrypb/file.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/devtools/artifactregistry/v1beta2/file.proto package artifactregistrypb @@ -256,17 +256,15 @@ type ListFilesRequest struct { // An expression for filtering the results of the request. Filter rules are // case insensitive. The fields eligible for filtering are: // - // - `name` + // * `name` + // * `owner` // - // - `owner` + // An example of using a filter: // - // An example of using a filter: - // - // - `name="projects/p1/locations/us-central1/repositories/repo1/files/a/b/*"` --> Files with an - // ID starting with "a/b/". - // - // - `owner="projects/p1/locations/us-central1/repositories/repo1/packages/pkg1/versions/1.0"` --> - // Files owned by the version `1.0` in package `pkg1`. + // * `name="projects/p1/locations/us-central1/repositories/repo1/files/a/b/*"` --> Files with an + // ID starting with "a/b/". + // * `owner="projects/p1/locations/us-central1/repositories/repo1/packages/pkg1/versions/1.0"` --> + // Files owned by the version `1.0` in package `pkg1`. Filter string `protobuf:"bytes,4,opt,name=filter,proto3" json:"filter,omitempty"` // The maximum number of files to return. PageSize int32 `protobuf:"varint,2,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"` diff --git a/artifactregistry/apiv1beta2/artifactregistrypb/package.pb.go b/artifactregistry/apiv1beta2/artifactregistrypb/package.pb.go index 53fea470b84a..fb87dc2b4874 100644 --- a/artifactregistry/apiv1beta2/artifactregistrypb/package.pb.go +++ b/artifactregistry/apiv1beta2/artifactregistrypb/package.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/devtools/artifactregistry/v1beta2/package.proto package artifactregistrypb diff --git a/artifactregistry/apiv1beta2/artifactregistrypb/repository.pb.go b/artifactregistry/apiv1beta2/artifactregistrypb/repository.pb.go index 9ab5aa68f799..0b7ccac82881 100644 --- a/artifactregistry/apiv1beta2/artifactregistrypb/repository.pb.go +++ b/artifactregistry/apiv1beta2/artifactregistrypb/repository.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/devtools/artifactregistry/v1beta2/repository.proto package artifactregistrypb @@ -171,7 +171,6 @@ type Repository struct { // Repository-specific configurations. // // Types that are assignable to FormatConfig: - // // *Repository_MavenConfig FormatConfig isRepository_FormatConfig `protobuf_oneof:"format_config"` // The name of the repository, for example: diff --git a/artifactregistry/apiv1beta2/artifactregistrypb/service.pb.go b/artifactregistry/apiv1beta2/artifactregistrypb/service.pb.go index 858b2493f758..54b9335118f4 100644 --- a/artifactregistry/apiv1beta2/artifactregistrypb/service.pb.go +++ b/artifactregistry/apiv1beta2/artifactregistrypb/service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/devtools/artifactregistry/v1beta2/service.proto package artifactregistrypb diff --git a/artifactregistry/apiv1beta2/artifactregistrypb/settings.pb.go b/artifactregistry/apiv1beta2/artifactregistrypb/settings.pb.go index e2aea7e2f608..09f41d594ef1 100644 --- a/artifactregistry/apiv1beta2/artifactregistrypb/settings.pb.go +++ b/artifactregistry/apiv1beta2/artifactregistrypb/settings.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/devtools/artifactregistry/v1beta2/settings.proto package artifactregistrypb diff --git a/artifactregistry/apiv1beta2/artifactregistrypb/tag.pb.go b/artifactregistry/apiv1beta2/artifactregistrypb/tag.pb.go index d3bc5b069071..b8f1e094e5b9 100644 --- a/artifactregistry/apiv1beta2/artifactregistrypb/tag.pb.go +++ b/artifactregistry/apiv1beta2/artifactregistrypb/tag.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/devtools/artifactregistry/v1beta2/tag.proto package artifactregistrypb @@ -114,12 +114,12 @@ type ListTagsRequest struct { // An expression for filtering the results of the request. Filter rules are // case insensitive. The fields eligible for filtering are: // - // - `version` + // * `version` // - // An example of using a filter: + // An example of using a filter: // - // - `version="projects/p1/locations/us-central1/repositories/repo1/packages/pkg1/versions/1.0"` - // --> Tags that are applied to the version `1.0` in package `pkg1`. + // * `version="projects/p1/locations/us-central1/repositories/repo1/packages/pkg1/versions/1.0"` + // --> Tags that are applied to the version `1.0` in package `pkg1`. Filter string `protobuf:"bytes,4,opt,name=filter,proto3" json:"filter,omitempty"` // The maximum number of tags to return. Maximum page size is 10,000. PageSize int32 `protobuf:"varint,2,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"` diff --git a/artifactregistry/apiv1beta2/artifactregistrypb/version.pb.go b/artifactregistry/apiv1beta2/artifactregistrypb/version.pb.go index 0024ee46d0d7..b56285b68f68 100644 --- a/artifactregistry/apiv1beta2/artifactregistrypb/version.pb.go +++ b/artifactregistry/apiv1beta2/artifactregistrypb/version.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/devtools/artifactregistry/v1beta2/version.proto package artifactregistrypb diff --git a/artifactregistry/apiv1beta2/artifactregistrypb/yum_artifact.pb.go b/artifactregistry/apiv1beta2/artifactregistrypb/yum_artifact.pb.go index 33be83a4a2f4..0b8680a873c7 100644 --- a/artifactregistry/apiv1beta2/artifactregistrypb/yum_artifact.pb.go +++ b/artifactregistry/apiv1beta2/artifactregistrypb/yum_artifact.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/devtools/artifactregistry/v1beta2/yum_artifact.proto package artifactregistrypb @@ -233,7 +233,6 @@ type ImportYumArtifactsRequest struct { // The source location of the package binaries. // // Types that are assignable to Source: - // // *ImportYumArtifactsRequest_GcsSource Source isImportYumArtifactsRequest_Source `protobuf_oneof:"source"` // The name of the parent resource where the artifacts will be imported. @@ -313,7 +312,6 @@ type ImportYumArtifactsErrorInfo struct { // The source that was not imported. // // Types that are assignable to Source: - // // *ImportYumArtifactsErrorInfo_GcsSource Source isImportYumArtifactsErrorInfo_Source `protobuf_oneof:"source"` // The detailed error status. diff --git a/asset/apiv1/asset_client.go b/asset/apiv1/asset_client.go index edb9cd0cce72..ba5a75b82601 100644 --- a/asset/apiv1/asset_client.go +++ b/asset/apiv1/asset_client.go @@ -17,9 +17,12 @@ package asset import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,14 +30,17 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -241,6 +247,157 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + ExportAssets: []gax.CallOption{}, + ListAssets: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + BatchGetAssetsHistory: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + CreateFeed: []gax.CallOption{}, + GetFeed: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + ListFeeds: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + UpdateFeed: []gax.CallOption{}, + DeleteFeed: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + SearchAllResources: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + SearchAllIamPolicies: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + AnalyzeIamPolicy: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + AnalyzeIamPolicyLongrunning: []gax.CallOption{}, + AnalyzeMove: []gax.CallOption{}, + QueryAssets: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateSavedQuery: []gax.CallOption{}, + GetSavedQuery: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + ListSavedQueries: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + UpdateSavedQuery: []gax.CallOption{}, + DeleteSavedQuery: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + BatchGetEffectiveIamPolicies: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetOperation: []gax.CallOption{}, + } +} + // internalClient is an interface that defines the methods available from Cloud Asset API. type internalClient interface { Close() error @@ -577,6 +734,89 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new asset service rest client. +// +// Asset service definition. +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://cloudasset.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://cloudasset.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://cloudasset.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) ExportAssets(ctx context.Context, req *assetpb.ExportAssetsRequest, opts ...gax.CallOption) (*ExportAssetsOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) @@ -1117,85 +1357,1655 @@ func (c *gRPCClient) GetOperation(ctx context.Context, req *longrunningpb.GetOpe return resp, nil } -// AnalyzeIamPolicyLongrunningOperation manages a long-running operation from AnalyzeIamPolicyLongrunning. -type AnalyzeIamPolicyLongrunningOperation struct { - lro *longrunning.Operation -} - -// AnalyzeIamPolicyLongrunningOperation returns a new AnalyzeIamPolicyLongrunningOperation from a given name. -// The name must be that of a previously created AnalyzeIamPolicyLongrunningOperation, possibly from a different process. -func (c *gRPCClient) AnalyzeIamPolicyLongrunningOperation(name string) *AnalyzeIamPolicyLongrunningOperation { - return &AnalyzeIamPolicyLongrunningOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} - -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *AnalyzeIamPolicyLongrunningOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*assetpb.AnalyzeIamPolicyLongrunningResponse, error) { - var resp assetpb.AnalyzeIamPolicyLongrunningResponse - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { +// ExportAssets exports assets with time and resource types to a given Cloud Storage +// location/BigQuery table. For Cloud Storage location destinations, the +// output format is newline-delimited JSON. Each line represents a +// google.cloud.asset.v1.Asset in the JSON format; for BigQuery table +// destinations, the output table stores the fields in asset Protobuf as +// columns. This API implements the google.longrunning.Operation API, +// which allows you to keep track of the export. We recommend intervals of at +// least 2 seconds with exponential retry to poll the export operation result. +// For regular-size resource parent, the export operation usually finishes +// within 5 minutes. +func (c *restClient) ExportAssets(ctx context.Context, req *assetpb.ExportAssetsRequest, opts ...gax.CallOption) (*ExportAssetsOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { return nil, err } - return &resp, nil -} -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *AnalyzeIamPolicyLongrunningOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*assetpb.AnalyzeIamPolicyLongrunningResponse, error) { - var resp assetpb.AnalyzeIamPolicyLongrunningResponse - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - if !op.Done() { - return nil, nil - } - return &resp, nil -} + baseUrl.Path += fmt.Sprintf("/v1/%v:exportAssets", req.GetParent()) -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *AnalyzeIamPolicyLongrunningOperation) Metadata() (*assetpb.AnalyzeIamPolicyLongrunningMetadata, error) { - var meta assetpb.AnalyzeIamPolicyLongrunningMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { - return nil, err - } - return &meta, nil -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") -// Done reports whether the long-running operation has completed. -func (op *AnalyzeIamPolicyLongrunningOperation) Done() bool { - return op.lro.Done() -} + baseUrl.RawQuery = params.Encode() -// 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 *AnalyzeIamPolicyLongrunningOperation) Name() string { - return op.lro.Name() -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) -// ExportAssetsOperation manages a long-running operation from ExportAssets. -type ExportAssetsOperation struct { - lro *longrunning.Operation -} + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers -// ExportAssetsOperation returns a new ExportAssetsOperation from a given name. -// The name must be that of a previously created ExportAssetsOperation, possibly from a different process. -func (c *gRPCClient) ExportAssetsOperation(name string) *ExportAssetsOperation { + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) return &ExportAssetsOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListAssets lists assets with time and resource types and returns paged results in +// response. +func (c *restClient) ListAssets(ctx context.Context, req *assetpb.ListAssetsRequest, opts ...gax.CallOption) *AssetIterator { + it := &AssetIterator{} + req = proto.Clone(req).(*assetpb.ListAssetsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*assetpb.Asset, string, error) { + resp := &assetpb.ListAssetsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/assets", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if items := req.GetAssetTypes(); len(items) > 0 { + for _, item := range items { + params.Add("assetTypes", fmt.Sprintf("%v", item)) + } + } + if req.GetContentType() != 0 { + params.Add("contentType", fmt.Sprintf("%v", req.GetContentType())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + if req.GetReadTime() != nil { + readTime, err := protojson.Marshal(req.GetReadTime()) + if err != nil { + return nil, "", err + } + params.Add("readTime", string(readTime)) + } + if items := req.GetRelationshipTypes(); len(items) > 0 { + for _, item := range items { + params.Add("relationshipTypes", fmt.Sprintf("%v", item)) + } + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetAssets(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// BatchGetAssetsHistory batch gets the update history of assets that overlap a time window. +// For IAM_POLICY content, this API outputs history when the asset and its +// attached IAM POLICY both exist. This can create gaps in the output history. +// Otherwise, this API outputs history with asset in both non-delete or +// deleted status. +// If a specified asset does not exist, this API returns an INVALID_ARGUMENT +// error. +func (c *restClient) BatchGetAssetsHistory(ctx context.Context, req *assetpb.BatchGetAssetsHistoryRequest, opts ...gax.CallOption) (*assetpb.BatchGetAssetsHistoryResponse, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:batchGetAssetsHistory", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if items := req.GetAssetNames(); len(items) > 0 { + for _, item := range items { + params.Add("assetNames", fmt.Sprintf("%v", item)) + } + } + if req.GetContentType() != 0 { + params.Add("contentType", fmt.Sprintf("%v", req.GetContentType())) + } + if req.GetReadTimeWindow().GetEndTime() != nil { + endTime, err := protojson.Marshal(req.GetReadTimeWindow().GetEndTime()) + if err != nil { + return nil, err + } + params.Add("readTimeWindow.endTime", string(endTime)) + } + if req.GetReadTimeWindow().GetStartTime() != nil { + startTime, err := protojson.Marshal(req.GetReadTimeWindow().GetStartTime()) + if err != nil { + return nil, err + } + params.Add("readTimeWindow.startTime", string(startTime)) + } + if items := req.GetRelationshipTypes(); len(items) > 0 { + for _, item := range items { + params.Add("relationshipTypes", fmt.Sprintf("%v", item)) + } + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).BatchGetAssetsHistory[0:len((*c.CallOptions).BatchGetAssetsHistory):len((*c.CallOptions).BatchGetAssetsHistory)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &assetpb.BatchGetAssetsHistoryResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateFeed creates a feed in a parent project/folder/organization to listen to its +// asset updates. +func (c *restClient) CreateFeed(ctx context.Context, req *assetpb.CreateFeedRequest, opts ...gax.CallOption) (*assetpb.Feed, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/feeds", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateFeed[0:len((*c.CallOptions).CreateFeed):len((*c.CallOptions).CreateFeed)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &assetpb.Feed{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetFeed gets details about an asset feed. +func (c *restClient) GetFeed(ctx context.Context, req *assetpb.GetFeedRequest, opts ...gax.CallOption) (*assetpb.Feed, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetFeed[0:len((*c.CallOptions).GetFeed):len((*c.CallOptions).GetFeed)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &assetpb.Feed{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListFeeds lists all asset feeds in a parent project/folder/organization. +func (c *restClient) ListFeeds(ctx context.Context, req *assetpb.ListFeedsRequest, opts ...gax.CallOption) (*assetpb.ListFeedsResponse, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/feeds", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).ListFeeds[0:len((*c.CallOptions).ListFeeds):len((*c.CallOptions).ListFeeds)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &assetpb.ListFeedsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateFeed updates an asset feed configuration. +func (c *restClient) UpdateFeed(ctx context.Context, req *assetpb.UpdateFeedRequest, opts ...gax.CallOption) (*assetpb.Feed, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetFeed().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "feed.name", url.QueryEscape(req.GetFeed().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateFeed[0:len((*c.CallOptions).UpdateFeed):len((*c.CallOptions).UpdateFeed)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &assetpb.Feed{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteFeed deletes an asset feed. +func (c *restClient) DeleteFeed(ctx context.Context, req *assetpb.DeleteFeedRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// SearchAllResources searches all Cloud resources within the specified scope, such as a project, +// folder, or organization. The caller must be granted the +// cloudasset.assets.searchAllResources permission on the desired scope, +// otherwise the request will be rejected. +func (c *restClient) SearchAllResources(ctx context.Context, req *assetpb.SearchAllResourcesRequest, opts ...gax.CallOption) *ResourceSearchResultIterator { + it := &ResourceSearchResultIterator{} + req = proto.Clone(req).(*assetpb.SearchAllResourcesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*assetpb.ResourceSearchResult, string, error) { + resp := &assetpb.SearchAllResourcesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:searchAllResources", req.GetScope()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if items := req.GetAssetTypes(); len(items) > 0 { + for _, item := range items { + params.Add("assetTypes", fmt.Sprintf("%v", item)) + } + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + if req.GetQuery() != "" { + params.Add("query", fmt.Sprintf("%v", req.GetQuery())) + } + if req.GetReadMask() != nil { + readMask, err := protojson.Marshal(req.GetReadMask()) + if err != nil { + return nil, "", err + } + params.Add("readMask", string(readMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetResults(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// SearchAllIamPolicies searches all IAM policies within the specified scope, such as a project, +// folder, or organization. The caller must be granted the +// cloudasset.assets.searchAllIamPolicies permission on the desired scope, +// otherwise the request will be rejected. +func (c *restClient) SearchAllIamPolicies(ctx context.Context, req *assetpb.SearchAllIamPoliciesRequest, opts ...gax.CallOption) *IamPolicySearchResultIterator { + it := &IamPolicySearchResultIterator{} + req = proto.Clone(req).(*assetpb.SearchAllIamPoliciesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*assetpb.IamPolicySearchResult, string, error) { + resp := &assetpb.SearchAllIamPoliciesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:searchAllIamPolicies", req.GetScope()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if items := req.GetAssetTypes(); len(items) > 0 { + for _, item := range items { + params.Add("assetTypes", fmt.Sprintf("%v", item)) + } + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + if req.GetQuery() != "" { + params.Add("query", fmt.Sprintf("%v", req.GetQuery())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetResults(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// AnalyzeIamPolicy analyzes IAM policies to answer which identities have what accesses on +// which resources. +func (c *restClient) AnalyzeIamPolicy(ctx context.Context, req *assetpb.AnalyzeIamPolicyRequest, opts ...gax.CallOption) (*assetpb.AnalyzeIamPolicyResponse, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:analyzeIamPolicy", req.GetAnalysisQuery().GetScope()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if items := req.GetAnalysisQuery().GetAccessSelector().GetPermissions(); len(items) > 0 { + for _, item := range items { + params.Add("analysisQuery.accessSelector.permissions", fmt.Sprintf("%v", item)) + } + } + if items := req.GetAnalysisQuery().GetAccessSelector().GetRoles(); len(items) > 0 { + for _, item := range items { + params.Add("analysisQuery.accessSelector.roles", fmt.Sprintf("%v", item)) + } + } + if req.GetAnalysisQuery().GetConditionContext().GetAccessTime() != nil { + accessTime, err := protojson.Marshal(req.GetAnalysisQuery().GetConditionContext().GetAccessTime()) + if err != nil { + return nil, err + } + params.Add("analysisQuery.conditionContext.accessTime", string(accessTime)) + } + params.Add("analysisQuery.identitySelector.identity", fmt.Sprintf("%v", req.GetAnalysisQuery().GetIdentitySelector().GetIdentity())) + if req.GetAnalysisQuery().GetOptions().GetAnalyzeServiceAccountImpersonation() { + params.Add("analysisQuery.options.analyzeServiceAccountImpersonation", fmt.Sprintf("%v", req.GetAnalysisQuery().GetOptions().GetAnalyzeServiceAccountImpersonation())) + } + if req.GetAnalysisQuery().GetOptions().GetExpandGroups() { + params.Add("analysisQuery.options.expandGroups", fmt.Sprintf("%v", req.GetAnalysisQuery().GetOptions().GetExpandGroups())) + } + if req.GetAnalysisQuery().GetOptions().GetExpandResources() { + params.Add("analysisQuery.options.expandResources", fmt.Sprintf("%v", req.GetAnalysisQuery().GetOptions().GetExpandResources())) + } + if req.GetAnalysisQuery().GetOptions().GetExpandRoles() { + params.Add("analysisQuery.options.expandRoles", fmt.Sprintf("%v", req.GetAnalysisQuery().GetOptions().GetExpandRoles())) + } + if req.GetAnalysisQuery().GetOptions().GetOutputGroupEdges() { + params.Add("analysisQuery.options.outputGroupEdges", fmt.Sprintf("%v", req.GetAnalysisQuery().GetOptions().GetOutputGroupEdges())) + } + if req.GetAnalysisQuery().GetOptions().GetOutputResourceEdges() { + params.Add("analysisQuery.options.outputResourceEdges", fmt.Sprintf("%v", req.GetAnalysisQuery().GetOptions().GetOutputResourceEdges())) + } + params.Add("analysisQuery.resourceSelector.fullResourceName", fmt.Sprintf("%v", req.GetAnalysisQuery().GetResourceSelector().GetFullResourceName())) + if req.GetExecutionTimeout() != nil { + executionTimeout, err := protojson.Marshal(req.GetExecutionTimeout()) + if err != nil { + return nil, err + } + params.Add("executionTimeout", string(executionTimeout)) + } + if req.GetSavedAnalysisQuery() != "" { + params.Add("savedAnalysisQuery", fmt.Sprintf("%v", req.GetSavedAnalysisQuery())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "analysis_query.scope", url.QueryEscape(req.GetAnalysisQuery().GetScope()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).AnalyzeIamPolicy[0:len((*c.CallOptions).AnalyzeIamPolicy):len((*c.CallOptions).AnalyzeIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &assetpb.AnalyzeIamPolicyResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// AnalyzeIamPolicyLongrunning analyzes IAM policies asynchronously to answer which identities have what +// accesses on which resources, and writes the analysis results to a Google +// Cloud Storage or a BigQuery destination. For Cloud Storage destination, the +// output format is the JSON format that represents a +// AnalyzeIamPolicyResponse. This method implements the +// google.longrunning.Operation, which allows you to track the operation +// status. We recommend intervals of at least 2 seconds with exponential +// backoff retry to poll the operation result. The metadata contains the +// metadata for the long-running operation. +func (c *restClient) AnalyzeIamPolicyLongrunning(ctx context.Context, req *assetpb.AnalyzeIamPolicyLongrunningRequest, opts ...gax.CallOption) (*AnalyzeIamPolicyLongrunningOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:analyzeIamPolicyLongrunning", req.GetAnalysisQuery().GetScope()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "analysis_query.scope", url.QueryEscape(req.GetAnalysisQuery().GetScope()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &AnalyzeIamPolicyLongrunningOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// AnalyzeMove analyze moving a resource to a specified destination without kicking off +// the actual move. The analysis is best effort depending on the user’s +// permissions of viewing different hierarchical policies and configurations. +// The policies and configuration are subject to change before the actual +// resource migration takes place. +func (c *restClient) AnalyzeMove(ctx context.Context, req *assetpb.AnalyzeMoveRequest, opts ...gax.CallOption) (*assetpb.AnalyzeMoveResponse, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:analyzeMove", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("destinationParent", fmt.Sprintf("%v", req.GetDestinationParent())) + if req.GetView() != 0 { + params.Add("view", fmt.Sprintf("%v", req.GetView())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).AnalyzeMove[0:len((*c.CallOptions).AnalyzeMove):len((*c.CallOptions).AnalyzeMove)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &assetpb.AnalyzeMoveResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// QueryAssets issue a job that queries assets using a SQL statement compatible with +// BigQuery Standard +// SQL (at http://cloud/bigquery/docs/reference/standard-sql/enabling-standard-sql). +// +// If the query execution finishes within timeout and there’s no pagination, +// the full query results will be returned in the QueryAssetsResponse. +// +// Otherwise, full query results can be obtained by issuing extra requests +// with the job_reference from the a previous QueryAssets call. +// +// Note, the query result has approximately 10 GB limitation enforced by +// BigQuery +// https://cloud.google.com/bigquery/docs/best-practices-performance-output (at https://cloud.google.com/bigquery/docs/best-practices-performance-output), +// queries return larger results will result in errors. +func (c *restClient) QueryAssets(ctx context.Context, req *assetpb.QueryAssetsRequest, opts ...gax.CallOption) (*assetpb.QueryAssetsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:queryAssets", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).QueryAssets[0:len((*c.CallOptions).QueryAssets):len((*c.CallOptions).QueryAssets)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &assetpb.QueryAssetsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateSavedQuery creates a saved query in a parent project/folder/organization. +func (c *restClient) CreateSavedQuery(ctx context.Context, req *assetpb.CreateSavedQueryRequest, opts ...gax.CallOption) (*assetpb.SavedQuery, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetSavedQuery() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/savedQueries", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("savedQueryId", fmt.Sprintf("%v", req.GetSavedQueryId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateSavedQuery[0:len((*c.CallOptions).CreateSavedQuery):len((*c.CallOptions).CreateSavedQuery)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &assetpb.SavedQuery{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetSavedQuery gets details about a saved query. +func (c *restClient) GetSavedQuery(ctx context.Context, req *assetpb.GetSavedQueryRequest, opts ...gax.CallOption) (*assetpb.SavedQuery, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetSavedQuery[0:len((*c.CallOptions).GetSavedQuery):len((*c.CallOptions).GetSavedQuery)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &assetpb.SavedQuery{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListSavedQueries lists all saved queries in a parent project/folder/organization. +func (c *restClient) ListSavedQueries(ctx context.Context, req *assetpb.ListSavedQueriesRequest, opts ...gax.CallOption) *SavedQueryIterator { + it := &SavedQueryIterator{} + req = proto.Clone(req).(*assetpb.ListSavedQueriesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*assetpb.SavedQuery, string, error) { + resp := &assetpb.ListSavedQueriesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/savedQueries", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetSavedQueries(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// UpdateSavedQuery updates a saved query. +func (c *restClient) UpdateSavedQuery(ctx context.Context, req *assetpb.UpdateSavedQueryRequest, opts ...gax.CallOption) (*assetpb.SavedQuery, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetSavedQuery() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetSavedQuery().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "saved_query.name", url.QueryEscape(req.GetSavedQuery().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateSavedQuery[0:len((*c.CallOptions).UpdateSavedQuery):len((*c.CallOptions).UpdateSavedQuery)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &assetpb.SavedQuery{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteSavedQuery deletes a saved query. +func (c *restClient) DeleteSavedQuery(ctx context.Context, req *assetpb.DeleteSavedQueryRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// BatchGetEffectiveIamPolicies gets effective IAM policies for a batch of resources. +func (c *restClient) BatchGetEffectiveIamPolicies(ctx context.Context, req *assetpb.BatchGetEffectiveIamPoliciesRequest, opts ...gax.CallOption) (*assetpb.BatchGetEffectiveIamPoliciesResponse, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/effectiveIamPolicies:batchGet", req.GetScope()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if items := req.GetNames(); len(items) > 0 { + for _, item := range items { + params.Add("names", fmt.Sprintf("%v", item)) + } + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "scope", url.QueryEscape(req.GetScope()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).BatchGetEffectiveIamPolicies[0:len((*c.CallOptions).BatchGetEffectiveIamPolicies):len((*c.CallOptions).BatchGetEffectiveIamPolicies)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &assetpb.BatchGetEffectiveIamPoliciesResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *restClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// AnalyzeIamPolicyLongrunningOperation manages a long-running operation from AnalyzeIamPolicyLongrunning. +type AnalyzeIamPolicyLongrunningOperation struct { + lro *longrunning.Operation + pollPath string +} + +// AnalyzeIamPolicyLongrunningOperation returns a new AnalyzeIamPolicyLongrunningOperation from a given name. +// The name must be that of a previously created AnalyzeIamPolicyLongrunningOperation, possibly from a different process. +func (c *gRPCClient) AnalyzeIamPolicyLongrunningOperation(name string) *AnalyzeIamPolicyLongrunningOperation { + return &AnalyzeIamPolicyLongrunningOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// AnalyzeIamPolicyLongrunningOperation returns a new AnalyzeIamPolicyLongrunningOperation from a given name. +// The name must be that of a previously created AnalyzeIamPolicyLongrunningOperation, possibly from a different process. +func (c *restClient) AnalyzeIamPolicyLongrunningOperation(name string) *AnalyzeIamPolicyLongrunningOperation { + override := fmt.Sprintf("/v1/%s", name) + return &AnalyzeIamPolicyLongrunningOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *AnalyzeIamPolicyLongrunningOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*assetpb.AnalyzeIamPolicyLongrunningResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp assetpb.AnalyzeIamPolicyLongrunningResponse + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *AnalyzeIamPolicyLongrunningOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*assetpb.AnalyzeIamPolicyLongrunningResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp assetpb.AnalyzeIamPolicyLongrunningResponse + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *AnalyzeIamPolicyLongrunningOperation) Metadata() (*assetpb.AnalyzeIamPolicyLongrunningMetadata, error) { + var meta assetpb.AnalyzeIamPolicyLongrunningMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *AnalyzeIamPolicyLongrunningOperation) Done() bool { + return op.lro.Done() +} + +// 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 *AnalyzeIamPolicyLongrunningOperation) Name() string { + return op.lro.Name() +} + +// ExportAssetsOperation manages a long-running operation from ExportAssets. +type ExportAssetsOperation struct { + lro *longrunning.Operation + pollPath string +} + +// ExportAssetsOperation returns a new ExportAssetsOperation from a given name. +// The name must be that of a previously created ExportAssetsOperation, possibly from a different process. +func (c *gRPCClient) ExportAssetsOperation(name string) *ExportAssetsOperation { + return &ExportAssetsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// ExportAssetsOperation returns a new ExportAssetsOperation from a given name. +// The name must be that of a previously created ExportAssetsOperation, possibly from a different process. +func (c *restClient) ExportAssetsOperation(name string) *ExportAssetsOperation { + override := fmt.Sprintf("/v1/%s", name) + return &ExportAssetsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, } } @@ -1203,6 +3013,7 @@ func (c *gRPCClient) ExportAssetsOperation(name string) *ExportAssetsOperation { // // See documentation of Poll for error-handling information. func (op *ExportAssetsOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*assetpb.ExportAssetsResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp assetpb.ExportAssetsResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1220,6 +3031,7 @@ func (op *ExportAssetsOperation) Wait(ctx context.Context, opts ...gax.CallOptio // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *ExportAssetsOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*assetpb.ExportAssetsResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp assetpb.ExportAssetsResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/asset/apiv1/asset_client_example_test.go b/asset/apiv1/asset_client_example_test.go index 32370a6c0efc..90c46f57ac48 100644 --- a/asset/apiv1/asset_client_example_test.go +++ b/asset/apiv1/asset_client_example_test.go @@ -42,6 +42,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := asset.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_ExportAssets() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/asset/apiv1/assetpb/asset_service.pb.go b/asset/apiv1/assetpb/asset_service.pb.go index 51d3562b2e12..f5b3901dd099 100644 --- a/asset/apiv1/assetpb/asset_service.pb.go +++ b/asset/apiv1/assetpb/asset_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/asset/v1/asset_service.proto package assetpb @@ -1278,7 +1278,6 @@ type OutputConfig struct { // Asset export destination. // // Types that are assignable to Destination: - // // *OutputConfig_GcsDestination // *OutputConfig_BigqueryDestination Destination isOutputConfig_Destination `protobuf_oneof:"destination"` @@ -1365,7 +1364,6 @@ type OutputResult struct { // Asset export result. // // Types that are assignable to Result: - // // *OutputResult_GcsResult Result isOutputResult_Result `protobuf_oneof:"result"` } @@ -1486,7 +1484,6 @@ type GcsDestination struct { // Required. // // Types that are assignable to ObjectUri: - // // *GcsDestination_Uri // *GcsDestination_UriPrefix ObjectUri isGcsDestination_ObjectUri `protobuf_oneof:"object_uri"` @@ -1826,7 +1823,6 @@ type FeedOutputConfig struct { // Asset feed destination. // // Types that are assignable to Destination: - // // *FeedOutputConfig_PubsubDestination Destination isFeedOutputConfig_Destination `protobuf_oneof:"destination"` } @@ -2066,51 +2062,51 @@ type SearchAllResourcesRequest struct { // // Examples: // - // - `name:Important` to find Cloud resources whose name contains - // "Important" as a word. - // - `name=Important` to find the Cloud resource whose name is exactly - // "Important". - // - `displayName:Impor*` to find Cloud resources whose display name - // contains "Impor" as a prefix of any word in the field. - // - `location:us-west*` to find Cloud resources whose location contains both - // "us" and "west" as prefixes. - // - `labels:prod` to find Cloud resources whose labels contain "prod" as - // a key or value. - // - `labels.env:prod` to find Cloud resources that have a label "env" - // and its value is "prod". - // - `labels.env:*` to find Cloud resources that have a label "env". - // - `kmsKey:key` to find Cloud resources encrypted with a customer-managed - // encryption key whose name contains "key" as a word. This field is - // deprecated. Please use the `kmsKeys` field to retrieve KMS key - // information. - // - `kmsKeys:key` to find Cloud resources encrypted with customer-managed - // encryption keys whose name contains the word "key". - // - `relationships:instance-group-1` to find Cloud resources that have - // relationships with "instance-group-1" in the related resource name. - // - `relationships:INSTANCE_TO_INSTANCEGROUP` to find compute instances that - // have relationships of type "INSTANCE_TO_INSTANCEGROUP". - // - `relationships.INSTANCE_TO_INSTANCEGROUP:instance-group-1` to find - // compute instances that have relationships with "instance-group-1" in the - // compute instance group resource name, for relationship type - // "INSTANCE_TO_INSTANCEGROUP". - // - `state:ACTIVE` to find Cloud resources whose state contains "ACTIVE" as a - // word. - // - `NOT state:ACTIVE` to find Cloud resources whose state doesn't contain - // "ACTIVE" as a word. - // - `createTime<1609459200` to find Cloud resources that were created before - // "2021-01-01 00:00:00 UTC". 1609459200 is the epoch timestamp of - // "2021-01-01 00:00:00 UTC" in seconds. - // - `updateTime>1609459200` to find Cloud resources that were updated after - // "2021-01-01 00:00:00 UTC". 1609459200 is the epoch timestamp of - // "2021-01-01 00:00:00 UTC" in seconds. - // - `Important` to find Cloud resources that contain "Important" as a word - // in any of the searchable fields. - // - `Impor*` to find Cloud resources that contain "Impor" as a prefix of any - // word in any of the searchable fields. - // - `Important location:(us-west1 OR global)` to find Cloud - // resources that contain "Important" as a word in any of the searchable - // fields and are also located in the "us-west1" region or the "global" - // location. + // * `name:Important` to find Cloud resources whose name contains + // "Important" as a word. + // * `name=Important` to find the Cloud resource whose name is exactly + // "Important". + // * `displayName:Impor*` to find Cloud resources whose display name + // contains "Impor" as a prefix of any word in the field. + // * `location:us-west*` to find Cloud resources whose location contains both + // "us" and "west" as prefixes. + // * `labels:prod` to find Cloud resources whose labels contain "prod" as + // a key or value. + // * `labels.env:prod` to find Cloud resources that have a label "env" + // and its value is "prod". + // * `labels.env:*` to find Cloud resources that have a label "env". + // * `kmsKey:key` to find Cloud resources encrypted with a customer-managed + // encryption key whose name contains "key" as a word. This field is + // deprecated. Please use the `kmsKeys` field to retrieve KMS key + // information. + // * `kmsKeys:key` to find Cloud resources encrypted with customer-managed + // encryption keys whose name contains the word "key". + // * `relationships:instance-group-1` to find Cloud resources that have + // relationships with "instance-group-1" in the related resource name. + // * `relationships:INSTANCE_TO_INSTANCEGROUP` to find compute instances that + // have relationships of type "INSTANCE_TO_INSTANCEGROUP". + // * `relationships.INSTANCE_TO_INSTANCEGROUP:instance-group-1` to find + // compute instances that have relationships with "instance-group-1" in the + // compute instance group resource name, for relationship type + // "INSTANCE_TO_INSTANCEGROUP". + // * `state:ACTIVE` to find Cloud resources whose state contains "ACTIVE" as a + // word. + // * `NOT state:ACTIVE` to find Cloud resources whose state doesn't contain + // "ACTIVE" as a word. + // * `createTime<1609459200` to find Cloud resources that were created before + // "2021-01-01 00:00:00 UTC". 1609459200 is the epoch timestamp of + // "2021-01-01 00:00:00 UTC" in seconds. + // * `updateTime>1609459200` to find Cloud resources that were updated after + // "2021-01-01 00:00:00 UTC". 1609459200 is the epoch timestamp of + // "2021-01-01 00:00:00 UTC" in seconds. + // * `Important` to find Cloud resources that contain "Important" as a word + // in any of the searchable fields. + // * `Impor*` to find Cloud resources that contain "Impor" as a prefix of any + // word in any of the searchable fields. + // * `Important location:(us-west1 OR global)` to find Cloud + // resources that contain "Important" as a word in any of the searchable + // fields and are also located in the "us-west1" region or the "global" + // location. Query string `protobuf:"bytes,2,opt,name=query,proto3" json:"query,omitempty"` // Optional. A list of asset types that this request searches for. If empty, it will // search all the [searchable asset @@ -2143,17 +2139,17 @@ type SearchAllResourcesRequest struct { // Example: "location DESC, name". // Only singular primitive fields in the response are sortable: // - // - name - // - assetType - // - project - // - displayName - // - description - // - location - // - createTime - // - updateTime - // - state - // - parentFullResourceName - // - parentAssetType + // * name + // * assetType + // * project + // * displayName + // * description + // * location + // * createTime + // * updateTime + // * state + // * parentFullResourceName + // * parentAssetType // // All the other fields such as repeated fields (e.g., `networkTags`, // `kmsKeys`), map fields (e.g., `labels`) and struct fields (e.g., @@ -2167,25 +2163,25 @@ type SearchAllResourcesRequest struct { // The read_mask paths must be valid field paths listed but not limited to // (both snake_case and camelCase are supported): // - // - name - // - assetType - // - project - // - displayName - // - description - // - location - // - tagKeys - // - tagValues - // - tagValueIds - // - labels - // - networkTags - // - kmsKey (This field is deprecated. Please use the `kmsKeys` field to + // * name + // * assetType + // * project + // * displayName + // * description + // * location + // * tagKeys + // * tagValues + // * tagValueIds + // * labels + // * networkTags + // * kmsKey (This field is deprecated. Please use the `kmsKeys` field to // retrieve KMS key information.) - // - kmsKeys - // - createTime - // - updateTime - // - state - // - additionalAttributes - // - versionedResources + // * kmsKeys + // * createTime + // * updateTime + // * state + // * additionalAttributes + // * versionedResources // // If read_mask is not specified, all fields except versionedResources will // be returned. @@ -2368,36 +2364,36 @@ type SearchAllIamPoliciesRequest struct { // // Examples: // - // - `policy:amy@gmail.com` to find IAM policy bindings that specify user - // "amy@gmail.com". - // - `policy:roles/compute.admin` to find IAM policy bindings that specify - // the Compute Admin role. - // - `policy:comp*` to find IAM policy bindings that contain "comp" as a - // prefix of any word in the binding. - // - `policy.role.permissions:storage.buckets.update` to find IAM policy - // bindings that specify a role containing "storage.buckets.update" - // permission. Note that if callers don't have `iam.roles.get` access to a - // role's included permissions, policy bindings that specify this role will - // be dropped from the search results. - // - `policy.role.permissions:upd*` to find IAM policy bindings that specify a - // role containing "upd" as a prefix of any word in the role permission. - // Note that if callers don't have `iam.roles.get` access to a role's - // included permissions, policy bindings that specify this role will be - // dropped from the search results. - // - `resource:organizations/123456` to find IAM policy bindings - // that are set on "organizations/123456". - // - `resource=//cloudresourcemanager.googleapis.com/projects/myproject` to - // find IAM policy bindings that are set on the project named "myproject". - // - `Important` to find IAM policy bindings that contain "Important" as a - // word in any of the searchable fields (except for the included - // permissions). - // - `resource:(instance1 OR instance2) policy:amy` to find - // IAM policy bindings that are set on resources "instance1" or - // "instance2" and also specify user "amy". - // - `roles:roles/compute.admin` to find IAM policy bindings that specify the - // Compute Admin role. - // - `memberTypes:user` to find IAM policy bindings that contain the - // principal type "user". + // * `policy:amy@gmail.com` to find IAM policy bindings that specify user + // "amy@gmail.com". + // * `policy:roles/compute.admin` to find IAM policy bindings that specify + // the Compute Admin role. + // * `policy:comp*` to find IAM policy bindings that contain "comp" as a + // prefix of any word in the binding. + // * `policy.role.permissions:storage.buckets.update` to find IAM policy + // bindings that specify a role containing "storage.buckets.update" + // permission. Note that if callers don't have `iam.roles.get` access to a + // role's included permissions, policy bindings that specify this role will + // be dropped from the search results. + // * `policy.role.permissions:upd*` to find IAM policy bindings that specify a + // role containing "upd" as a prefix of any word in the role permission. + // Note that if callers don't have `iam.roles.get` access to a role's + // included permissions, policy bindings that specify this role will be + // dropped from the search results. + // * `resource:organizations/123456` to find IAM policy bindings + // that are set on "organizations/123456". + // * `resource=//cloudresourcemanager.googleapis.com/projects/myproject` to + // find IAM policy bindings that are set on the project named "myproject". + // * `Important` to find IAM policy bindings that contain "Important" as a + // word in any of the searchable fields (except for the included + // permissions). + // * `resource:(instance1 OR instance2) policy:amy` to find + // IAM policy bindings that are set on resources "instance1" or + // "instance2" and also specify user "amy". + // * `roles:roles/compute.admin` to find IAM policy bindings that specify the + // Compute Admin role. + // * `memberTypes:user` to find IAM policy bindings that contain the + // principal type "user". Query string `protobuf:"bytes,2,opt,name=query,proto3" json:"query,omitempty"` // Optional. The page size for search result pagination. Page size is capped at 500 even // if a larger value is given. If set to zero, server will pick an appropriate @@ -2431,10 +2427,9 @@ type SearchAllIamPoliciesRequest struct { // to indicate descending order. Redundant space characters are ignored. // Example: "assetType DESC, resource". // Only singular primitive fields in the response are sortable: - // - resource - // - assetType - // - project - // + // * resource + // * assetType + // * project // All the other fields such as repeated fields (e.g., `folders`) and // non-primitive fields (e.g., `policy`) are not supported. OrderBy string `protobuf:"bytes,7,opt,name=order_by,json=orderBy,proto3" json:"order_by,omitempty"` @@ -2851,7 +2846,6 @@ type IamPolicyAnalysisOutputConfig struct { // IAM policy analysis export destination. // // Types that are assignable to Destination: - // // *IamPolicyAnalysisOutputConfig_GcsDestination_ // *IamPolicyAnalysisOutputConfig_BigqueryDestination Destination isIamPolicyAnalysisOutputConfig_Destination `protobuf_oneof:"destination"` @@ -3322,8 +3316,7 @@ type ListSavedQueriesRequest struct { Filter string `protobuf:"bytes,4,opt,name=filter,proto3" json:"filter,omitempty"` // Optional. The maximum number of saved queries to return per page. The service may // return fewer than this value. If unspecified, at most 50 will be returned. - // - // The maximum value is 1000; values above 1000 will be coerced to 1000. + // The maximum value is 1000; values above 1000 will be coerced to 1000. PageSize int32 `protobuf:"varint,2,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"` // Optional. A page token, received from a previous `ListSavedQueries` call. // Provide this to retrieve the subsequent page. @@ -3705,7 +3698,6 @@ type MoveAnalysis struct { // Policy etc. DisplayName string `protobuf:"bytes,1,opt,name=display_name,json=displayName,proto3" json:"display_name,omitempty"` // Types that are assignable to Result: - // // *MoveAnalysis_Analysis // *MoveAnalysis_Error Result isMoveAnalysis_Result `protobuf_oneof:"result"` @@ -3962,7 +3954,6 @@ type QueryAssetsRequest struct { // Only assets belonging to the `parent` will be returned. Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // Types that are assignable to Query: - // // *QueryAssetsRequest_Statement // *QueryAssetsRequest_JobReference Query isQueryAssetsRequest_Query `protobuf_oneof:"query"` @@ -4000,7 +3991,6 @@ type QueryAssetsRequest struct { // it will simply return a valid response with no rows. // // Types that are assignable to Time: - // // *QueryAssetsRequest_ReadTimeWindow // *QueryAssetsRequest_ReadTime Time isQueryAssetsRequest_Time `protobuf_oneof:"time"` @@ -4181,7 +4171,6 @@ type QueryAssetsResponse struct { // `error`, `query_result` or `output_config` will be set. Done bool `protobuf:"varint,2,opt,name=done,proto3" json:"done,omitempty"` // Types that are assignable to Response: - // // *QueryAssetsResponse_Error // *QueryAssetsResponse_QueryResult // *QueryAssetsResponse_OutputConfig @@ -4993,7 +4982,6 @@ type IamPolicyAnalysisQuery_ConditionContext struct { // The IAM conditions time context. // // Types that are assignable to TimeContext: - // // *IamPolicyAnalysisQuery_ConditionContext_AccessTime TimeContext isIamPolicyAnalysisQuery_ConditionContext_TimeContext `protobuf_oneof:"TimeContext"` } @@ -5205,10 +5193,9 @@ type IamPolicyAnalysisOutputConfig_BigQueryDestination struct { Dataset string `protobuf:"bytes,1,opt,name=dataset,proto3" json:"dataset,omitempty"` // Required. The prefix of the BigQuery tables to which the analysis results will be // written. Tables will be created based on this table_prefix if not exist: - // - _analysis table will contain export operation's metadata. - // - _analysis_result will contain all the - // [IamPolicyAnalysisResult][google.cloud.asset.v1.IamPolicyAnalysisResult]. - // + // * _analysis table will contain export operation's metadata. + // * _analysis_result will contain all the + // [IamPolicyAnalysisResult][google.cloud.asset.v1.IamPolicyAnalysisResult]. // When [partition_key] is specified, both tables will be partitioned based // on the [partition_key]. TablePrefix string `protobuf:"bytes,2,opt,name=table_prefix,json=tablePrefix,proto3" json:"table_prefix,omitempty"` @@ -5297,7 +5284,6 @@ type SavedQuery_QueryContent struct { unknownFields protoimpl.UnknownFields // Types that are assignable to QueryContent: - // // *SavedQuery_QueryContent_IamPolicyAnalysisQuery QueryContent isSavedQuery_QueryContent_QueryContent `protobuf_oneof:"query_content"` } diff --git a/asset/apiv1/assetpb/assets.pb.go b/asset/apiv1/assetpb/assets.pb.go index b35540fb5325..09f060b6d0a1 100644 --- a/asset/apiv1/assetpb/assets.pb.go +++ b/asset/apiv1/assetpb/assets.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/asset/v1/assets.proto package assetpb @@ -360,7 +360,6 @@ type Asset struct { // policy](https://cloud.google.com/access-context-manager/docs/overview#access-policies). // // Types that are assignable to AccessContextPolicy: - // // *Asset_AccessPolicy // *Asset_AccessLevel // *Asset_ServicePerimeter @@ -1010,10 +1009,9 @@ type ResourceSearchResult struct { // To search against the `labels`: // // * Use a field query: - // - query on any label's key or value. Example: `labels:prod` - // - query by a given label. Example: `labels.env:prod` - // - query by a given label's existence. Example: `labels.env:*` - // + // - query on any label's key or value. Example: `labels:prod` + // - query by a given label. Example: `labels.env:prod` + // - query by a given label's existence. Example: `labels.env:*` // * Use a free text query. Example: `prod` Labels map[string]string `protobuf:"bytes,7,rep,name=labels,proto3" json:"labels,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` // Network tags associated with this resource. Like labels, network tags are a @@ -1066,9 +1064,9 @@ type ResourceSearchResult struct { // To search against `create_time`: // // * Use a field query. - // - value in seconds since unix epoch. Example: `createTime > 1609459200` - // - value in date string. Example: `createTime > 2021-01-01` - // - value in date-time string (must be quoted). Example: `createTime > + // - value in seconds since unix epoch. Example: `createTime > 1609459200` + // - value in date string. Example: `createTime > 2021-01-01` + // - value in date-time string (must be quoted). Example: `createTime > // "2021-01-01T00:00:00"` CreateTime *timestamppb.Timestamp `protobuf:"bytes,11,opt,name=create_time,json=createTime,proto3" json:"create_time,omitempty"` // The last update timestamp of this resource, at which the resource was last @@ -1079,9 +1077,9 @@ type ResourceSearchResult struct { // To search against `update_time`: // // * Use a field query. - // - value in seconds since unix epoch. Example: `updateTime < 1609459200` - // - value in date string. Example: `updateTime < 2021-01-01` - // - value in date-time string (must be quoted). Example: `updateTime < + // - value in seconds since unix epoch. Example: `updateTime < 1609459200` + // - value in date string. Example: `updateTime < 2021-01-01` + // - value in date-time string (must be quoted). Example: `updateTime < // "2021-01-01T00:00:00"` UpdateTime *timestamppb.Timestamp `protobuf:"bytes,12,opt,name=update_time,json=updateTime,proto3" json:"update_time,omitempty"` // The state of this resource. Different resources types have different state @@ -1121,9 +1119,9 @@ type ResourceSearchResult struct { // // To search against the `additional_attributes`: // - // - Use a free text query to match the attributes values. Example: to search - // `additional_attributes = { dnsName: "foobar" }`, you can issue a query - // `foobar`. + // * Use a free text query to match the attributes values. Example: to search + // `additional_attributes = { dnsName: "foobar" }`, you can issue a query + // `foobar`. AdditionalAttributes *structpb.Struct `protobuf:"bytes,9,opt,name=additional_attributes,json=additionalAttributes,proto3" json:"additional_attributes,omitempty"` // The full resource name of this resource's parent, if it has one. // To search against the `parent_full_resource_name`: @@ -1160,35 +1158,35 @@ type ResourceSearchResult struct { // To search against the `tagKeys`: // // * Use a field query. Example: - // - `tagKeys:"123456789/env*"` - // - `tagKeys="123456789/env"` - // - `tagKeys:"env"` + // - `tagKeys:"123456789/env*"` + // - `tagKeys="123456789/env"` + // - `tagKeys:"env"` // // * Use a free text query. Example: - // - `env` + // - `env` TagKeys []string `protobuf:"bytes,23,rep,name=tag_keys,json=tagKeys,proto3" json:"tag_keys,omitempty"` // TagValue namespaced names, in the format of // {ORG_ID}/{TAG_KEY_SHORT_NAME}/{TAG_VALUE_SHORT_NAME}. // To search against the `tagValues`: // // * Use a field query. Example: - // - `tagValues:"env"` - // - `tagValues:"env/prod"` - // - `tagValues:"123456789/env/prod*"` - // - `tagValues="123456789/env/prod"` + // - `tagValues:"env"` + // - `tagValues:"env/prod"` + // - `tagValues:"123456789/env/prod*"` + // - `tagValues="123456789/env/prod"` // // * Use a free text query. Example: - // - `prod` + // - `prod` TagValues []string `protobuf:"bytes,25,rep,name=tag_values,json=tagValues,proto3" json:"tag_values,omitempty"` // TagValue IDs, in the format of tagValues/{TAG_VALUE_ID}. // To search against the `tagValueIds`: // // * Use a field query. Example: - // - `tagValueIds:"456"` - // - `tagValueIds="tagValues/456"` + // - `tagValueIds:"456"` + // - `tagValueIds="tagValues/456"` // // * Use a free text query. Example: - // - `456` + // - `456` TagValueIds []string `protobuf:"bytes,26,rep,name=tag_value_ids,json=tagValueIds,proto3" json:"tag_value_ids,omitempty"` // The type of this resource's immediate parent, if there is one. // @@ -1714,12 +1712,12 @@ type IamPolicySearchResult struct { // To search against the `policy` bindings: // // * use a field query: - // - query by the policy contained members. Example: - // `policy:amy@gmail.com` - // - query by the policy contained roles. Example: - // `policy:roles/compute.admin` - // - query by the policy contained roles' included permissions. Example: - // `policy.role.permissions:compute.instances.create` + // - query by the policy contained members. Example: + // `policy:amy@gmail.com` + // - query by the policy contained roles. Example: + // `policy:roles/compute.admin` + // - query by the policy contained roles' included permissions. Example: + // `policy.role.permissions:compute.instances.create` Policy *v1.Policy `protobuf:"bytes,3,opt,name=policy,proto3" json:"policy,omitempty"` // Explanation about the IAM policy search result. It contains additional // information to explain why the search result matches the query. @@ -1861,7 +1859,7 @@ func (x *IamPolicyAnalysisState) GetCode() code.Code { if x != nil { return x.Code } - return code.Code_OK + return code.Code(0) } func (x *IamPolicyAnalysisState) GetCause() string { @@ -2181,7 +2179,6 @@ type IamPolicyAnalysisResult_Access struct { unknownFields protoimpl.UnknownFields // Types that are assignable to OneofAccess: - // // *IamPolicyAnalysisResult_Access_Role // *IamPolicyAnalysisResult_Access_Permission OneofAccess isIamPolicyAnalysisResult_Access_OneofAccess `protobuf_oneof:"oneof_access"` diff --git a/asset/apiv1/doc.go b/asset/apiv1/doc.go index 96f097653b8b..835b54b6a33b 100644 --- a/asset/apiv1/doc.go +++ b/asset/apiv1/doc.go @@ -85,6 +85,8 @@ package asset // import "cloud.google.com/go/asset/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -173,3 +175,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/asset/apiv1/gapic_metadata.json b/asset/apiv1/gapic_metadata.json index 10fd5089523c..685316be03d0 100644 --- a/asset/apiv1/gapic_metadata.json +++ b/asset/apiv1/gapic_metadata.json @@ -116,6 +116,116 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "AnalyzeIamPolicy": { + "methods": [ + "AnalyzeIamPolicy" + ] + }, + "AnalyzeIamPolicyLongrunning": { + "methods": [ + "AnalyzeIamPolicyLongrunning" + ] + }, + "AnalyzeMove": { + "methods": [ + "AnalyzeMove" + ] + }, + "BatchGetAssetsHistory": { + "methods": [ + "BatchGetAssetsHistory" + ] + }, + "BatchGetEffectiveIamPolicies": { + "methods": [ + "BatchGetEffectiveIamPolicies" + ] + }, + "CreateFeed": { + "methods": [ + "CreateFeed" + ] + }, + "CreateSavedQuery": { + "methods": [ + "CreateSavedQuery" + ] + }, + "DeleteFeed": { + "methods": [ + "DeleteFeed" + ] + }, + "DeleteSavedQuery": { + "methods": [ + "DeleteSavedQuery" + ] + }, + "ExportAssets": { + "methods": [ + "ExportAssets" + ] + }, + "GetFeed": { + "methods": [ + "GetFeed" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "GetSavedQuery": { + "methods": [ + "GetSavedQuery" + ] + }, + "ListAssets": { + "methods": [ + "ListAssets" + ] + }, + "ListFeeds": { + "methods": [ + "ListFeeds" + ] + }, + "ListSavedQueries": { + "methods": [ + "ListSavedQueries" + ] + }, + "QueryAssets": { + "methods": [ + "QueryAssets" + ] + }, + "SearchAllIamPolicies": { + "methods": [ + "SearchAllIamPolicies" + ] + }, + "SearchAllResources": { + "methods": [ + "SearchAllResources" + ] + }, + "UpdateFeed": { + "methods": [ + "UpdateFeed" + ] + }, + "UpdateSavedQuery": { + "methods": [ + "UpdateSavedQuery" + ] + } + } } } } diff --git a/asset/apiv1p2beta1/asset_client.go b/asset/apiv1p2beta1/asset_client.go index 46c017cdfd7e..a3ed712eebea 100644 --- a/asset/apiv1p2beta1/asset_client.go +++ b/asset/apiv1p2beta1/asset_client.go @@ -488,6 +488,11 @@ func (c *restClient) CreateFeed(ctx context.Context, req *assetpb.CreateFeedRequ } baseUrl.Path += fmt.Sprintf("/v1p2beta1/%v/feeds", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -541,6 +546,11 @@ func (c *restClient) GetFeed(ctx context.Context, req *assetpb.GetFeedRequest, o } baseUrl.Path += fmt.Sprintf("/v1p2beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -594,6 +604,11 @@ func (c *restClient) ListFeeds(ctx context.Context, req *assetpb.ListFeedsReques } baseUrl.Path += fmt.Sprintf("/v1p2beta1/%v/feeds", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -653,6 +668,11 @@ func (c *restClient) UpdateFeed(ctx context.Context, req *assetpb.UpdateFeedRequ } baseUrl.Path += fmt.Sprintf("/v1p2beta1/%v", req.GetFeed().GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "feed.name", url.QueryEscape(req.GetFeed().GetName()))) @@ -706,6 +726,11 @@ func (c *restClient) DeleteFeed(ctx context.Context, req *assetpb.DeleteFeedRequ } baseUrl.Path += fmt.Sprintf("/v1p2beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) diff --git a/asset/apiv1p2beta1/assetpb/asset_service.pb.go b/asset/apiv1p2beta1/assetpb/asset_service.pb.go index 418ff9798089..bc973cb011ff 100644 --- a/asset/apiv1p2beta1/assetpb/asset_service.pb.go +++ b/asset/apiv1p2beta1/assetpb/asset_service.pb.go @@ -15,8 +15,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/asset/v1p2beta1/asset_service.proto package assetpb @@ -447,7 +447,6 @@ type OutputConfig struct { // Asset export destination. // // Types that are assignable to Destination: - // // *OutputConfig_GcsDestination Destination isOutputConfig_Destination `protobuf_oneof:"destination"` } @@ -518,7 +517,6 @@ type GcsDestination struct { // Required. // // Types that are assignable to ObjectUri: - // // *GcsDestination_Uri ObjectUri isGcsDestination_ObjectUri `protobuf_oneof:"object_uri"` } @@ -643,7 +641,6 @@ type FeedOutputConfig struct { // Asset feed destination. // // Types that are assignable to Destination: - // // *FeedOutputConfig_PubsubDestination Destination isFeedOutputConfig_Destination `protobuf_oneof:"destination"` } diff --git a/asset/apiv1p2beta1/assetpb/assets.pb.go b/asset/apiv1p2beta1/assetpb/assets.pb.go index 50f1177fade6..e6cdfc697d83 100644 --- a/asset/apiv1p2beta1/assetpb/assets.pb.go +++ b/asset/apiv1p2beta1/assetpb/assets.pb.go @@ -15,8 +15,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/asset/v1p2beta1/assets.proto package assetpb diff --git a/asset/apiv1p5beta1/asset_client.go b/asset/apiv1p5beta1/asset_client.go index 08d65d0c6797..0812e8459141 100644 --- a/asset/apiv1p5beta1/asset_client.go +++ b/asset/apiv1p5beta1/asset_client.go @@ -358,8 +358,11 @@ func (c *restClient) ListAssets(ctx context.Context, req *assetpb.ListAssetsRequ baseUrl.Path += fmt.Sprintf("/v1p5beta1/%v/assets", req.GetParent()) params := url.Values{} - if req.GetAssetTypes() != nil { - params.Add("assetTypes", fmt.Sprintf("%v", req.GetAssetTypes())) + params.Add("$alt", "json;enum-encoding=int") + if items := req.GetAssetTypes(); len(items) > 0 { + for _, item := range items { + params.Add("assetTypes", fmt.Sprintf("%v", item)) + } } if req.GetContentType() != 0 { params.Add("contentType", fmt.Sprintf("%v", req.GetContentType())) diff --git a/asset/apiv1p5beta1/assetpb/asset_service.pb.go b/asset/apiv1p5beta1/assetpb/asset_service.pb.go index ffc659f0ba4f..b8b41a76c417 100644 --- a/asset/apiv1p5beta1/assetpb/asset_service.pb.go +++ b/asset/apiv1p5beta1/assetpb/asset_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/asset/v1p5beta1/asset_service.proto package assetpb diff --git a/asset/apiv1p5beta1/assetpb/assets.pb.go b/asset/apiv1p5beta1/assetpb/assets.pb.go index 1599241241dc..e85918e70c2b 100644 --- a/asset/apiv1p5beta1/assetpb/assets.pb.go +++ b/asset/apiv1p5beta1/assetpb/assets.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/asset/v1p5beta1/assets.proto package assetpb @@ -67,7 +67,6 @@ type Asset struct { // Representation of the Cloud Organization access policy. // // Types that are assignable to AccessContextPolicy: - // // *Asset_AccessPolicy // *Asset_AccessLevel // *Asset_ServicePerimeter diff --git a/assuredworkloads/apiv1/assured_workloads_client.go b/assuredworkloads/apiv1/assured_workloads_client.go index bda4941659c3..21762b523706 100644 --- a/assuredworkloads/apiv1/assured_workloads_client.go +++ b/assuredworkloads/apiv1/assured_workloads_client.go @@ -17,9 +17,12 @@ package assuredworkloads import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,13 +30,16 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -82,6 +88,22 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + CreateWorkload: []gax.CallOption{}, + UpdateWorkload: []gax.CallOption{}, + RestrictAllowedResources: []gax.CallOption{}, + DeleteWorkload: []gax.CallOption{}, + GetWorkload: []gax.CallOption{}, + ListWorkloads: []gax.CallOption{}, + ListViolations: []gax.CallOption{}, + GetViolation: []gax.CallOption{}, + AcknowledgeViolation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalClient is an interface that defines the methods available from Assured Workloads API. type internalClient interface { Close() error @@ -319,6 +341,89 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new assured workloads service rest client. +// +// Service to manage AssuredWorkloads. +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://assuredworkloads.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://assuredworkloads.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://assuredworkloads.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) CreateWorkload(ctx context.Context, req *assuredworkloadspb.CreateWorkloadRequest, opts ...gax.CallOption) (*CreateWorkloadOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) @@ -617,9 +722,800 @@ func (c *gRPCClient) ListOperations(ctx context.Context, req *longrunningpb.List return it } +// CreateWorkload creates Assured Workload. +func (c *restClient) CreateWorkload(ctx context.Context, req *assuredworkloadspb.CreateWorkloadRequest, opts ...gax.CallOption) (*CreateWorkloadOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetWorkload() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/workloads", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetExternalId() != "" { + params.Add("externalId", fmt.Sprintf("%v", req.GetExternalId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateWorkloadOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateWorkload updates an existing workload. +// Currently allows updating of workload display_name and labels. +// For force updates don’t set etag field in the Workload. +// Only one update operation per workload can be in progress. +func (c *restClient) UpdateWorkload(ctx context.Context, req *assuredworkloadspb.UpdateWorkloadRequest, opts ...gax.CallOption) (*assuredworkloadspb.Workload, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetWorkload() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetWorkload().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "workload.name", url.QueryEscape(req.GetWorkload().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateWorkload[0:len((*c.CallOptions).UpdateWorkload):len((*c.CallOptions).UpdateWorkload)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &assuredworkloadspb.Workload{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// RestrictAllowedResources restrict the list of resources allowed in the Workload environment. +// The current list of allowed products can be found at +// https://cloud.google.com/assured-workloads/docs/supported-products (at https://cloud.google.com/assured-workloads/docs/supported-products) +// In addition to assuredworkloads.workload.update permission, the user should +// also have orgpolicy.policy.set permission on the folder resource +// to use this functionality. +func (c *restClient) RestrictAllowedResources(ctx context.Context, req *assuredworkloadspb.RestrictAllowedResourcesRequest, opts ...gax.CallOption) (*assuredworkloadspb.RestrictAllowedResourcesResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:restrictAllowedResources", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).RestrictAllowedResources[0:len((*c.CallOptions).RestrictAllowedResources):len((*c.CallOptions).RestrictAllowedResources)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &assuredworkloadspb.RestrictAllowedResourcesResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteWorkload deletes the workload. Make sure that workload’s direct children are already +// in a deleted state, otherwise the request will fail with a +// FAILED_PRECONDITION error. +func (c *restClient) DeleteWorkload(ctx context.Context, req *assuredworkloadspb.DeleteWorkloadRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetEtag() != "" { + params.Add("etag", fmt.Sprintf("%v", req.GetEtag())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetWorkload gets Assured Workload associated with a CRM Node +func (c *restClient) GetWorkload(ctx context.Context, req *assuredworkloadspb.GetWorkloadRequest, opts ...gax.CallOption) (*assuredworkloadspb.Workload, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetWorkload[0:len((*c.CallOptions).GetWorkload):len((*c.CallOptions).GetWorkload)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &assuredworkloadspb.Workload{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListWorkloads lists Assured Workloads under a CRM Node. +func (c *restClient) ListWorkloads(ctx context.Context, req *assuredworkloadspb.ListWorkloadsRequest, opts ...gax.CallOption) *WorkloadIterator { + it := &WorkloadIterator{} + req = proto.Clone(req).(*assuredworkloadspb.ListWorkloadsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*assuredworkloadspb.Workload, string, error) { + resp := &assuredworkloadspb.ListWorkloadsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/workloads", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetWorkloads(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// ListViolations lists the Violations in the AssuredWorkload Environment. +// Callers may also choose to read across multiple Workloads as per +// AIP-159 (at https://google.aip.dev/159) by using ‘-’ (the hyphen or dash +// character) as a wildcard character instead of workload-id in the parent. +// Format organizations/{org_id}/locations/{location}/workloads/- +func (c *restClient) ListViolations(ctx context.Context, req *assuredworkloadspb.ListViolationsRequest, opts ...gax.CallOption) *ViolationIterator { + it := &ViolationIterator{} + req = proto.Clone(req).(*assuredworkloadspb.ListViolationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*assuredworkloadspb.Violation, string, error) { + resp := &assuredworkloadspb.ListViolationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetInterval().GetEndTime() != nil { + endTime, err := protojson.Marshal(req.GetInterval().GetEndTime()) + if err != nil { + return nil, "", err + } + params.Add("interval.endTime", string(endTime)) + } + if req.GetInterval().GetStartTime() != nil { + startTime, err := protojson.Marshal(req.GetInterval().GetStartTime()) + if err != nil { + return nil, "", err + } + params.Add("interval.startTime", string(startTime)) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + params.Add("parent", fmt.Sprintf("%v", req.GetParent())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetViolations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetViolation retrieves Assured Workload Violation based on ID. +func (c *restClient) GetViolation(ctx context.Context, req *assuredworkloadspb.GetViolationRequest, opts ...gax.CallOption) (*assuredworkloadspb.Violation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("name", fmt.Sprintf("%v", req.GetName())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetViolation[0:len((*c.CallOptions).GetViolation):len((*c.CallOptions).GetViolation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &assuredworkloadspb.Violation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// AcknowledgeViolation acknowledges an existing violation. By acknowledging a violation, users +// acknowledge the existence of a compliance violation in their workload and +// decide to ignore it due to a valid business justification. Acknowledgement +// is a permanent operation and it cannot be reverted. +func (c *restClient) AcknowledgeViolation(ctx context.Context, req *assuredworkloadspb.AcknowledgeViolationRequest, opts ...gax.CallOption) (*assuredworkloadspb.AcknowledgeViolationResponse, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("comment", fmt.Sprintf("%v", req.GetComment())) + params.Add("name", fmt.Sprintf("%v", req.GetName())) + if req.GetNonCompliantOrgPolicy() != "" { + params.Add("nonCompliantOrgPolicy", fmt.Sprintf("%v", req.GetNonCompliantOrgPolicy())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).AcknowledgeViolation[0:len((*c.CallOptions).AcknowledgeViolation):len((*c.CallOptions).AcknowledgeViolation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &assuredworkloadspb.AcknowledgeViolationResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *restClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *restClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + // CreateWorkloadOperation manages a long-running operation from CreateWorkload. type CreateWorkloadOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateWorkloadOperation returns a new CreateWorkloadOperation from a given name. @@ -630,10 +1526,21 @@ func (c *gRPCClient) CreateWorkloadOperation(name string) *CreateWorkloadOperati } } +// CreateWorkloadOperation returns a new CreateWorkloadOperation from a given name. +// The name must be that of a previously created CreateWorkloadOperation, possibly from a different process. +func (c *restClient) CreateWorkloadOperation(name string) *CreateWorkloadOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateWorkloadOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateWorkloadOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*assuredworkloadspb.Workload, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp assuredworkloadspb.Workload if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -651,6 +1558,7 @@ func (op *CreateWorkloadOperation) Wait(ctx context.Context, opts ...gax.CallOpt // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateWorkloadOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*assuredworkloadspb.Workload, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp assuredworkloadspb.Workload if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/assuredworkloads/apiv1/assured_workloads_client_example_test.go b/assuredworkloads/apiv1/assured_workloads_client_example_test.go index 0e53e5e859b0..b74b05025c30 100644 --- a/assuredworkloads/apiv1/assured_workloads_client_example_test.go +++ b/assuredworkloads/apiv1/assured_workloads_client_example_test.go @@ -42,6 +42,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := assuredworkloads.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_CreateWorkload() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/assuredworkloads/apiv1/assuredworkloadspb/assuredworkloads.pb.go b/assuredworkloads/apiv1/assuredworkloadspb/assuredworkloads.pb.go index a789203bd06b..4e94aa0d5f62 100644 --- a/assuredworkloads/apiv1/assuredworkloadspb/assuredworkloads.pb.go +++ b/assuredworkloads/apiv1/assuredworkloadspb/assuredworkloads.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/assuredworkloads/v1/assuredworkloads.proto package assuredworkloadspb @@ -1800,11 +1800,10 @@ type Violation struct { AuditLogLink string `protobuf:"bytes,11,opt,name=audit_log_link,json=auditLogLink,proto3" json:"audit_log_link,omitempty"` // Output only. Immutable. Name of the OrgPolicy which was modified with non-compliant change and // resulted this violation. - // - // Format: - // projects/{project_number}/policies/{constraint_name} - // folders/{folder_id}/policies/{constraint_name} - // organizations/{organization_id}/policies/{constraint_name} + // Format: + // projects/{project_number}/policies/{constraint_name} + // folders/{folder_id}/policies/{constraint_name} + // organizations/{organization_id}/policies/{constraint_name} NonCompliantOrgPolicy string `protobuf:"bytes,12,opt,name=non_compliant_org_policy,json=nonCompliantOrgPolicy,proto3" json:"non_compliant_org_policy,omitempty"` // Output only. Compliance violation remediation Remediation *Violation_Remediation `protobuf:"bytes,13,opt,name=remediation,proto3" json:"remediation,omitempty"` diff --git a/assuredworkloads/apiv1/doc.go b/assuredworkloads/apiv1/doc.go index 6f2d5f6e5d64..7e779a44d4e9 100644 --- a/assuredworkloads/apiv1/doc.go +++ b/assuredworkloads/apiv1/doc.go @@ -83,6 +83,8 @@ package assuredworkloads // import "cloud.google.com/go/assuredworkloads/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -171,3 +173,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/assuredworkloads/apiv1/gapic_metadata.json b/assuredworkloads/apiv1/gapic_metadata.json index 45cc3eb5338f..2e8e88ebdd00 100644 --- a/assuredworkloads/apiv1/gapic_metadata.json +++ b/assuredworkloads/apiv1/gapic_metadata.json @@ -66,6 +66,66 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "AcknowledgeViolation": { + "methods": [ + "AcknowledgeViolation" + ] + }, + "CreateWorkload": { + "methods": [ + "CreateWorkload" + ] + }, + "DeleteWorkload": { + "methods": [ + "DeleteWorkload" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "GetViolation": { + "methods": [ + "GetViolation" + ] + }, + "GetWorkload": { + "methods": [ + "GetWorkload" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "ListViolations": { + "methods": [ + "ListViolations" + ] + }, + "ListWorkloads": { + "methods": [ + "ListWorkloads" + ] + }, + "RestrictAllowedResources": { + "methods": [ + "RestrictAllowedResources" + ] + }, + "UpdateWorkload": { + "methods": [ + "UpdateWorkload" + ] + } + } } } } diff --git a/assuredworkloads/apiv1beta1/assured_workloads_client.go b/assuredworkloads/apiv1beta1/assured_workloads_client.go index 2f777a90c93f..872693b60810 100644 --- a/assuredworkloads/apiv1beta1/assured_workloads_client.go +++ b/assuredworkloads/apiv1beta1/assured_workloads_client.go @@ -763,6 +763,7 @@ func (c *restClient) CreateWorkload(ctx context.Context, req *assuredworkloadspb baseUrl.Path += fmt.Sprintf("/v1beta1/%v/workloads", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetExternalId() != "" { params.Add("externalId", fmt.Sprintf("%v", req.GetExternalId())) } @@ -830,6 +831,7 @@ func (c *restClient) UpdateWorkload(ctx context.Context, req *assuredworkloadspb baseUrl.Path += fmt.Sprintf("") params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -855,8 +857,10 @@ func (c *restClient) UpdateWorkload(ctx context.Context, req *assuredworkloadspb params.Add("workload.cjisSettings.kmsSettings.rotationPeriod", string(rotationPeriod)) } params.Add("workload.complianceRegime", fmt.Sprintf("%v", req.GetWorkload().GetComplianceRegime())) - if req.GetWorkload().GetCompliantButDisallowedServices() != nil { - params.Add("workload.compliantButDisallowedServices", fmt.Sprintf("%v", req.GetWorkload().GetCompliantButDisallowedServices())) + if items := req.GetWorkload().GetCompliantButDisallowedServices(); len(items) > 0 { + for _, item := range items { + params.Add("workload.compliantButDisallowedServices", fmt.Sprintf("%v", item)) + } } if req.GetWorkload().GetCreateTime() != nil { createTime, err := protojson.Marshal(req.GetWorkload().GetCreateTime()) @@ -937,8 +941,10 @@ func (c *restClient) UpdateWorkload(ctx context.Context, req *assuredworkloadspb if req.GetWorkload().GetProvisionedResourcesParent() != "" { params.Add("workload.provisionedResourcesParent", fmt.Sprintf("%v", req.GetWorkload().GetProvisionedResourcesParent())) } - if req.GetWorkload().GetSaaEnrollmentResponse().GetSetupErrors() != nil { - params.Add("workload.saaEnrollmentResponse.setupErrors", fmt.Sprintf("%v", req.GetWorkload().GetSaaEnrollmentResponse().GetSetupErrors())) + if items := req.GetWorkload().GetSaaEnrollmentResponse().GetSetupErrors(); len(items) > 0 { + for _, item := range items { + params.Add("workload.saaEnrollmentResponse.setupErrors", fmt.Sprintf("%v", item)) + } } if req.GetWorkload().GetSaaEnrollmentResponse() != nil && req.GetWorkload().GetSaaEnrollmentResponse().SetupStatus != nil { params.Add("workload.saaEnrollmentResponse.setupStatus", fmt.Sprintf("%v", req.GetWorkload().GetSaaEnrollmentResponse().GetSetupStatus())) @@ -1008,6 +1014,11 @@ func (c *restClient) RestrictAllowedResources(ctx context.Context, req *assuredw } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:restrictAllowedResources", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1067,6 +1078,7 @@ func (c *restClient) DeleteWorkload(ctx context.Context, req *assuredworkloadspb baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetEtag() != "" { params.Add("etag", fmt.Sprintf("%v", req.GetEtag())) } @@ -1109,6 +1121,7 @@ func (c *restClient) GetWorkload(ctx context.Context, req *assuredworkloadspb.Ge baseUrl.Path += fmt.Sprintf("") params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("name", fmt.Sprintf("%v", req.GetName())) baseUrl.RawQuery = params.Encode() @@ -1166,6 +1179,7 @@ func (c *restClient) AnalyzeWorkloadMove(ctx context.Context, req *assuredworklo baseUrl.Path += fmt.Sprintf("") params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetProject() != "" { params.Add("project", fmt.Sprintf("%v", req.GetProject())) } @@ -1241,6 +1255,7 @@ func (c *restClient) ListWorkloads(ctx context.Context, req *assuredworkloadspb. baseUrl.Path += fmt.Sprintf("") params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1318,6 +1333,11 @@ func (c *restClient) GetOperation(ctx context.Context, req *longrunningpb.GetOpe } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1385,6 +1405,7 @@ func (c *restClient) ListOperations(ctx context.Context, req *longrunningpb.List baseUrl.Path += fmt.Sprintf("/v1beta1/%v/operations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/assuredworkloads/apiv1beta1/assuredworkloadspb/assuredworkloads.pb.go b/assuredworkloads/apiv1beta1/assuredworkloadspb/assuredworkloads.pb.go index f73bcfa9d76a..b793e3ee405c 100644 --- a/assuredworkloads/apiv1beta1/assuredworkloadspb/assuredworkloads.pb.go +++ b/assuredworkloads/apiv1beta1/assuredworkloadspb/assuredworkloads.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/assuredworkloads/v1beta1/assuredworkloads.proto package assuredworkloadspb @@ -777,7 +777,6 @@ type AnalyzeWorkloadMoveRequest struct { // an existing project or a project-based workload. // // Types that are assignable to ProjectOrWorkloadResource: - // // *AnalyzeWorkloadMoveRequest_Source // *AnalyzeWorkloadMoveRequest_Project ProjectOrWorkloadResource isAnalyzeWorkloadMoveRequest_ProjectOrWorkloadResource `protobuf_oneof:"projectOrWorkloadResource"` @@ -1106,7 +1105,6 @@ type Workload struct { // Settings specific to the selected [compliance_regime] // // Types that are assignable to ComplianceRegimeSettings: - // // *Workload_Il4Settings // *Workload_CjisSettings // *Workload_FedrampHighSettings_ diff --git a/assuredworkloads/apiv1beta1/assuredworkloadspb/assuredworkloads_service.pb.go b/assuredworkloads/apiv1beta1/assuredworkloadspb/assuredworkloads_service.pb.go index fd53f637e414..ec376dcc037d 100644 --- a/assuredworkloads/apiv1beta1/assuredworkloadspb/assuredworkloads_service.pb.go +++ b/assuredworkloads/apiv1beta1/assuredworkloadspb/assuredworkloads_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/assuredworkloads/v1beta1/assuredworkloads_service.proto package assuredworkloadspb diff --git a/automl/apiv1/auto_ml_client.go b/automl/apiv1/auto_ml_client.go index 81cef7ef7e2e..7d1646ab2065 100644 --- a/automl/apiv1/auto_ml_client.go +++ b/automl/apiv1/auto_ml_client.go @@ -17,9 +17,12 @@ package automl import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,14 +30,17 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -196,6 +202,119 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + CreateDataset: []gax.CallOption{}, + GetDataset: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + ListDatasets: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + UpdateDataset: []gax.CallOption{}, + DeleteDataset: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + ImportData: []gax.CallOption{}, + ExportData: []gax.CallOption{}, + GetAnnotationSpec: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + CreateModel: []gax.CallOption{}, + GetModel: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + ListModels: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + DeleteModel: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + UpdateModel: []gax.CallOption{}, + DeployModel: []gax.CallOption{}, + UndeployModel: []gax.CallOption{}, + ExportModel: []gax.CallOption{}, + GetModelEvaluation: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + ListModelEvaluations: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + } +} + // internalClient is an interface that defines the methods available from Cloud AutoML API. type internalClient interface { Close() error @@ -582,6 +701,102 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new auto ml rest client. +// +// AutoML Server API. +// +// The resource names are assigned by the server. +// The server never reuses names that it has created after the resources with +// those names are deleted. +// +// An ID of a resource is the last element of the item’s resource name. For +// projects/{project_id}/locations/{location_id}/datasets/{dataset_id}, then +// the id for the item is {dataset_id}. +// +// Currently the only supported location_id is “us-central1”. +// +// On any input that is documented to expect a string parameter in +// snake_case or dash-case, either of those cases is accepted. +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://automl.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://automl.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://automl.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) CreateDataset(ctx context.Context, req *automlpb.CreateDatasetRequest, opts ...gax.CallOption) (*CreateDatasetOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 5000*time.Millisecond) @@ -1065,114 +1280,1434 @@ func (c *gRPCClient) ListModelEvaluations(ctx context.Context, req *automlpb.Lis return it } -// CreateDatasetOperation manages a long-running operation from CreateDataset. -type CreateDatasetOperation struct { - lro *longrunning.Operation -} - -// CreateDatasetOperation returns a new CreateDatasetOperation from a given name. -// The name must be that of a previously created CreateDatasetOperation, possibly from a different process. -func (c *gRPCClient) CreateDatasetOperation(name string) *CreateDatasetOperation { - return &CreateDatasetOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} - -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *CreateDatasetOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*automlpb.Dataset, error) { - var resp automlpb.Dataset - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { +// CreateDataset creates a dataset. +func (c *restClient) CreateDataset(ctx context.Context, req *automlpb.CreateDatasetRequest, opts ...gax.CallOption) (*CreateDatasetOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetDataset() + jsonReq, err := m.Marshal(body) + if err != nil { return nil, err } - return &resp, nil -} -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *CreateDatasetOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*automlpb.Dataset, error) { - var resp automlpb.Dataset - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - if !op.Done() { - return nil, nil - } - return &resp, nil -} + baseUrl.Path += fmt.Sprintf("/v1/%v/datasets", req.GetParent()) -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *CreateDatasetOperation) Metadata() (*automlpb.OperationMetadata, error) { - var meta automlpb.OperationMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { - return nil, err - } - return &meta, nil -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") -// Done reports whether the long-running operation has completed. -func (op *CreateDatasetOperation) Done() bool { - return op.lro.Done() -} + baseUrl.RawQuery = params.Encode() -// 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 *CreateDatasetOperation) Name() string { - return op.lro.Name() -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) -// CreateModelOperation manages a long-running operation from CreateModel. -type CreateModelOperation struct { - lro *longrunning.Operation -} + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers -// CreateModelOperation returns a new CreateModelOperation from a given name. -// The name must be that of a previously created CreateModelOperation, possibly from a different process. -func (c *gRPCClient) CreateModelOperation(name string) *CreateModelOperation { - return &CreateModelOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *CreateModelOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*automlpb.Model, error) { - var resp automlpb.Model - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { - return nil, err + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e } - return &resp, nil + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateDatasetOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil } -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *CreateModelOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*automlpb.Model, error) { - var resp automlpb.Model - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { +// GetDataset gets a dataset. +func (c *restClient) GetDataset(ctx context.Context, req *automlpb.GetDatasetRequest, opts ...gax.CallOption) (*automlpb.Dataset, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - if !op.Done() { + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetDataset[0:len((*c.CallOptions).GetDataset):len((*c.CallOptions).GetDataset)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &automlpb.Dataset{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListDatasets lists datasets in a project. +func (c *restClient) ListDatasets(ctx context.Context, req *automlpb.ListDatasetsRequest, opts ...gax.CallOption) *DatasetIterator { + it := &DatasetIterator{} + req = proto.Clone(req).(*automlpb.ListDatasetsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*automlpb.Dataset, string, error) { + resp := &automlpb.ListDatasetsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/datasets", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetDatasets(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// UpdateDataset updates a dataset. +func (c *restClient) UpdateDataset(ctx context.Context, req *automlpb.UpdateDatasetRequest, opts ...gax.CallOption) (*automlpb.Dataset, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetDataset() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetDataset().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "dataset.name", url.QueryEscape(req.GetDataset().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateDataset[0:len((*c.CallOptions).UpdateDataset):len((*c.CallOptions).UpdateDataset)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &automlpb.Dataset{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteDataset deletes a dataset and all of its contents. +// Returns empty response in the +// response field when it completes, +// and delete_details in the +// metadata field. +func (c *restClient) DeleteDataset(ctx context.Context, req *automlpb.DeleteDatasetRequest, opts ...gax.CallOption) (*DeleteDatasetOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteDatasetOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ImportData imports data into a dataset. +// For Tables this method can only be called on an empty Dataset. +// +// For Tables: +// +// A +// schema_inference_version +// parameter must be explicitly set. +// Returns an empty response in the +// response field when it completes. +func (c *restClient) ImportData(ctx context.Context, req *automlpb.ImportDataRequest, opts ...gax.CallOption) (*ImportDataOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:importData", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &ImportDataOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ExportData exports dataset’s data to the provided output location. +// Returns an empty response in the +// response field when it completes. +func (c *restClient) ExportData(ctx context.Context, req *automlpb.ExportDataRequest, opts ...gax.CallOption) (*ExportDataOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:exportData", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &ExportDataOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetAnnotationSpec gets an annotation spec. +func (c *restClient) GetAnnotationSpec(ctx context.Context, req *automlpb.GetAnnotationSpecRequest, opts ...gax.CallOption) (*automlpb.AnnotationSpec, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetAnnotationSpec[0:len((*c.CallOptions).GetAnnotationSpec):len((*c.CallOptions).GetAnnotationSpec)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &automlpb.AnnotationSpec{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateModel creates a model. +// Returns a Model in the response +// field when it completes. +// When you create a model, several model evaluations are created for it: +// a global evaluation, and one evaluation for each annotation spec. +func (c *restClient) CreateModel(ctx context.Context, req *automlpb.CreateModelRequest, opts ...gax.CallOption) (*CreateModelOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetModel() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/models", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateModelOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetModel gets a model. +func (c *restClient) GetModel(ctx context.Context, req *automlpb.GetModelRequest, opts ...gax.CallOption) (*automlpb.Model, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetModel[0:len((*c.CallOptions).GetModel):len((*c.CallOptions).GetModel)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &automlpb.Model{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListModels lists models. +func (c *restClient) ListModels(ctx context.Context, req *automlpb.ListModelsRequest, opts ...gax.CallOption) *ModelIterator { + it := &ModelIterator{} + req = proto.Clone(req).(*automlpb.ListModelsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*automlpb.Model, string, error) { + resp := &automlpb.ListModelsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/models", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetModel(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// DeleteModel deletes a model. +// Returns google.protobuf.Empty in the +// response field when it completes, +// and delete_details in the +// metadata field. +func (c *restClient) DeleteModel(ctx context.Context, req *automlpb.DeleteModelRequest, opts ...gax.CallOption) (*DeleteModelOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteModelOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateModel updates a model. +func (c *restClient) UpdateModel(ctx context.Context, req *automlpb.UpdateModelRequest, opts ...gax.CallOption) (*automlpb.Model, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetModel() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetModel().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "model.name", url.QueryEscape(req.GetModel().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateModel[0:len((*c.CallOptions).UpdateModel):len((*c.CallOptions).UpdateModel)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &automlpb.Model{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeployModel deploys a model. If a model is already deployed, deploying it with the +// same parameters has no effect. Deploying with different parametrs +// (as e.g. changing +// node_number) +// will reset the deployment state without pausing the model’s availability. +// +// Only applicable for Text Classification, Image Object Detection , Tables, and Image Segmentation; all other domains manage +// deployment automatically. +// +// Returns an empty response in the +// response field when it completes. +func (c *restClient) DeployModel(ctx context.Context, req *automlpb.DeployModelRequest, opts ...gax.CallOption) (*DeployModelOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:deploy", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeployModelOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UndeployModel undeploys a model. If the model is not deployed this method has no effect. +// +// Only applicable for Text Classification, Image Object Detection and Tables; +// all other domains manage deployment automatically. +// +// Returns an empty response in the +// response field when it completes. +func (c *restClient) UndeployModel(ctx context.Context, req *automlpb.UndeployModelRequest, opts ...gax.CallOption) (*UndeployModelOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:undeploy", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UndeployModelOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ExportModel exports a trained, “export-able”, model to a user specified Google Cloud +// Storage location. A model is considered export-able if and only if it has +// an export format defined for it in +// ModelExportOutputConfig. +// +// Returns an empty response in the +// response field when it completes. +func (c *restClient) ExportModel(ctx context.Context, req *automlpb.ExportModelRequest, opts ...gax.CallOption) (*ExportModelOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:export", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &ExportModelOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetModelEvaluation gets a model evaluation. +func (c *restClient) GetModelEvaluation(ctx context.Context, req *automlpb.GetModelEvaluationRequest, opts ...gax.CallOption) (*automlpb.ModelEvaluation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetModelEvaluation[0:len((*c.CallOptions).GetModelEvaluation):len((*c.CallOptions).GetModelEvaluation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &automlpb.ModelEvaluation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListModelEvaluations lists model evaluations. +func (c *restClient) ListModelEvaluations(ctx context.Context, req *automlpb.ListModelEvaluationsRequest, opts ...gax.CallOption) *ModelEvaluationIterator { + it := &ModelEvaluationIterator{} + req = proto.Clone(req).(*automlpb.ListModelEvaluationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*automlpb.ModelEvaluation, string, error) { + resp := &automlpb.ListModelEvaluationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/modelEvaluations", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetModelEvaluation(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CreateDatasetOperation manages a long-running operation from CreateDataset. +type CreateDatasetOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateDatasetOperation returns a new CreateDatasetOperation from a given name. +// The name must be that of a previously created CreateDatasetOperation, possibly from a different process. +func (c *gRPCClient) CreateDatasetOperation(name string) *CreateDatasetOperation { + return &CreateDatasetOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateDatasetOperation returns a new CreateDatasetOperation from a given name. +// The name must be that of a previously created CreateDatasetOperation, possibly from a different process. +func (c *restClient) CreateDatasetOperation(name string) *CreateDatasetOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateDatasetOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CreateDatasetOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*automlpb.Dataset, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp automlpb.Dataset + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *CreateDatasetOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*automlpb.Dataset, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp automlpb.Dataset + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *CreateDatasetOperation) Metadata() (*automlpb.OperationMetadata, error) { + var meta automlpb.OperationMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *CreateDatasetOperation) Done() bool { + return op.lro.Done() +} + +// 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 *CreateDatasetOperation) Name() string { + return op.lro.Name() +} + +// CreateModelOperation manages a long-running operation from CreateModel. +type CreateModelOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateModelOperation returns a new CreateModelOperation from a given name. +// The name must be that of a previously created CreateModelOperation, possibly from a different process. +func (c *gRPCClient) CreateModelOperation(name string) *CreateModelOperation { + return &CreateModelOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateModelOperation returns a new CreateModelOperation from a given name. +// The name must be that of a previously created CreateModelOperation, possibly from a different process. +func (c *restClient) CreateModelOperation(name string) *CreateModelOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateModelOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CreateModelOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*automlpb.Model, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp automlpb.Model + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *CreateModelOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*automlpb.Model, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp automlpb.Model + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { return nil, nil } return &resp, nil @@ -1205,7 +2740,8 @@ func (op *CreateModelOperation) Name() string { // DeleteDatasetOperation manages a long-running operation from DeleteDataset. type DeleteDatasetOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteDatasetOperation returns a new DeleteDatasetOperation from a given name. @@ -1216,10 +2752,21 @@ func (c *gRPCClient) DeleteDatasetOperation(name string) *DeleteDatasetOperation } } +// DeleteDatasetOperation returns a new DeleteDatasetOperation from a given name. +// The name must be that of a previously created DeleteDatasetOperation, possibly from a different process. +func (c *restClient) DeleteDatasetOperation(name string) *DeleteDatasetOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteDatasetOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteDatasetOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -1233,6 +2780,7 @@ func (op *DeleteDatasetOperation) Wait(ctx context.Context, opts ...gax.CallOpti // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteDatasetOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -1263,7 +2811,8 @@ func (op *DeleteDatasetOperation) Name() string { // DeleteModelOperation manages a long-running operation from DeleteModel. type DeleteModelOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteModelOperation returns a new DeleteModelOperation from a given name. @@ -1274,10 +2823,21 @@ func (c *gRPCClient) DeleteModelOperation(name string) *DeleteModelOperation { } } +// DeleteModelOperation returns a new DeleteModelOperation from a given name. +// The name must be that of a previously created DeleteModelOperation, possibly from a different process. +func (c *restClient) DeleteModelOperation(name string) *DeleteModelOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteModelOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteModelOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -1291,6 +2851,7 @@ func (op *DeleteModelOperation) Wait(ctx context.Context, opts ...gax.CallOption // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteModelOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -1321,7 +2882,8 @@ func (op *DeleteModelOperation) Name() string { // DeployModelOperation manages a long-running operation from DeployModel. type DeployModelOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeployModelOperation returns a new DeployModelOperation from a given name. @@ -1332,10 +2894,21 @@ func (c *gRPCClient) DeployModelOperation(name string) *DeployModelOperation { } } +// DeployModelOperation returns a new DeployModelOperation from a given name. +// The name must be that of a previously created DeployModelOperation, possibly from a different process. +func (c *restClient) DeployModelOperation(name string) *DeployModelOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeployModelOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeployModelOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -1349,6 +2922,7 @@ func (op *DeployModelOperation) Wait(ctx context.Context, opts ...gax.CallOption // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeployModelOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -1379,7 +2953,8 @@ func (op *DeployModelOperation) Name() string { // ExportDataOperation manages a long-running operation from ExportData. type ExportDataOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // ExportDataOperation returns a new ExportDataOperation from a given name. @@ -1390,10 +2965,21 @@ func (c *gRPCClient) ExportDataOperation(name string) *ExportDataOperation { } } +// ExportDataOperation returns a new ExportDataOperation from a given name. +// The name must be that of a previously created ExportDataOperation, possibly from a different process. +func (c *restClient) ExportDataOperation(name string) *ExportDataOperation { + override := fmt.Sprintf("/v1/%s", name) + return &ExportDataOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *ExportDataOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -1407,6 +2993,7 @@ func (op *ExportDataOperation) Wait(ctx context.Context, opts ...gax.CallOption) // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *ExportDataOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -1437,7 +3024,8 @@ func (op *ExportDataOperation) Name() string { // ExportModelOperation manages a long-running operation from ExportModel. type ExportModelOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // ExportModelOperation returns a new ExportModelOperation from a given name. @@ -1448,10 +3036,21 @@ func (c *gRPCClient) ExportModelOperation(name string) *ExportModelOperation { } } +// ExportModelOperation returns a new ExportModelOperation from a given name. +// The name must be that of a previously created ExportModelOperation, possibly from a different process. +func (c *restClient) ExportModelOperation(name string) *ExportModelOperation { + override := fmt.Sprintf("/v1/%s", name) + return &ExportModelOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *ExportModelOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -1465,6 +3064,7 @@ func (op *ExportModelOperation) Wait(ctx context.Context, opts ...gax.CallOption // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *ExportModelOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -1495,7 +3095,8 @@ func (op *ExportModelOperation) Name() string { // ImportDataOperation manages a long-running operation from ImportData. type ImportDataOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // ImportDataOperation returns a new ImportDataOperation from a given name. @@ -1506,10 +3107,21 @@ func (c *gRPCClient) ImportDataOperation(name string) *ImportDataOperation { } } +// ImportDataOperation returns a new ImportDataOperation from a given name. +// The name must be that of a previously created ImportDataOperation, possibly from a different process. +func (c *restClient) ImportDataOperation(name string) *ImportDataOperation { + override := fmt.Sprintf("/v1/%s", name) + return &ImportDataOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *ImportDataOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -1523,6 +3135,7 @@ func (op *ImportDataOperation) Wait(ctx context.Context, opts ...gax.CallOption) // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *ImportDataOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -1553,7 +3166,8 @@ func (op *ImportDataOperation) Name() string { // UndeployModelOperation manages a long-running operation from UndeployModel. type UndeployModelOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UndeployModelOperation returns a new UndeployModelOperation from a given name. @@ -1564,10 +3178,21 @@ func (c *gRPCClient) UndeployModelOperation(name string) *UndeployModelOperation } } +// UndeployModelOperation returns a new UndeployModelOperation from a given name. +// The name must be that of a previously created UndeployModelOperation, possibly from a different process. +func (c *restClient) UndeployModelOperation(name string) *UndeployModelOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UndeployModelOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UndeployModelOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -1581,6 +3206,7 @@ func (op *UndeployModelOperation) Wait(ctx context.Context, opts ...gax.CallOpti // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UndeployModelOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } diff --git a/automl/apiv1/auto_ml_client_example_test.go b/automl/apiv1/auto_ml_client_example_test.go index 4b1f6c0176d8..bb8e73ee3c01 100644 --- a/automl/apiv1/auto_ml_client_example_test.go +++ b/automl/apiv1/auto_ml_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := automl.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_CreateDataset() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/automl/apiv1/automlpb/annotation_payload.pb.go b/automl/apiv1/automlpb/annotation_payload.pb.go index 65bcb0f4ae8f..1a21caad0f40 100644 --- a/automl/apiv1/automlpb/annotation_payload.pb.go +++ b/automl/apiv1/automlpb/annotation_payload.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/automl/v1/annotation_payload.proto package automlpb @@ -45,7 +45,6 @@ type AnnotationPayload struct { // specific to the AutoML domain. // // Types that are assignable to Detail: - // // *AnnotationPayload_Translation // *AnnotationPayload_Classification // *AnnotationPayload_ImageObjectDetection diff --git a/automl/apiv1/automlpb/annotation_spec.pb.go b/automl/apiv1/automlpb/annotation_spec.pb.go index 8f0bde5a8ea3..3a0a2dacc2d4 100644 --- a/automl/apiv1/automlpb/annotation_spec.pb.go +++ b/automl/apiv1/automlpb/annotation_spec.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/automl/v1/annotation_spec.proto package automlpb diff --git a/automl/apiv1/automlpb/classification.pb.go b/automl/apiv1/automlpb/classification.pb.go index 0043ad41dd2e..a6b136c0c4cb 100644 --- a/automl/apiv1/automlpb/classification.pb.go +++ b/automl/apiv1/automlpb/classification.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/automl/v1/classification.proto package automlpb diff --git a/automl/apiv1/automlpb/data_items.pb.go b/automl/apiv1/automlpb/data_items.pb.go index 7c72a3ff6136..a2b7434eda37 100644 --- a/automl/apiv1/automlpb/data_items.pb.go +++ b/automl/apiv1/automlpb/data_items.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/automl/v1/data_items.proto package automlpb @@ -194,7 +194,6 @@ type Image struct { // For Predict calls [image_bytes][google.cloud.automl.v1.Image.image_bytes] must be set . // // Types that are assignable to Data: - // // *Image_ImageBytes Data isImage_Data `protobuf_oneof:"data"` // Output only. HTTP URI to the thumbnail image. @@ -499,7 +498,6 @@ type ExamplePayload struct { // Required. The example data. // // Types that are assignable to Payload: - // // *ExamplePayload_Image // *ExamplePayload_TextSnippet // *ExamplePayload_Document diff --git a/automl/apiv1/automlpb/dataset.pb.go b/automl/apiv1/automlpb/dataset.pb.go index acb6f4a633d3..6ec1fe52d04f 100644 --- a/automl/apiv1/automlpb/dataset.pb.go +++ b/automl/apiv1/automlpb/dataset.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/automl/v1/dataset.proto package automlpb @@ -48,7 +48,6 @@ type Dataset struct { // The dataset metadata that is specific to the problem type. // // Types that are assignable to DatasetMetadata: - // // *Dataset_TranslationDatasetMetadata // *Dataset_ImageClassificationDatasetMetadata // *Dataset_TextClassificationDatasetMetadata diff --git a/automl/apiv1/automlpb/detection.pb.go b/automl/apiv1/automlpb/detection.pb.go index 5f00691fcdfb..031581cc37f5 100644 --- a/automl/apiv1/automlpb/detection.pb.go +++ b/automl/apiv1/automlpb/detection.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/automl/v1/detection.proto package automlpb diff --git a/automl/apiv1/automlpb/geometry.pb.go b/automl/apiv1/automlpb/geometry.pb.go index f0691996a173..e5dcc5d0ba93 100644 --- a/automl/apiv1/automlpb/geometry.pb.go +++ b/automl/apiv1/automlpb/geometry.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/automl/v1/geometry.proto package automlpb diff --git a/automl/apiv1/automlpb/image.pb.go b/automl/apiv1/automlpb/image.pb.go index 0492c7337add..f238b54f9993 100644 --- a/automl/apiv1/automlpb/image.pb.go +++ b/automl/apiv1/automlpb/image.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/automl/v1/image.proto package automlpb @@ -159,38 +159,38 @@ type ImageClassificationModelMetadata struct { // e.g. `BUDGET_REACHED`, `MODEL_CONVERGED`. StopReason string `protobuf:"bytes,5,opt,name=stop_reason,json=stopReason,proto3" json:"stop_reason,omitempty"` // Optional. Type of the model. The available values are: - // - `cloud` - Model to be used via prediction calls to AutoML API. - // This is the default value. - // - `mobile-low-latency-1` - A model that, in addition to providing - // prediction via AutoML API, can also be exported (see - // [AutoMl.ExportModel][google.cloud.automl.v1.AutoMl.ExportModel]) and used on a mobile or edge device - // with TensorFlow afterwards. Expected to have low latency, but - // may have lower prediction quality than other models. - // - `mobile-versatile-1` - A model that, in addition to providing - // prediction via AutoML API, can also be exported (see - // [AutoMl.ExportModel][google.cloud.automl.v1.AutoMl.ExportModel]) and used on a mobile or edge device - // with TensorFlow afterwards. - // - `mobile-high-accuracy-1` - A model that, in addition to providing - // prediction via AutoML API, can also be exported (see - // [AutoMl.ExportModel][google.cloud.automl.v1.AutoMl.ExportModel]) and used on a mobile or edge device - // with TensorFlow afterwards. Expected to have a higher - // latency, but should also have a higher prediction quality - // than other models. - // - `mobile-core-ml-low-latency-1` - A model that, in addition to providing - // prediction via AutoML API, can also be exported (see - // [AutoMl.ExportModel][google.cloud.automl.v1.AutoMl.ExportModel]) and used on a mobile device with Core - // ML afterwards. Expected to have low latency, but may have - // lower prediction quality than other models. - // - `mobile-core-ml-versatile-1` - A model that, in addition to providing - // prediction via AutoML API, can also be exported (see - // [AutoMl.ExportModel][google.cloud.automl.v1.AutoMl.ExportModel]) and used on a mobile device with Core - // ML afterwards. - // - `mobile-core-ml-high-accuracy-1` - A model that, in addition to - // providing prediction via AutoML API, can also be exported - // (see [AutoMl.ExportModel][google.cloud.automl.v1.AutoMl.ExportModel]) and used on a mobile device with - // Core ML afterwards. Expected to have a higher latency, but - // should also have a higher prediction quality than other - // models. + // * `cloud` - Model to be used via prediction calls to AutoML API. + // This is the default value. + // * `mobile-low-latency-1` - A model that, in addition to providing + // prediction via AutoML API, can also be exported (see + // [AutoMl.ExportModel][google.cloud.automl.v1.AutoMl.ExportModel]) and used on a mobile or edge device + // with TensorFlow afterwards. Expected to have low latency, but + // may have lower prediction quality than other models. + // * `mobile-versatile-1` - A model that, in addition to providing + // prediction via AutoML API, can also be exported (see + // [AutoMl.ExportModel][google.cloud.automl.v1.AutoMl.ExportModel]) and used on a mobile or edge device + // with TensorFlow afterwards. + // * `mobile-high-accuracy-1` - A model that, in addition to providing + // prediction via AutoML API, can also be exported (see + // [AutoMl.ExportModel][google.cloud.automl.v1.AutoMl.ExportModel]) and used on a mobile or edge device + // with TensorFlow afterwards. Expected to have a higher + // latency, but should also have a higher prediction quality + // than other models. + // * `mobile-core-ml-low-latency-1` - A model that, in addition to providing + // prediction via AutoML API, can also be exported (see + // [AutoMl.ExportModel][google.cloud.automl.v1.AutoMl.ExportModel]) and used on a mobile device with Core + // ML afterwards. Expected to have low latency, but may have + // lower prediction quality than other models. + // * `mobile-core-ml-versatile-1` - A model that, in addition to providing + // prediction via AutoML API, can also be exported (see + // [AutoMl.ExportModel][google.cloud.automl.v1.AutoMl.ExportModel]) and used on a mobile device with Core + // ML afterwards. + // * `mobile-core-ml-high-accuracy-1` - A model that, in addition to + // providing prediction via AutoML API, can also be exported + // (see [AutoMl.ExportModel][google.cloud.automl.v1.AutoMl.ExportModel]) and used on a mobile device with + // Core ML afterwards. Expected to have a higher latency, but + // should also have a higher prediction quality than other + // models. ModelType string `protobuf:"bytes,7,opt,name=model_type,json=modelType,proto3" json:"model_type,omitempty"` // Output only. An approximate number of online prediction QPS that can // be supported by this model per each node on which it is deployed. @@ -289,28 +289,28 @@ type ImageObjectDetectionModelMetadata struct { unknownFields protoimpl.UnknownFields // Optional. Type of the model. The available values are: - // - `cloud-high-accuracy-1` - (default) A model to be used via prediction - // calls to AutoML API. Expected to have a higher latency, but - // should also have a higher prediction quality than other - // models. - // - `cloud-low-latency-1` - A model to be used via prediction - // calls to AutoML API. Expected to have low latency, but may - // have lower prediction quality than other models. - // - `mobile-low-latency-1` - A model that, in addition to providing - // prediction via AutoML API, can also be exported (see - // [AutoMl.ExportModel][google.cloud.automl.v1.AutoMl.ExportModel]) and used on a mobile or edge device - // with TensorFlow afterwards. Expected to have low latency, but - // may have lower prediction quality than other models. - // - `mobile-versatile-1` - A model that, in addition to providing - // prediction via AutoML API, can also be exported (see - // [AutoMl.ExportModel][google.cloud.automl.v1.AutoMl.ExportModel]) and used on a mobile or edge device - // with TensorFlow afterwards. - // - `mobile-high-accuracy-1` - A model that, in addition to providing - // prediction via AutoML API, can also be exported (see - // [AutoMl.ExportModel][google.cloud.automl.v1.AutoMl.ExportModel]) and used on a mobile or edge device - // with TensorFlow afterwards. Expected to have a higher - // latency, but should also have a higher prediction quality - // than other models. + // * `cloud-high-accuracy-1` - (default) A model to be used via prediction + // calls to AutoML API. Expected to have a higher latency, but + // should also have a higher prediction quality than other + // models. + // * `cloud-low-latency-1` - A model to be used via prediction + // calls to AutoML API. Expected to have low latency, but may + // have lower prediction quality than other models. + // * `mobile-low-latency-1` - A model that, in addition to providing + // prediction via AutoML API, can also be exported (see + // [AutoMl.ExportModel][google.cloud.automl.v1.AutoMl.ExportModel]) and used on a mobile or edge device + // with TensorFlow afterwards. Expected to have low latency, but + // may have lower prediction quality than other models. + // * `mobile-versatile-1` - A model that, in addition to providing + // prediction via AutoML API, can also be exported (see + // [AutoMl.ExportModel][google.cloud.automl.v1.AutoMl.ExportModel]) and used on a mobile or edge device + // with TensorFlow afterwards. + // * `mobile-high-accuracy-1` - A model that, in addition to providing + // prediction via AutoML API, can also be exported (see + // [AutoMl.ExportModel][google.cloud.automl.v1.AutoMl.ExportModel]) and used on a mobile or edge device + // with TensorFlow afterwards. Expected to have a higher + // latency, but should also have a higher prediction quality + // than other models. ModelType string `protobuf:"bytes,1,opt,name=model_type,json=modelType,proto3" json:"model_type,omitempty"` // Output only. The number of nodes this model is deployed on. A node is an // abstraction of a machine resource, which can handle online prediction QPS diff --git a/automl/apiv1/automlpb/io.pb.go b/automl/apiv1/automlpb/io.pb.go index 0f0369f7ee26..3700a254ee1a 100644 --- a/automl/apiv1/automlpb/io.pb.go +++ b/automl/apiv1/automlpb/io.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/automl/v1/io.proto package automlpb @@ -67,16 +67,16 @@ const ( // * `ML_USE` - Identifies the data set that the current row (file) applies // to. // -// This value can be one of the following: -// * `TRAIN` - Rows in this file are used to train the model. -// * `TEST` - Rows in this file are used to test the model during training. -// * `UNASSIGNED` - Rows in this file are not categorized. They are -// Automatically divided into train and test data. 80% for training and -// 20% for testing. +// This value can be one of the following: +// * `TRAIN` - Rows in this file are used to train the model. +// * `TEST` - Rows in this file are used to test the model during training. +// * `UNASSIGNED` - Rows in this file are not categorized. They are +// Automatically divided into train and test data. 80% for training and +// 20% for testing. // -// - `GCS_FILE_PATH` - The Google Cloud Storage location of an image of up to -// 30MB in size. Supported extensions: .JPEG, .GIF, .PNG, .WEBP, .BMP, -// .TIFF, .ICO. +// - `GCS_FILE_PATH` - The Google Cloud Storage location of an image of up to +// 30MB in size. Supported extensions: .JPEG, .GIF, .PNG, .WEBP, .BMP, +// .TIFF, .ICO. // // * `LABEL` - A label that identifies the object in the image. // @@ -103,26 +103,26 @@ const ( // * `ML_USE` - Identifies the data set that the current row (file) applies // to. // -// This value can be one of the following: -// * `TRAIN` - Rows in this file are used to train the model. -// * `TEST` - Rows in this file are used to test the model during training. -// * `UNASSIGNED` - Rows in this file are not categorized. They are -// Automatically divided into train and test data. 80% for training and -// 20% for testing. +// This value can be one of the following: +// * `TRAIN` - Rows in this file are used to train the model. +// * `TEST` - Rows in this file are used to test the model during training. +// * `UNASSIGNED` - Rows in this file are not categorized. They are +// Automatically divided into train and test data. 80% for training and +// 20% for testing. // -// - `GCS_FILE_PATH` - The Google Cloud Storage location of an image of up to -// 30MB in size. Supported extensions: .JPEG, .GIF, .PNG. Each image -// is assumed to be exhaustively labeled. +// - `GCS_FILE_PATH` - The Google Cloud Storage location of an image of up to +// 30MB in size. Supported extensions: .JPEG, .GIF, .PNG. Each image +// is assumed to be exhaustively labeled. // -// - `LABEL` - A label that identifies the object in the image specified by the -// `BOUNDING_BOX`. +// - `LABEL` - A label that identifies the object in the image specified by the +// `BOUNDING_BOX`. // -// - `BOUNDING BOX` - The vertices of an object in the example image. -// The minimum allowed `BOUNDING_BOX` edge length is 0.01, and no more than -// 500 `BOUNDING_BOX` instances per image are allowed (one `BOUNDING_BOX` -// per line). If an image has no looked for objects then it should be -// mentioned just once with no LABEL and the ",,,,,,," in place of the -// `BOUNDING_BOX`. +// - `BOUNDING BOX` - The vertices of an object in the example image. +// The minimum allowed `BOUNDING_BOX` edge length is 0.01, and no more than +// 500 `BOUNDING_BOX` instances per image are allowed (one `BOUNDING_BOX` +// per line). If an image has no looked for objects then it should be +// mentioned just once with no LABEL and the ",,,,,,," in place of the +// `BOUNDING_BOX`. // // **Four sample rows:** // @@ -247,16 +247,16 @@ const ( // * `ML_USE` - Identifies the data set that the current row (file) applies // to. // -// This value can be one of the following: -// * `TRAIN` - Rows in this file are used to train the model. -// * `TEST` - Rows in this file are used to test the model during training. -// * `UNASSIGNED` - Rows in this file are not categorized. They are -// Automatically divided into train and test data. 80% for training and -// 20% for testing.. +// This value can be one of the following: +// * `TRAIN` - Rows in this file are used to train the model. +// * `TEST` - Rows in this file are used to test the model during training. +// * `UNASSIGNED` - Rows in this file are not categorized. They are +// Automatically divided into train and test data. 80% for training and +// 20% for testing.. // -// - `GCS_FILE_PATH` - a Identifies JSON Lines (.JSONL) file stored in -// Google Cloud Storage that contains in-line text in-line as documents -// for model training. +// - `GCS_FILE_PATH` - a Identifies JSON Lines (.JSONL) file stored in +// Google Cloud Storage that contains in-line text in-line as documents +// for model training. // // After the training data set has been determined from the `TRAIN` and // `UNASSIGNED` CSV files, the training data is divided into train and @@ -428,29 +428,29 @@ const ( // * `ML_USE` - Identifies the data set that the current row (file) applies // to. // -// This value can be one of the following: -// * `TRAIN` - Rows in this file are used to train the model. -// * `TEST` - Rows in this file are used to test the model during training. -// * `UNASSIGNED` - Rows in this file are not categorized. They are -// Automatically divided into train and test data. 80% for training and -// 20% for testing. -// -// - `TEXT_SNIPPET` and `GCS_FILE_PATH` are distinguished by a pattern. If -// the column content is a valid Google Cloud Storage file path, that is, -// prefixed by "gs://", it is treated as a `GCS_FILE_PATH`. Otherwise, if -// the content is enclosed in double quotes (""), it is treated as a -// `TEXT_SNIPPET`. For `GCS_FILE_PATH`, the path must lead to a -// file with supported extension and UTF-8 encoding, for example, -// "gs://folder/content.txt" AutoML imports the file content -// as a text snippet. For `TEXT_SNIPPET`, AutoML imports the column content -// excluding quotes. In both cases, size of the content must be 10MB or -// less in size. For zip files, the size of each file inside the zip must be -// 10MB or less in size. -// -// For the `MULTICLASS` classification type, at most one `LABEL` is allowed. -// -// The `ML_USE` and `LABEL` columns are optional. -// Supported file extensions: .TXT, .PDF, .TIF, .TIFF, .ZIP +// This value can be one of the following: +// * `TRAIN` - Rows in this file are used to train the model. +// * `TEST` - Rows in this file are used to test the model during training. +// * `UNASSIGNED` - Rows in this file are not categorized. They are +// Automatically divided into train and test data. 80% for training and +// 20% for testing. +// +// - `TEXT_SNIPPET` and `GCS_FILE_PATH` are distinguished by a pattern. If +// the column content is a valid Google Cloud Storage file path, that is, +// prefixed by "gs://", it is treated as a `GCS_FILE_PATH`. Otherwise, if +// the content is enclosed in double quotes (""), it is treated as a +// `TEXT_SNIPPET`. For `GCS_FILE_PATH`, the path must lead to a +// file with supported extension and UTF-8 encoding, for example, +// "gs://folder/content.txt" AutoML imports the file content +// as a text snippet. For `TEXT_SNIPPET`, AutoML imports the column content +// excluding quotes. In both cases, size of the content must be 10MB or +// less in size. For zip files, the size of each file inside the zip must be +// 10MB or less in size. +// +// For the `MULTICLASS` classification type, at most one `LABEL` is allowed. +// +// The `ML_USE` and `LABEL` columns are optional. +// Supported file extensions: .TXT, .PDF, .TIF, .TIFF, .ZIP // // A maximum of 100 unique labels are allowed per CSV row. // @@ -474,44 +474,44 @@ const ( // * `ML_USE` - Identifies the data set that the current row (file) applies // to. // -// This value can be one of the following: -// * `TRAIN` - Rows in this file are used to train the model. -// * `TEST` - Rows in this file are used to test the model during training. -// * `UNASSIGNED` - Rows in this file are not categorized. They are -// Automatically divided into train and test data. 80% for training and -// 20% for testing. -// -// - `TEXT_SNIPPET` and `GCS_FILE_PATH` are distinguished by a pattern. If -// the column content is a valid Google Cloud Storage file path, that is, -// prefixed by "gs://", it is treated as a `GCS_FILE_PATH`. Otherwise, if -// the content is enclosed in double quotes (""), it is treated as a -// `TEXT_SNIPPET`. For `GCS_FILE_PATH`, the path must lead to a -// file with supported extension and UTF-8 encoding, for example, -// "gs://folder/content.txt" AutoML imports the file content -// as a text snippet. For `TEXT_SNIPPET`, AutoML imports the column content -// excluding quotes. In both cases, size of the content must be 128kB or -// less in size. For zip files, the size of each file inside the zip must be -// 128kB or less in size. -// -// The `ML_USE` and `SENTIMENT` columns are optional. -// Supported file extensions: .TXT, .PDF, .TIF, .TIFF, .ZIP -// -// - `SENTIMENT` - An integer between 0 and -// Dataset.text_sentiment_dataset_metadata.sentiment_max -// (inclusive). Describes the ordinal of the sentiment - higher -// value means a more positive sentiment. All the values are -// completely relative, i.e. neither 0 needs to mean a negative or -// neutral sentiment nor sentiment_max needs to mean a positive one - -// it is just required that 0 is the least positive sentiment -// in the data, and sentiment_max is the most positive one. -// The SENTIMENT shouldn't be confused with "score" or "magnitude" -// from the previous Natural Language Sentiment Analysis API. -// All SENTIMENT values between 0 and sentiment_max must be -// represented in the imported data. On prediction the same 0 to -// sentiment_max range will be used. The difference between -// neighboring sentiment values needs not to be uniform, e.g. 1 and -// 2 may be similar whereas the difference between 2 and 3 may be -// large. +// This value can be one of the following: +// * `TRAIN` - Rows in this file are used to train the model. +// * `TEST` - Rows in this file are used to test the model during training. +// * `UNASSIGNED` - Rows in this file are not categorized. They are +// Automatically divided into train and test data. 80% for training and +// 20% for testing. +// +// - `TEXT_SNIPPET` and `GCS_FILE_PATH` are distinguished by a pattern. If +// the column content is a valid Google Cloud Storage file path, that is, +// prefixed by "gs://", it is treated as a `GCS_FILE_PATH`. Otherwise, if +// the content is enclosed in double quotes (""), it is treated as a +// `TEXT_SNIPPET`. For `GCS_FILE_PATH`, the path must lead to a +// file with supported extension and UTF-8 encoding, for example, +// "gs://folder/content.txt" AutoML imports the file content +// as a text snippet. For `TEXT_SNIPPET`, AutoML imports the column content +// excluding quotes. In both cases, size of the content must be 128kB or +// less in size. For zip files, the size of each file inside the zip must be +// 128kB or less in size. +// +// The `ML_USE` and `SENTIMENT` columns are optional. +// Supported file extensions: .TXT, .PDF, .TIF, .TIFF, .ZIP +// +// - `SENTIMENT` - An integer between 0 and +// Dataset.text_sentiment_dataset_metadata.sentiment_max +// (inclusive). Describes the ordinal of the sentiment - higher +// value means a more positive sentiment. All the values are +// completely relative, i.e. neither 0 needs to mean a negative or +// neutral sentiment nor sentiment_max needs to mean a positive one - +// it is just required that 0 is the least positive sentiment +// in the data, and sentiment_max is the most positive one. +// The SENTIMENT shouldn't be confused with "score" or "magnitude" +// from the previous Natural Language Sentiment Analysis API. +// All SENTIMENT values between 0 and sentiment_max must be +// represented in the imported data. On prediction the same 0 to +// sentiment_max range will be used. The difference between +// neighboring sentiment values needs not to be uniform, e.g. 1 and +// 2 may be similar whereas the difference between 2 and 3 may be +// large. // // Sample rows: // @@ -660,7 +660,6 @@ type InputConfig struct { // The source of the input. // // Types that are assignable to Source: - // // *InputConfig_GcsSource Source isInputConfig_Source `protobuf_oneof:"source"` // Additional domain-specific parameters describing the semantic of the @@ -671,10 +670,9 @@ type InputConfig struct { // // `schema_inference_version` // : (integer) This value must be supplied. - // - // The version of the - // algorithm to use for the initial inference of the - // column data types of the imported table. Allowed values: "1". + // The version of the + // algorithm to use for the initial inference of the + // column data types of the imported table. Allowed values: "1". Params map[string]string `protobuf:"bytes,2,rep,name=params,proto3" json:"params,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` } @@ -1034,7 +1032,6 @@ type BatchPredictInputConfig struct { // The source of the input. // // Types that are assignable to Source: - // // *BatchPredictInputConfig_GcsSource Source isBatchPredictInputConfig_Source `protobuf_oneof:"source"` } @@ -1186,7 +1183,6 @@ type OutputConfig struct { // The destination of the output. // // Types that are assignable to Destination: - // // *OutputConfig_GcsDestination Destination isOutputConfig_Destination `protobuf_oneof:"destination"` } @@ -1512,7 +1508,6 @@ type BatchPredictOutputConfig struct { // The destination of the output. // // Types that are assignable to Destination: - // // *BatchPredictOutputConfig_GcsDestination Destination isBatchPredictOutputConfig_Destination `protobuf_oneof:"destination"` } @@ -1584,7 +1579,6 @@ type ModelExportOutputConfig struct { // The destination of the output. // // Types that are assignable to Destination: - // // *ModelExportOutputConfig_GcsDestination Destination isModelExportOutputConfig_Destination `protobuf_oneof:"destination"` // The format in which the model must be exported. The available, and default, @@ -1592,39 +1586,38 @@ type ModelExportOutputConfig struct { // combination doesn't have a format listed, it means its models are not // exportable): // - // - For Image Classification mobile-low-latency-1, mobile-versatile-1, - // mobile-high-accuracy-1: - // "tflite" (default), "edgetpu_tflite", "tf_saved_model", "tf_js", - // "docker". + // * For Image Classification mobile-low-latency-1, mobile-versatile-1, + // mobile-high-accuracy-1: + // "tflite" (default), "edgetpu_tflite", "tf_saved_model", "tf_js", + // "docker". // - // - For Image Classification mobile-core-ml-low-latency-1, - // mobile-core-ml-versatile-1, mobile-core-ml-high-accuracy-1: - // "core_ml" (default). - // - // - For Image Object Detection mobile-low-latency-1, mobile-versatile-1, - // mobile-high-accuracy-1: - // "tflite", "tf_saved_model", "tf_js". + // * For Image Classification mobile-core-ml-low-latency-1, + // mobile-core-ml-versatile-1, mobile-core-ml-high-accuracy-1: + // "core_ml" (default). // + // * For Image Object Detection mobile-low-latency-1, mobile-versatile-1, + // mobile-high-accuracy-1: + // "tflite", "tf_saved_model", "tf_js". // Formats description: // - // - tflite - Used for Android mobile devices. - // - edgetpu_tflite - Used for [Edge TPU](https://cloud.google.com/edge-tpu/) - // devices. - // - tf_saved_model - A tensorflow model in SavedModel format. - // - tf_js - A [TensorFlow.js](https://www.tensorflow.org/js) model that can - // be used in the browser and in Node.js using JavaScript. - // - docker - Used for Docker containers. Use the params field to customize - // the container. The container is verified to work correctly on - // ubuntu 16.04 operating system. See more at - // [containers - // quickstart](https://cloud.google.com/vision/automl/docs/containers-gcs-quickstart) - // - core_ml - Used for iOS mobile devices. + // * tflite - Used for Android mobile devices. + // * edgetpu_tflite - Used for [Edge TPU](https://cloud.google.com/edge-tpu/) + // devices. + // * tf_saved_model - A tensorflow model in SavedModel format. + // * tf_js - A [TensorFlow.js](https://www.tensorflow.org/js) model that can + // be used in the browser and in Node.js using JavaScript. + // * docker - Used for Docker containers. Use the params field to customize + // the container. The container is verified to work correctly on + // ubuntu 16.04 operating system. See more at + // [containers + // quickstart](https://cloud.google.com/vision/automl/docs/containers-gcs-quickstart) + // * core_ml - Used for iOS mobile devices. ModelFormat string `protobuf:"bytes,4,opt,name=model_format,json=modelFormat,proto3" json:"model_format,omitempty"` // Additional model-type and format specific parameters describing the // requirements for the to be exported model files, any string must be up to // 25000 characters long. // - // - For `docker` format: + // * For `docker` format: // `cpu_architecture` - (string) "x86_64" (default). // `gpu_architecture` - (string) "none" (default), "nvidia". Params map[string]string `protobuf:"bytes,2,rep,name=params,proto3" json:"params,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` @@ -1697,14 +1690,13 @@ type isModelExportOutputConfig_Destination interface { type ModelExportOutputConfig_GcsDestination struct { // Required. The Google Cloud Storage location where the model is to be written to. // This location may only be set for the following model formats: + // "tflite", "edgetpu_tflite", "tf_saved_model", "tf_js", "core_ml". // - // "tflite", "edgetpu_tflite", "tf_saved_model", "tf_js", "core_ml". - // - // Under the directory given as the destination a new one with name - // "model-export--", - // where timestamp is in YYYY-MM-DDThh:mm:ss.sssZ ISO-8601 format, - // will be created. Inside the model and any of its supporting files - // will be written. + // Under the directory given as the destination a new one with name + // "model-export--", + // where timestamp is in YYYY-MM-DDThh:mm:ss.sssZ ISO-8601 format, + // will be created. Inside the model and any of its supporting files + // will be written. GcsDestination *GcsDestination `protobuf:"bytes,1,opt,name=gcs_destination,json=gcsDestination,proto3,oneof"` } diff --git a/automl/apiv1/automlpb/model.pb.go b/automl/apiv1/automlpb/model.pb.go index eb76620c861e..92fdbd5df5ff 100644 --- a/automl/apiv1/automlpb/model.pb.go +++ b/automl/apiv1/automlpb/model.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/automl/v1/model.proto package automlpb @@ -101,7 +101,6 @@ type Model struct { // Must match the metadata type of the dataset used to train the model. // // Types that are assignable to ModelMetadata: - // // *Model_TranslationModelMetadata // *Model_ImageClassificationModelMetadata // *Model_TextClassificationModelMetadata diff --git a/automl/apiv1/automlpb/model_evaluation.pb.go b/automl/apiv1/automlpb/model_evaluation.pb.go index d7cf4a964bd6..eb5ade55a167 100644 --- a/automl/apiv1/automlpb/model_evaluation.pb.go +++ b/automl/apiv1/automlpb/model_evaluation.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/automl/v1/model_evaluation.proto package automlpb @@ -46,7 +46,6 @@ type ModelEvaluation struct { // Output only. Problem type specific evaluation metrics. // // Types that are assignable to Metrics: - // // *ModelEvaluation_ClassificationEvaluationMetrics // *ModelEvaluation_TranslationEvaluationMetrics // *ModelEvaluation_ImageObjectDetectionEvaluationMetrics diff --git a/automl/apiv1/automlpb/operations.pb.go b/automl/apiv1/automlpb/operations.pb.go index 99616aac63d2..94853d8f9a3b 100644 --- a/automl/apiv1/automlpb/operations.pb.go +++ b/automl/apiv1/automlpb/operations.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/automl/v1/operations.proto package automlpb @@ -47,7 +47,6 @@ type OperationMetadata struct { // the presence allows to distinguish different types of operations. // // Types that are assignable to Details: - // // *OperationMetadata_DeleteDetails // *OperationMetadata_DeployModelDetails // *OperationMetadata_UndeployModelDetails @@ -672,7 +671,6 @@ type ExportDataOperationMetadata_ExportDataOutputInfo struct { // The output location to which the exported data is written. // // Types that are assignable to OutputLocation: - // // *ExportDataOperationMetadata_ExportDataOutputInfo_GcsOutputDirectory OutputLocation isExportDataOperationMetadata_ExportDataOutputInfo_OutputLocation `protobuf_oneof:"output_location"` } @@ -747,7 +745,6 @@ type BatchPredictOperationMetadata_BatchPredictOutputInfo struct { // The output location into which prediction output is written. // // Types that are assignable to OutputLocation: - // // *BatchPredictOperationMetadata_BatchPredictOutputInfo_GcsOutputDirectory OutputLocation isBatchPredictOperationMetadata_BatchPredictOutputInfo_OutputLocation `protobuf_oneof:"output_location"` } diff --git a/automl/apiv1/automlpb/prediction_service.pb.go b/automl/apiv1/automlpb/prediction_service.pb.go index ab21cfd8cc71..075d862dcbb9 100644 --- a/automl/apiv1/automlpb/prediction_service.pb.go +++ b/automl/apiv1/automlpb/prediction_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/automl/v1/prediction_service.proto package automlpb @@ -55,37 +55,33 @@ type PredictRequest struct { // Additional domain-specific parameters, any string must be up to 25000 // characters long. // - // # AutoML Vision Classification + // AutoML Vision Classification // // `score_threshold` // : (float) A value from 0.0 to 1.0. When the model + // makes predictions for an image, it will only produce results that have + // at least this confidence score. The default is 0.5. // - // makes predictions for an image, it will only produce results that have - // at least this confidence score. The default is 0.5. - // - // # AutoML Vision Object Detection + // AutoML Vision Object Detection // // `score_threshold` // : (float) When Model detects objects on the image, - // - // it will only produce bounding boxes which have at least this - // confidence score. Value in 0 to 1 range, default is 0.5. + // it will only produce bounding boxes which have at least this + // confidence score. Value in 0 to 1 range, default is 0.5. // // `max_bounding_box_count` // : (int64) The maximum number of bounding + // boxes returned. The default is 100. The + // number of returned bounding boxes might be limited by the server. // - // boxes returned. The default is 100. The - // number of returned bounding boxes might be limited by the server. - // - // # AutoML Tables + // AutoML Tables // // `feature_importance` // : (boolean) Whether // [feature_importance][google.cloud.automl.v1.TablesModelColumnInfo.feature_importance] - // - // is populated in the returned list of - // [TablesAnnotation][google.cloud.automl.v1.TablesAnnotation] - // objects. The default is false. + // is populated in the returned list of + // [TablesAnnotation][google.cloud.automl.v1.TablesAnnotation] + // objects. The default is false. Params map[string]string `protobuf:"bytes,3,rep,name=params,proto3" json:"params,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` } @@ -163,23 +159,22 @@ type PredictResponse struct { PreprocessedInput *ExamplePayload `protobuf:"bytes,3,opt,name=preprocessed_input,json=preprocessedInput,proto3" json:"preprocessed_input,omitempty"` // Additional domain-specific prediction response metadata. // - // # AutoML Vision Object Detection + // AutoML Vision Object Detection // // `max_bounding_box_count` // : (int64) The maximum number of bounding boxes to return per image. // - // # AutoML Natural Language Sentiment Analysis + // AutoML Natural Language Sentiment Analysis // // `sentiment_score` // : (float, deprecated) A value between -1 and 1, - // - // -1 maps to least positive sentiment, while 1 maps to the most positive - // one and the higher the score, the more positive the sentiment in the - // document is. Yet these values are relative to the training data, so - // e.g. if all data was positive then -1 is also positive (though - // the least). - // `sentiment_score` is not the same as "score" and "magnitude" - // from Sentiment Analysis in the Natural Language API. + // -1 maps to least positive sentiment, while 1 maps to the most positive + // one and the higher the score, the more positive the sentiment in the + // document is. Yet these values are relative to the training data, so + // e.g. if all data was positive then -1 is also positive (though + // the least). + // `sentiment_score` is not the same as "score" and "magnitude" + // from Sentiment Analysis in the Natural Language API. Metadata map[string]string `protobuf:"bytes,2,rep,name=metadata,proto3" json:"metadata,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` } @@ -252,97 +247,87 @@ type BatchPredictRequest struct { // Additional domain-specific parameters for the predictions, any string must // be up to 25000 characters long. // - // # AutoML Natural Language Classification + // AutoML Natural Language Classification // // `score_threshold` // : (float) A value from 0.0 to 1.0. When the model + // makes predictions for a text snippet, it will only produce results + // that have at least this confidence score. The default is 0.5. // - // makes predictions for a text snippet, it will only produce results - // that have at least this confidence score. The default is 0.5. // - // # AutoML Vision Classification + // AutoML Vision Classification // // `score_threshold` // : (float) A value from 0.0 to 1.0. When the model + // makes predictions for an image, it will only produce results that + // have at least this confidence score. The default is 0.5. // - // makes predictions for an image, it will only produce results that - // have at least this confidence score. The default is 0.5. - // - // # AutoML Vision Object Detection + // AutoML Vision Object Detection // // `score_threshold` // : (float) When Model detects objects on the image, - // - // it will only produce bounding boxes which have at least this - // confidence score. Value in 0 to 1 range, default is 0.5. + // it will only produce bounding boxes which have at least this + // confidence score. Value in 0 to 1 range, default is 0.5. // // `max_bounding_box_count` // : (int64) The maximum number of bounding - // - // boxes returned per image. The default is 100, the - // number of bounding boxes returned might be limited by the server. - // + // boxes returned per image. The default is 100, the + // number of bounding boxes returned might be limited by the server. // AutoML Video Intelligence Classification // // `score_threshold` // : (float) A value from 0.0 to 1.0. When the model - // - // makes predictions for a video, it will only produce results that - // have at least this confidence score. The default is 0.5. + // makes predictions for a video, it will only produce results that + // have at least this confidence score. The default is 0.5. // // `segment_classification` // : (boolean) Set to true to request - // - // segment-level classification. AutoML Video Intelligence returns - // labels and their confidence scores for the entire segment of the - // video that user specified in the request configuration. - // The default is true. + // segment-level classification. AutoML Video Intelligence returns + // labels and their confidence scores for the entire segment of the + // video that user specified in the request configuration. + // The default is true. // // `shot_classification` // : (boolean) Set to true to request shot-level + // classification. AutoML Video Intelligence determines the boundaries + // for each camera shot in the entire segment of the video that user + // specified in the request configuration. AutoML Video Intelligence + // then returns labels and their confidence scores for each detected + // shot, along with the start and end time of the shot. + // The default is false. // - // classification. AutoML Video Intelligence determines the boundaries - // for each camera shot in the entire segment of the video that user - // specified in the request configuration. AutoML Video Intelligence - // then returns labels and their confidence scores for each detected - // shot, along with the start and end time of the shot. - // The default is false. - // - // WARNING: Model evaluation is not done for this classification type, - // the quality of it depends on training data, but there are no metrics - // provided to describe that quality. + // WARNING: Model evaluation is not done for this classification type, + // the quality of it depends on training data, but there are no metrics + // provided to describe that quality. // // `1s_interval_classification` // : (boolean) Set to true to request + // classification for a video at one-second intervals. AutoML Video + // Intelligence returns labels and their confidence scores for each + // second of the entire segment of the video that user specified in the + // request configuration. The default is false. // - // classification for a video at one-second intervals. AutoML Video - // Intelligence returns labels and their confidence scores for each - // second of the entire segment of the video that user specified in the - // request configuration. The default is false. + // WARNING: Model evaluation is not done for this classification + // type, the quality of it depends on training data, but there are no + // metrics provided to describe that quality. // - // WARNING: Model evaluation is not done for this classification - // type, the quality of it depends on training data, but there are no - // metrics provided to describe that quality. - // - // # AutoML Video Intelligence Object Tracking + // AutoML Video Intelligence Object Tracking // // `score_threshold` // : (float) When Model detects objects on video frames, - // - // it will only produce bounding boxes which have at least this - // confidence score. Value in 0 to 1 range, default is 0.5. + // it will only produce bounding boxes which have at least this + // confidence score. Value in 0 to 1 range, default is 0.5. // // `max_bounding_box_count` // : (int64) The maximum number of bounding - // - // boxes returned per image. The default is 100, the - // number of bounding boxes returned might be limited by the server. + // boxes returned per image. The default is 100, the + // number of bounding boxes returned might be limited by the server. // // `min_bounding_box_size` // : (float) Only bounding boxes with shortest edge + // at least that long as a relative value of video frame size are + // returned. Value in 0 to 1 range. Default is 0. // - // at least that long as a relative value of video frame size are - // returned. Value in 0 to 1 range. Default is 0. Params map[string]string `protobuf:"bytes,5,rep,name=params,proto3" json:"params,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` } @@ -416,12 +401,12 @@ type BatchPredictResult struct { // Additional domain-specific prediction response metadata. // - // # AutoML Vision Object Detection + // AutoML Vision Object Detection // // `max_bounding_box_count` // : (int64) The maximum number of bounding boxes returned per image. // - // # AutoML Video Intelligence Object Tracking + // AutoML Video Intelligence Object Tracking // // `max_bounding_box_count` // : (int64) The maximum number of bounding boxes returned per frame. @@ -756,38 +741,38 @@ type PredictionServiceClient interface { // returned in the response. // Available for following ML scenarios, and their expected request payloads: // - // # AutoML Vision Classification + // AutoML Vision Classification // // * An image in .JPEG, .GIF or .PNG format, image_bytes up to 30MB. // - // # AutoML Vision Object Detection + // AutoML Vision Object Detection // // * An image in .JPEG, .GIF or .PNG format, image_bytes up to 30MB. // - // # AutoML Natural Language Classification + // AutoML Natural Language Classification // // * A TextSnippet up to 60,000 characters, UTF-8 encoded or a document in // .PDF, .TIF or .TIFF format with size upto 2MB. // - // # AutoML Natural Language Entity Extraction + // AutoML Natural Language Entity Extraction // - // - A TextSnippet up to 10,000 characters, UTF-8 NFC encoded or a document - // in .PDF, .TIF or .TIFF format with size upto 20MB. + // * A TextSnippet up to 10,000 characters, UTF-8 NFC encoded or a document + // in .PDF, .TIF or .TIFF format with size upto 20MB. // - // # AutoML Natural Language Sentiment Analysis + // AutoML Natural Language Sentiment Analysis // // * A TextSnippet up to 60,000 characters, UTF-8 encoded or a document in // .PDF, .TIF or .TIFF format with size upto 2MB. // - // # AutoML Translation + // AutoML Translation // // * A TextSnippet up to 25,000 characters, UTF-8 encoded. // - // # AutoML Tables + // AutoML Tables // - // - A row with column values matching - // the columns of the model, up to 5MB. Not available for FORECASTING - // `prediction_type`. + // * A row with column values matching + // the columns of the model, up to 5MB. Not available for FORECASTING + // `prediction_type`. Predict(ctx context.Context, in *PredictRequest, opts ...grpc.CallOption) (*PredictResponse, error) // Perform a batch prediction. Unlike the online [Predict][google.cloud.automl.v1.PredictionService.Predict], batch // prediction result won't be immediately available in the response. Instead, @@ -839,38 +824,38 @@ type PredictionServiceServer interface { // returned in the response. // Available for following ML scenarios, and their expected request payloads: // - // # AutoML Vision Classification + // AutoML Vision Classification // // * An image in .JPEG, .GIF or .PNG format, image_bytes up to 30MB. // - // # AutoML Vision Object Detection + // AutoML Vision Object Detection // // * An image in .JPEG, .GIF or .PNG format, image_bytes up to 30MB. // - // # AutoML Natural Language Classification + // AutoML Natural Language Classification // // * A TextSnippet up to 60,000 characters, UTF-8 encoded or a document in // .PDF, .TIF or .TIFF format with size upto 2MB. // - // # AutoML Natural Language Entity Extraction + // AutoML Natural Language Entity Extraction // - // - A TextSnippet up to 10,000 characters, UTF-8 NFC encoded or a document - // in .PDF, .TIF or .TIFF format with size upto 20MB. + // * A TextSnippet up to 10,000 characters, UTF-8 NFC encoded or a document + // in .PDF, .TIF or .TIFF format with size upto 20MB. // - // # AutoML Natural Language Sentiment Analysis + // AutoML Natural Language Sentiment Analysis // // * A TextSnippet up to 60,000 characters, UTF-8 encoded or a document in // .PDF, .TIF or .TIFF format with size upto 2MB. // - // # AutoML Translation + // AutoML Translation // // * A TextSnippet up to 25,000 characters, UTF-8 encoded. // - // # AutoML Tables + // AutoML Tables // - // - A row with column values matching - // the columns of the model, up to 5MB. Not available for FORECASTING - // `prediction_type`. + // * A row with column values matching + // the columns of the model, up to 5MB. Not available for FORECASTING + // `prediction_type`. Predict(context.Context, *PredictRequest) (*PredictResponse, error) // Perform a batch prediction. Unlike the online [Predict][google.cloud.automl.v1.PredictionService.Predict], batch // prediction result won't be immediately available in the response. Instead, diff --git a/automl/apiv1/automlpb/service.pb.go b/automl/apiv1/automlpb/service.pb.go index acb53eaf34f2..be71b9194e09 100644 --- a/automl/apiv1/automlpb/service.pb.go +++ b/automl/apiv1/automlpb/service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/automl/v1/service.proto package automlpb @@ -159,11 +159,11 @@ type ListDatasetsRequest struct { Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // An expression for filtering the results of the request. // - // - `dataset_metadata` - for existence of the case (e.g. - // `image_classification_dataset_metadata:*`). Some examples of using the filter are: + // * `dataset_metadata` - for existence of the case (e.g. + // `image_classification_dataset_metadata:*`). Some examples of using the filter are: // - // - `translation_dataset_metadata:*` --> The dataset has - // `translation_dataset_metadata`. + // * `translation_dataset_metadata:*` --> The dataset has + // `translation_dataset_metadata`. Filter string `protobuf:"bytes,3,opt,name=filter,proto3" json:"filter,omitempty"` // Requested page size. Server may return fewer results than requested. // If unspecified, server will pick a default size. @@ -685,15 +685,13 @@ type ListModelsRequest struct { Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // An expression for filtering the results of the request. // - // - `model_metadata` - for existence of the case (e.g. - // `video_classification_model_metadata:*`). + // * `model_metadata` - for existence of the case (e.g. + // `video_classification_model_metadata:*`). + // * `dataset_id` - for = or !=. Some examples of using the filter are: // - // - `dataset_id` - for = or !=. Some examples of using the filter are: - // - // - `image_classification_model_metadata:*` --> The model has - // `image_classification_model_metadata`. - // - // - `dataset_id=5` --> The model was created from a dataset with ID 5. + // * `image_classification_model_metadata:*` --> The model has + // `image_classification_model_metadata`. + // * `dataset_id=5` --> The model was created from a dataset with ID 5. Filter string `protobuf:"bytes,3,opt,name=filter,proto3" json:"filter,omitempty"` // Requested page size. PageSize int32 `protobuf:"varint,4,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"` @@ -939,7 +937,6 @@ type DeployModelRequest struct { // The per-domain specific deployment parameters. // // Types that are assignable to ModelDeploymentMetadata: - // // *DeployModelRequest_ImageObjectDetectionModelDeploymentMetadata // *DeployModelRequest_ImageClassificationModelDeploymentMetadata ModelDeploymentMetadata isDeployModelRequest_ModelDeploymentMetadata `protobuf_oneof:"model_deployment_metadata"` @@ -1197,15 +1194,15 @@ type ListModelEvaluationsRequest struct { Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // Required. An expression for filtering the results of the request. // - // - `annotation_spec_id` - for =, != or existence. See example below for - // the last. + // * `annotation_spec_id` - for =, != or existence. See example below for + // the last. // // Some examples of using the filter are: // - // - `annotation_spec_id!=4` --> The model evaluation was done for - // annotation spec with ID different than 4. - // - `NOT annotation_spec_id:*` --> The model evaluation was done for - // aggregate of all annotation specs. + // * `annotation_spec_id!=4` --> The model evaluation was done for + // annotation spec with ID different than 4. + // * `NOT annotation_spec_id:*` --> The model evaluation was done for + // aggregate of all annotation specs. Filter string `protobuf:"bytes,3,opt,name=filter,proto3" json:"filter,omitempty"` // Requested page size. PageSize int32 `protobuf:"varint,4,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"` @@ -2228,9 +2225,7 @@ type AutoMlClient interface { // For Tables: // * A // [schema_inference_version][google.cloud.automl.v1.InputConfig.params] - // - // parameter must be explicitly set. - // + // parameter must be explicitly set. // Returns an empty response in the // [response][google.longrunning.Operation.response] field when it completes. ImportData(ctx context.Context, in *ImportDataRequest, opts ...grpc.CallOption) (*longrunning.Operation, error) @@ -2262,8 +2257,7 @@ type AutoMlClient interface { // same parameters has no effect. Deploying with different parametrs // (as e.g. changing // [node_number][google.cloud.automl.v1p1beta.ImageObjectDetectionModelDeploymentMetadata.node_number]) - // - // will reset the deployment state without pausing the model's availability. + // will reset the deployment state without pausing the model's availability. // // Only applicable for Text Classification, Image Object Detection , Tables, and Image Segmentation; all other domains manage // deployment automatically. @@ -2485,9 +2479,7 @@ type AutoMlServer interface { // For Tables: // * A // [schema_inference_version][google.cloud.automl.v1.InputConfig.params] - // - // parameter must be explicitly set. - // + // parameter must be explicitly set. // Returns an empty response in the // [response][google.longrunning.Operation.response] field when it completes. ImportData(context.Context, *ImportDataRequest) (*longrunning.Operation, error) @@ -2519,8 +2511,7 @@ type AutoMlServer interface { // same parameters has no effect. Deploying with different parametrs // (as e.g. changing // [node_number][google.cloud.automl.v1p1beta.ImageObjectDetectionModelDeploymentMetadata.node_number]) - // - // will reset the deployment state without pausing the model's availability. + // will reset the deployment state without pausing the model's availability. // // Only applicable for Text Classification, Image Object Detection , Tables, and Image Segmentation; all other domains manage // deployment automatically. diff --git a/automl/apiv1/automlpb/text.pb.go b/automl/apiv1/automlpb/text.pb.go index f273d1b90fd1..88412f805539 100644 --- a/automl/apiv1/automlpb/text.pb.go +++ b/automl/apiv1/automlpb/text.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/automl/v1/text.proto package automlpb diff --git a/automl/apiv1/automlpb/text_extraction.pb.go b/automl/apiv1/automlpb/text_extraction.pb.go index 7383338e81c3..f37b43e7ab63 100644 --- a/automl/apiv1/automlpb/text_extraction.pb.go +++ b/automl/apiv1/automlpb/text_extraction.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/automl/v1/text_extraction.proto package automlpb @@ -45,7 +45,6 @@ type TextExtractionAnnotation struct { // text relation. // // Types that are assignable to Annotation: - // // *TextExtractionAnnotation_TextSegment Annotation isTextExtractionAnnotation_Annotation `protobuf_oneof:"annotation"` // Output only. A confidence estimate between 0.0 and 1.0. A higher value diff --git a/automl/apiv1/automlpb/text_segment.pb.go b/automl/apiv1/automlpb/text_segment.pb.go index 786b39a759ea..4e6900e95b51 100644 --- a/automl/apiv1/automlpb/text_segment.pb.go +++ b/automl/apiv1/automlpb/text_segment.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/automl/v1/text_segment.proto package automlpb diff --git a/automl/apiv1/automlpb/text_sentiment.pb.go b/automl/apiv1/automlpb/text_sentiment.pb.go index 9a44dc411d88..071da67c7ed7 100644 --- a/automl/apiv1/automlpb/text_sentiment.pb.go +++ b/automl/apiv1/automlpb/text_sentiment.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/automl/v1/text_sentiment.proto package automlpb @@ -49,9 +49,7 @@ type TextSentimentAnnotation struct { // with higher value meaning more positive sentiment. They are completely // relative, i.e. 0 means least positive sentiment and sentiment_max means // the most positive from the sentiments present in the train data. Therefore - // - // e.g. if train data had only negative sentiment, then sentiment_max, would - // + // e.g. if train data had only negative sentiment, then sentiment_max, would // be still negative (although least negative). // The sentiment shouldn't be confused with "score" or "magnitude" // from the previous Natural Language Sentiment Analysis API. diff --git a/automl/apiv1/automlpb/translation.pb.go b/automl/apiv1/automlpb/translation.pb.go index 6108325437ff..4b5a904f6d88 100644 --- a/automl/apiv1/automlpb/translation.pb.go +++ b/automl/apiv1/automlpb/translation.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/automl/v1/translation.proto package automlpb diff --git a/automl/apiv1/doc.go b/automl/apiv1/doc.go index 4ed33405033a..8bcde170a1ed 100644 --- a/automl/apiv1/doc.go +++ b/automl/apiv1/doc.go @@ -81,6 +81,8 @@ package automl // import "cloud.google.com/go/automl/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -169,3 +171,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/automl/apiv1/gapic_metadata.json b/automl/apiv1/gapic_metadata.json index e31b1eb209b6..315d9a1b87e3 100644 --- a/automl/apiv1/gapic_metadata.json +++ b/automl/apiv1/gapic_metadata.json @@ -101,6 +101,101 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "CreateDataset": { + "methods": [ + "CreateDataset" + ] + }, + "CreateModel": { + "methods": [ + "CreateModel" + ] + }, + "DeleteDataset": { + "methods": [ + "DeleteDataset" + ] + }, + "DeleteModel": { + "methods": [ + "DeleteModel" + ] + }, + "DeployModel": { + "methods": [ + "DeployModel" + ] + }, + "ExportData": { + "methods": [ + "ExportData" + ] + }, + "ExportModel": { + "methods": [ + "ExportModel" + ] + }, + "GetAnnotationSpec": { + "methods": [ + "GetAnnotationSpec" + ] + }, + "GetDataset": { + "methods": [ + "GetDataset" + ] + }, + "GetModel": { + "methods": [ + "GetModel" + ] + }, + "GetModelEvaluation": { + "methods": [ + "GetModelEvaluation" + ] + }, + "ImportData": { + "methods": [ + "ImportData" + ] + }, + "ListDatasets": { + "methods": [ + "ListDatasets" + ] + }, + "ListModelEvaluations": { + "methods": [ + "ListModelEvaluations" + ] + }, + "ListModels": { + "methods": [ + "ListModels" + ] + }, + "UndeployModel": { + "methods": [ + "UndeployModel" + ] + }, + "UpdateDataset": { + "methods": [ + "UpdateDataset" + ] + }, + "UpdateModel": { + "methods": [ + "UpdateModel" + ] + } + } } } }, @@ -120,6 +215,21 @@ ] } } + }, + "rest": { + "libraryClient": "PredictionClient", + "rpcs": { + "BatchPredict": { + "methods": [ + "BatchPredict" + ] + }, + "Predict": { + "methods": [ + "Predict" + ] + } + } } } } diff --git a/automl/apiv1/prediction_client.go b/automl/apiv1/prediction_client.go index b8a203c14cc2..dcf1dae0f078 100644 --- a/automl/apiv1/prediction_client.go +++ b/automl/apiv1/prediction_client.go @@ -17,9 +17,12 @@ package automl import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,12 +30,15 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" ) var newPredictionClientHook clientHook @@ -62,6 +68,13 @@ func defaultPredictionCallOptions() *PredictionCallOptions { } } +func defaultPredictionRESTCallOptions() *PredictionCallOptions { + return &PredictionCallOptions{ + Predict: []gax.CallOption{}, + BatchPredict: []gax.CallOption{}, + } +} + // internalPredictionClient is an interface that defines the methods available from Cloud AutoML API. type internalPredictionClient interface { Close() error @@ -286,6 +299,92 @@ func (c *predictionGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type predictionRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing PredictionClient + CallOptions **PredictionCallOptions +} + +// NewPredictionRESTClient creates a new prediction service rest client. +// +// AutoML Prediction API. +// +// On any input that is documented to expect a string parameter in +// snake_case or dash-case, either of those cases is accepted. +func NewPredictionRESTClient(ctx context.Context, opts ...option.ClientOption) (*PredictionClient, error) { + clientOpts := append(defaultPredictionRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultPredictionRESTCallOptions() + c := &predictionRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &PredictionClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultPredictionRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://automl.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://automl.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://automl.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *predictionRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *predictionRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *predictionRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *predictionGRPCClient) Predict(ctx context.Context, req *automlpb.PredictRequest, opts ...gax.CallOption) (*automlpb.PredictResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) @@ -332,9 +431,197 @@ func (c *predictionGRPCClient) BatchPredict(ctx context.Context, req *automlpb.B }, nil } +// Predict perform an online prediction. The prediction result is directly +// returned in the response. +// Available for following ML scenarios, and their expected request payloads: +// +// AutoML Vision Classification +// +// An image in .JPEG, .GIF or .PNG format, image_bytes up to 30MB. +// +// AutoML Vision Object Detection +// +// An image in .JPEG, .GIF or .PNG format, image_bytes up to 30MB. +// +// AutoML Natural Language Classification +// +// A TextSnippet up to 60,000 characters, UTF-8 encoded or a document in +// .PDF, .TIF or .TIFF format with size upto 2MB. +// +// AutoML Natural Language Entity Extraction +// +// A TextSnippet up to 10,000 characters, UTF-8 NFC encoded or a document +// in .PDF, .TIF or .TIFF format with size upto 20MB. +// +// AutoML Natural Language Sentiment Analysis +// +// A TextSnippet up to 60,000 characters, UTF-8 encoded or a document in +// .PDF, .TIF or .TIFF format with size upto 2MB. +// +// AutoML Translation +// +// A TextSnippet up to 25,000 characters, UTF-8 encoded. +// +// AutoML Tables +// +// A row with column values matching +// the columns of the model, up to 5MB. Not available for FORECASTING +// prediction_type. +func (c *predictionRESTClient) Predict(ctx context.Context, req *automlpb.PredictRequest, opts ...gax.CallOption) (*automlpb.PredictResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:predict", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).Predict[0:len((*c.CallOptions).Predict):len((*c.CallOptions).Predict)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &automlpb.PredictResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// BatchPredict perform a batch prediction. Unlike the online Predict, batch +// prediction result won’t be immediately available in the response. Instead, +// a long running operation object is returned. User can poll the operation +// result via GetOperation +// method. Once the operation is done, BatchPredictResult is returned in +// the response field. +// Available for following ML scenarios: +// +// AutoML Vision Classification +// +// AutoML Vision Object Detection +// +// AutoML Video Intelligence Classification +// +// AutoML Video Intelligence Object Tracking * AutoML Natural Language Classification +// +// AutoML Natural Language Entity Extraction +// +// AutoML Natural Language Sentiment Analysis +// +// AutoML Tables +func (c *predictionRESTClient) BatchPredict(ctx context.Context, req *automlpb.BatchPredictRequest, opts ...gax.CallOption) (*BatchPredictOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:batchPredict", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &BatchPredictOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + // BatchPredictOperation manages a long-running operation from BatchPredict. type BatchPredictOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // BatchPredictOperation returns a new BatchPredictOperation from a given name. @@ -345,10 +632,21 @@ func (c *predictionGRPCClient) BatchPredictOperation(name string) *BatchPredictO } } +// BatchPredictOperation returns a new BatchPredictOperation from a given name. +// The name must be that of a previously created BatchPredictOperation, possibly from a different process. +func (c *predictionRESTClient) BatchPredictOperation(name string) *BatchPredictOperation { + override := fmt.Sprintf("/v1/%s", name) + return &BatchPredictOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *BatchPredictOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*automlpb.BatchPredictResult, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp automlpb.BatchPredictResult if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -366,6 +664,7 @@ func (op *BatchPredictOperation) Wait(ctx context.Context, opts ...gax.CallOptio // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *BatchPredictOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*automlpb.BatchPredictResult, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp automlpb.BatchPredictResult if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/automl/apiv1/prediction_client_example_test.go b/automl/apiv1/prediction_client_example_test.go index 8f2305046add..f8d7a257958b 100644 --- a/automl/apiv1/prediction_client_example_test.go +++ b/automl/apiv1/prediction_client_example_test.go @@ -40,6 +40,23 @@ func ExampleNewPredictionClient() { _ = c } +func ExampleNewPredictionRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := automl.NewPredictionRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExamplePredictionClient_Predict() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/automl/apiv1beta1/auto_ml_client.go b/automl/apiv1beta1/auto_ml_client.go index 377e91bf678c..1e651e44d5ec 100644 --- a/automl/apiv1beta1/auto_ml_client.go +++ b/automl/apiv1beta1/auto_ml_client.go @@ -1605,6 +1605,11 @@ func (c *restClient) CreateDataset(ctx context.Context, req *automlpb.CreateData } baseUrl.Path += fmt.Sprintf("/v1beta1/%v/datasets", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1658,6 +1663,11 @@ func (c *restClient) GetDataset(ctx context.Context, req *automlpb.GetDatasetReq } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1725,6 +1735,7 @@ func (c *restClient) ListDatasets(ctx context.Context, req *automlpb.ListDataset baseUrl.Path += fmt.Sprintf("/v1beta1/%v/datasets", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1809,6 +1820,7 @@ func (c *restClient) UpdateDataset(ctx context.Context, req *automlpb.UpdateData baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetDataset().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -1876,6 +1888,11 @@ func (c *restClient) DeleteDataset(ctx context.Context, req *automlpb.DeleteData } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1948,6 +1965,11 @@ func (c *restClient) ImportData(ctx context.Context, req *automlpb.ImportDataReq } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:importData", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2013,6 +2035,11 @@ func (c *restClient) ExportData(ctx context.Context, req *automlpb.ExportDataReq } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:exportData", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2070,6 +2097,11 @@ func (c *restClient) GetAnnotationSpec(ctx context.Context, req *automlpb.GetAnn } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2124,6 +2156,7 @@ func (c *restClient) GetTableSpec(ctx context.Context, req *automlpb.GetTableSpe baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFieldMask() != nil { fieldMask, err := protojson.Marshal(req.GetFieldMask()) if err != nil { @@ -2201,6 +2234,7 @@ func (c *restClient) ListTableSpecs(ctx context.Context, req *automlpb.ListTable baseUrl.Path += fmt.Sprintf("/v1beta1/%v/tableSpecs", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFieldMask() != nil { fieldMask, err := protojson.Marshal(req.GetFieldMask()) if err != nil { @@ -2292,6 +2326,7 @@ func (c *restClient) UpdateTableSpec(ctx context.Context, req *automlpb.UpdateTa baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetTableSpec().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -2356,6 +2391,7 @@ func (c *restClient) GetColumnSpec(ctx context.Context, req *automlpb.GetColumnS baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFieldMask() != nil { fieldMask, err := protojson.Marshal(req.GetFieldMask()) if err != nil { @@ -2433,6 +2469,7 @@ func (c *restClient) ListColumnSpecs(ctx context.Context, req *automlpb.ListColu baseUrl.Path += fmt.Sprintf("/v1beta1/%v/columnSpecs", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFieldMask() != nil { fieldMask, err := protojson.Marshal(req.GetFieldMask()) if err != nil { @@ -2524,6 +2561,7 @@ func (c *restClient) UpdateColumnSpec(ctx context.Context, req *automlpb.UpdateC baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetColumnSpec().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -2598,6 +2636,11 @@ func (c *restClient) CreateModel(ctx context.Context, req *automlpb.CreateModelR } baseUrl.Path += fmt.Sprintf("/v1beta1/%v/models", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -2655,6 +2698,11 @@ func (c *restClient) GetModel(ctx context.Context, req *automlpb.GetModelRequest } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2722,6 +2770,7 @@ func (c *restClient) ListModels(ctx context.Context, req *automlpb.ListModelsReq baseUrl.Path += fmt.Sprintf("/v1beta1/%v/models", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -2802,6 +2851,11 @@ func (c *restClient) DeleteModel(ctx context.Context, req *automlpb.DeleteModelR } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2876,6 +2930,11 @@ func (c *restClient) DeployModel(ctx context.Context, req *automlpb.DeployModelR } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:deploy", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2945,6 +3004,11 @@ func (c *restClient) UndeployModel(ctx context.Context, req *automlpb.UndeployMo } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:undeploy", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -3015,6 +3079,11 @@ func (c *restClient) ExportModel(ctx context.Context, req *automlpb.ExportModelR } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:export", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -3091,6 +3160,11 @@ func (c *restClient) ExportEvaluatedExamples(ctx context.Context, req *automlpb. } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:exportEvaluatedExamples", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -3148,6 +3222,11 @@ func (c *restClient) GetModelEvaluation(ctx context.Context, req *automlpb.GetMo } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -3215,6 +3294,7 @@ func (c *restClient) ListModelEvaluations(ctx context.Context, req *automlpb.Lis baseUrl.Path += fmt.Sprintf("/v1beta1/%v/modelEvaluations", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/automl/apiv1beta1/automlpb/annotation_payload.pb.go b/automl/apiv1beta1/automlpb/annotation_payload.pb.go index eb17416e4bac..a60e791ca537 100644 --- a/automl/apiv1beta1/automlpb/annotation_payload.pb.go +++ b/automl/apiv1beta1/automlpb/annotation_payload.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/automl/v1beta1/annotation_payload.proto package automlpb @@ -45,7 +45,6 @@ type AnnotationPayload struct { // specific to the AutoML domain. // // Types that are assignable to Detail: - // // *AnnotationPayload_Translation // *AnnotationPayload_Classification // *AnnotationPayload_ImageObjectDetection diff --git a/automl/apiv1beta1/automlpb/annotation_spec.pb.go b/automl/apiv1beta1/automlpb/annotation_spec.pb.go index 3870715a4d05..cb3973605108 100644 --- a/automl/apiv1beta1/automlpb/annotation_spec.pb.go +++ b/automl/apiv1beta1/automlpb/annotation_spec.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/automl/v1beta1/annotation_spec.proto package automlpb diff --git a/automl/apiv1beta1/automlpb/classification.pb.go b/automl/apiv1beta1/automlpb/classification.pb.go index 6db1ebd9ec00..6ab3d45faac6 100644 --- a/automl/apiv1beta1/automlpb/classification.pb.go +++ b/automl/apiv1beta1/automlpb/classification.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/automl/v1beta1/classification.proto package automlpb @@ -149,27 +149,27 @@ type VideoClassificationAnnotation struct { // Output only. Expresses the type of video classification. Possible values: // - // - `segment` - Classification done on a specified by user - // time segment of a video. AnnotationSpec is answered to be present - // in that time segment, if it is present in any part of it. The video - // ML model evaluations are done only for this type of classification. + // * `segment` - Classification done on a specified by user + // time segment of a video. AnnotationSpec is answered to be present + // in that time segment, if it is present in any part of it. The video + // ML model evaluations are done only for this type of classification. // - // - `shot`- Shot-level classification. - // AutoML Video Intelligence determines the boundaries - // for each camera shot in the entire segment of the video that user - // specified in the request configuration. AutoML Video Intelligence - // then returns labels and their confidence scores for each detected - // shot, along with the start and end time of the shot. - // WARNING: Model evaluation is not done for this classification type, - // the quality of it depends on training data, but there are no - // metrics provided to describe that quality. + // * `shot`- Shot-level classification. + // AutoML Video Intelligence determines the boundaries + // for each camera shot in the entire segment of the video that user + // specified in the request configuration. AutoML Video Intelligence + // then returns labels and their confidence scores for each detected + // shot, along with the start and end time of the shot. + // WARNING: Model evaluation is not done for this classification type, + // the quality of it depends on training data, but there are no + // metrics provided to describe that quality. // - // - `1s_interval` - AutoML Video Intelligence returns labels and their - // confidence scores for each second of the entire segment of the video - // that user specified in the request configuration. - // WARNING: Model evaluation is not done for this classification type, - // the quality of it depends on training data, but there are no - // metrics provided to describe that quality. + // * `1s_interval` - AutoML Video Intelligence returns labels and their + // confidence scores for each second of the entire segment of the video + // that user specified in the request configuration. + // WARNING: Model evaluation is not done for this classification type, + // the quality of it depends on training data, but there are no + // metrics provided to describe that quality. Type string `protobuf:"bytes,1,opt,name=type,proto3" json:"type,omitempty"` // Output only . The classification details of this annotation. ClassificationAnnotation *ClassificationAnnotation `protobuf:"bytes,2,opt,name=classification_annotation,json=classificationAnnotation,proto3" json:"classification_annotation,omitempty"` diff --git a/automl/apiv1beta1/automlpb/column_spec.pb.go b/automl/apiv1beta1/automlpb/column_spec.pb.go index 6c68eca18179..3577db8d61af 100644 --- a/automl/apiv1beta1/automlpb/column_spec.pb.go +++ b/automl/apiv1beta1/automlpb/column_spec.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/automl/v1beta1/column_spec.proto package automlpb diff --git a/automl/apiv1beta1/automlpb/data_items.pb.go b/automl/apiv1beta1/automlpb/data_items.pb.go index 1963459f95f4..76c38317c2dd 100644 --- a/automl/apiv1beta1/automlpb/data_items.pb.go +++ b/automl/apiv1beta1/automlpb/data_items.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/automl/v1beta1/data_items.proto package automlpb @@ -197,7 +197,6 @@ type Image struct { // uploaded image by using the [content_uri][google.cloud.automl.v1beta1.Image.content_uri] field. // // Types that are assignable to Data: - // // *Image_ImageBytes // *Image_InputConfig Data isImage_Data `protobuf_oneof:"data"` @@ -587,7 +586,6 @@ type ExamplePayload struct { // Required. Input only. The example data. // // Types that are assignable to Payload: - // // *ExamplePayload_Image // *ExamplePayload_TextSnippet // *ExamplePayload_Document diff --git a/automl/apiv1beta1/automlpb/data_stats.pb.go b/automl/apiv1beta1/automlpb/data_stats.pb.go index f37cb22e01ee..f45eed77e6fe 100644 --- a/automl/apiv1beta1/automlpb/data_stats.pb.go +++ b/automl/apiv1beta1/automlpb/data_stats.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/automl/v1beta1/data_stats.proto package automlpb @@ -44,7 +44,6 @@ type DataStats struct { // The data statistics specific to a DataType. // // Types that are assignable to Stats: - // // *DataStats_Float64Stats // *DataStats_StringStats // *DataStats_TimestampStats diff --git a/automl/apiv1beta1/automlpb/data_types.pb.go b/automl/apiv1beta1/automlpb/data_types.pb.go index 7ca5f9e51fa8..22a9b6738f2c 100644 --- a/automl/apiv1beta1/automlpb/data_types.pb.go +++ b/automl/apiv1beta1/automlpb/data_types.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/automl/v1beta1/data_types.proto package automlpb @@ -127,7 +127,6 @@ type DataType struct { // Details of DataType-s that need additional specification. // // Types that are assignable to Details: - // // *DataType_ListElementType // *DataType_StructType // *DataType_TimeFormat diff --git a/automl/apiv1beta1/automlpb/dataset.pb.go b/automl/apiv1beta1/automlpb/dataset.pb.go index cbffaf13b538..d5799a7e05fd 100644 --- a/automl/apiv1beta1/automlpb/dataset.pb.go +++ b/automl/apiv1beta1/automlpb/dataset.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/automl/v1beta1/dataset.proto package automlpb @@ -48,7 +48,6 @@ type Dataset struct { // The dataset metadata that is specific to the problem type. // // Types that are assignable to DatasetMetadata: - // // *Dataset_TranslationDatasetMetadata // *Dataset_ImageClassificationDatasetMetadata // *Dataset_TextClassificationDatasetMetadata diff --git a/automl/apiv1beta1/automlpb/detection.pb.go b/automl/apiv1beta1/automlpb/detection.pb.go index 652db3ca5b22..ab49d7472362 100644 --- a/automl/apiv1beta1/automlpb/detection.pb.go +++ b/automl/apiv1beta1/automlpb/detection.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/automl/v1beta1/detection.proto package automlpb diff --git a/automl/apiv1beta1/automlpb/geometry.pb.go b/automl/apiv1beta1/automlpb/geometry.pb.go index 4f7c5f93877f..17fe6b78c2f8 100644 --- a/automl/apiv1beta1/automlpb/geometry.pb.go +++ b/automl/apiv1beta1/automlpb/geometry.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/automl/v1beta1/geometry.proto package automlpb diff --git a/automl/apiv1beta1/automlpb/image.pb.go b/automl/apiv1beta1/automlpb/image.pb.go index 4105927a2227..591e20943e95 100644 --- a/automl/apiv1beta1/automlpb/image.pb.go +++ b/automl/apiv1beta1/automlpb/image.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/automl/v1beta1/image.proto package automlpb @@ -146,38 +146,38 @@ type ImageClassificationModelMetadata struct { // e.g. `BUDGET_REACHED`, `MODEL_CONVERGED`. StopReason string `protobuf:"bytes,5,opt,name=stop_reason,json=stopReason,proto3" json:"stop_reason,omitempty"` // Optional. Type of the model. The available values are: - // - `cloud` - Model to be used via prediction calls to AutoML API. - // This is the default value. - // - `mobile-low-latency-1` - A model that, in addition to providing - // prediction via AutoML API, can also be exported (see - // [AutoMl.ExportModel][google.cloud.automl.v1beta1.AutoMl.ExportModel]) and used on a mobile or edge device - // with TensorFlow afterwards. Expected to have low latency, but - // may have lower prediction quality than other models. - // - `mobile-versatile-1` - A model that, in addition to providing - // prediction via AutoML API, can also be exported (see - // [AutoMl.ExportModel][google.cloud.automl.v1beta1.AutoMl.ExportModel]) and used on a mobile or edge device - // with TensorFlow afterwards. - // - `mobile-high-accuracy-1` - A model that, in addition to providing - // prediction via AutoML API, can also be exported (see - // [AutoMl.ExportModel][google.cloud.automl.v1beta1.AutoMl.ExportModel]) and used on a mobile or edge device - // with TensorFlow afterwards. Expected to have a higher - // latency, but should also have a higher prediction quality - // than other models. - // - `mobile-core-ml-low-latency-1` - A model that, in addition to providing - // prediction via AutoML API, can also be exported (see - // [AutoMl.ExportModel][google.cloud.automl.v1beta1.AutoMl.ExportModel]) and used on a mobile device with Core - // ML afterwards. Expected to have low latency, but may have - // lower prediction quality than other models. - // - `mobile-core-ml-versatile-1` - A model that, in addition to providing - // prediction via AutoML API, can also be exported (see - // [AutoMl.ExportModel][google.cloud.automl.v1beta1.AutoMl.ExportModel]) and used on a mobile device with Core - // ML afterwards. - // - `mobile-core-ml-high-accuracy-1` - A model that, in addition to - // providing prediction via AutoML API, can also be exported - // (see [AutoMl.ExportModel][google.cloud.automl.v1beta1.AutoMl.ExportModel]) and used on a mobile device with - // Core ML afterwards. Expected to have a higher latency, but - // should also have a higher prediction quality than other - // models. + // * `cloud` - Model to be used via prediction calls to AutoML API. + // This is the default value. + // * `mobile-low-latency-1` - A model that, in addition to providing + // prediction via AutoML API, can also be exported (see + // [AutoMl.ExportModel][google.cloud.automl.v1beta1.AutoMl.ExportModel]) and used on a mobile or edge device + // with TensorFlow afterwards. Expected to have low latency, but + // may have lower prediction quality than other models. + // * `mobile-versatile-1` - A model that, in addition to providing + // prediction via AutoML API, can also be exported (see + // [AutoMl.ExportModel][google.cloud.automl.v1beta1.AutoMl.ExportModel]) and used on a mobile or edge device + // with TensorFlow afterwards. + // * `mobile-high-accuracy-1` - A model that, in addition to providing + // prediction via AutoML API, can also be exported (see + // [AutoMl.ExportModel][google.cloud.automl.v1beta1.AutoMl.ExportModel]) and used on a mobile or edge device + // with TensorFlow afterwards. Expected to have a higher + // latency, but should also have a higher prediction quality + // than other models. + // * `mobile-core-ml-low-latency-1` - A model that, in addition to providing + // prediction via AutoML API, can also be exported (see + // [AutoMl.ExportModel][google.cloud.automl.v1beta1.AutoMl.ExportModel]) and used on a mobile device with Core + // ML afterwards. Expected to have low latency, but may have + // lower prediction quality than other models. + // * `mobile-core-ml-versatile-1` - A model that, in addition to providing + // prediction via AutoML API, can also be exported (see + // [AutoMl.ExportModel][google.cloud.automl.v1beta1.AutoMl.ExportModel]) and used on a mobile device with Core + // ML afterwards. + // * `mobile-core-ml-high-accuracy-1` - A model that, in addition to + // providing prediction via AutoML API, can also be exported + // (see [AutoMl.ExportModel][google.cloud.automl.v1beta1.AutoMl.ExportModel]) and used on a mobile device with + // Core ML afterwards. Expected to have a higher latency, but + // should also have a higher prediction quality than other + // models. ModelType string `protobuf:"bytes,7,opt,name=model_type,json=modelType,proto3" json:"model_type,omitempty"` // Output only. An approximate number of online prediction QPS that can // be supported by this model per each node on which it is deployed. @@ -276,28 +276,28 @@ type ImageObjectDetectionModelMetadata struct { unknownFields protoimpl.UnknownFields // Optional. Type of the model. The available values are: - // - `cloud-high-accuracy-1` - (default) A model to be used via prediction - // calls to AutoML API. Expected to have a higher latency, but - // should also have a higher prediction quality than other - // models. - // - `cloud-low-latency-1` - A model to be used via prediction - // calls to AutoML API. Expected to have low latency, but may - // have lower prediction quality than other models. - // - `mobile-low-latency-1` - A model that, in addition to providing - // prediction via AutoML API, can also be exported (see - // [AutoMl.ExportModel][google.cloud.automl.v1beta1.AutoMl.ExportModel]) and used on a mobile or edge device - // with TensorFlow afterwards. Expected to have low latency, but - // may have lower prediction quality than other models. - // - `mobile-versatile-1` - A model that, in addition to providing - // prediction via AutoML API, can also be exported (see - // [AutoMl.ExportModel][google.cloud.automl.v1beta1.AutoMl.ExportModel]) and used on a mobile or edge device - // with TensorFlow afterwards. - // - `mobile-high-accuracy-1` - A model that, in addition to providing - // prediction via AutoML API, can also be exported (see - // [AutoMl.ExportModel][google.cloud.automl.v1beta1.AutoMl.ExportModel]) and used on a mobile or edge device - // with TensorFlow afterwards. Expected to have a higher - // latency, but should also have a higher prediction quality - // than other models. + // * `cloud-high-accuracy-1` - (default) A model to be used via prediction + // calls to AutoML API. Expected to have a higher latency, but + // should also have a higher prediction quality than other + // models. + // * `cloud-low-latency-1` - A model to be used via prediction + // calls to AutoML API. Expected to have low latency, but may + // have lower prediction quality than other models. + // * `mobile-low-latency-1` - A model that, in addition to providing + // prediction via AutoML API, can also be exported (see + // [AutoMl.ExportModel][google.cloud.automl.v1beta1.AutoMl.ExportModel]) and used on a mobile or edge device + // with TensorFlow afterwards. Expected to have low latency, but + // may have lower prediction quality than other models. + // * `mobile-versatile-1` - A model that, in addition to providing + // prediction via AutoML API, can also be exported (see + // [AutoMl.ExportModel][google.cloud.automl.v1beta1.AutoMl.ExportModel]) and used on a mobile or edge device + // with TensorFlow afterwards. + // * `mobile-high-accuracy-1` - A model that, in addition to providing + // prediction via AutoML API, can also be exported (see + // [AutoMl.ExportModel][google.cloud.automl.v1beta1.AutoMl.ExportModel]) and used on a mobile or edge device + // with TensorFlow afterwards. Expected to have a higher + // latency, but should also have a higher prediction quality + // than other models. ModelType string `protobuf:"bytes,1,opt,name=model_type,json=modelType,proto3" json:"model_type,omitempty"` // Output only. The number of nodes this model is deployed on. A node is an // abstraction of a machine resource, which can handle online prediction QPS diff --git a/automl/apiv1beta1/automlpb/io.pb.go b/automl/apiv1beta1/automlpb/io.pb.go index f7d4a20e91d5..64bf5ebde179 100644 --- a/automl/apiv1beta1/automlpb/io.pb.go +++ b/automl/apiv1beta1/automlpb/io.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/automl/v1beta1/io.proto package automlpb @@ -404,7 +404,6 @@ type InputConfig struct { // The source of the input. // // Types that are assignable to Source: - // // *InputConfig_GcsSource // *InputConfig_BigquerySource Source isInputConfig_Source `protobuf_oneof:"source"` @@ -412,11 +411,11 @@ type InputConfig struct { // imported data, any string must be up to 25000 // characters long. // - // - For Tables: - // `schema_inference_version` - (integer) Required. The version of the - // algorithm that should be used for the initial inference of the - // schema (columns' DataTypes) of the table the data is being imported - // into. Allowed values: "1". + // * For Tables: + // `schema_inference_version` - (integer) Required. The version of the + // algorithm that should be used for the initial inference of the + // schema (columns' DataTypes) of the table the data is being imported + // into. Allowed values: "1". Params map[string]string `protobuf:"bytes,2,rep,name=params,proto3" json:"params,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` } @@ -730,7 +729,6 @@ type BatchPredictInputConfig struct { // Required. The source of the input. // // Types that are assignable to Source: - // // *BatchPredictInputConfig_GcsSource // *BatchPredictInputConfig_BigquerySource Source isBatchPredictInputConfig_Source `protobuf_oneof:"source"` @@ -901,7 +899,6 @@ type OutputConfig struct { // Required. The destination of the output. // // Types that are assignable to Destination: - // // *OutputConfig_GcsDestination // *OutputConfig_BigqueryDestination Destination isOutputConfig_Destination `protobuf_oneof:"destination"` @@ -1294,7 +1291,6 @@ type BatchPredictOutputConfig struct { // Required. The destination of the output. // // Types that are assignable to Destination: - // // *BatchPredictOutputConfig_GcsDestination // *BatchPredictOutputConfig_BigqueryDestination Destination isBatchPredictOutputConfig_Destination `protobuf_oneof:"destination"` @@ -1381,7 +1377,6 @@ type ModelExportOutputConfig struct { // Required. The destination of the output. // // Types that are assignable to Destination: - // // *ModelExportOutputConfig_GcsDestination // *ModelExportOutputConfig_GcrDestination Destination isModelExportOutputConfig_Destination `protobuf_oneof:"destination"` @@ -1390,52 +1385,52 @@ type ModelExportOutputConfig struct { // combination doesn't have a format listed, it means its models are not // exportable): // - // - For Image Classification mobile-low-latency-1, mobile-versatile-1, - // mobile-high-accuracy-1: - // "tflite" (default), "edgetpu_tflite", "tf_saved_model", "tf_js", - // "docker". + // * For Image Classification mobile-low-latency-1, mobile-versatile-1, + // mobile-high-accuracy-1: + // "tflite" (default), "edgetpu_tflite", "tf_saved_model", "tf_js", + // "docker". // - // - For Image Classification mobile-core-ml-low-latency-1, - // mobile-core-ml-versatile-1, mobile-core-ml-high-accuracy-1: - // "core_ml" (default). + // * For Image Classification mobile-core-ml-low-latency-1, + // mobile-core-ml-versatile-1, mobile-core-ml-high-accuracy-1: + // "core_ml" (default). // - // - For Image Object Detection mobile-low-latency-1, mobile-versatile-1, - // mobile-high-accuracy-1: - // "tflite", "tf_saved_model", "tf_js". + // * For Image Object Detection mobile-low-latency-1, mobile-versatile-1, + // mobile-high-accuracy-1: + // "tflite", "tf_saved_model", "tf_js". // - // - For Video Classification cloud, - // "tf_saved_model". + // * For Video Classification cloud, + // "tf_saved_model". // - // - For Video Object Tracking cloud, - // "tf_saved_model". + // * For Video Object Tracking cloud, + // "tf_saved_model". // - // - For Video Object Tracking mobile-versatile-1: - // "tflite", "edgetpu_tflite", "tf_saved_model", "docker". + // * For Video Object Tracking mobile-versatile-1: + // "tflite", "edgetpu_tflite", "tf_saved_model", "docker". // - // - For Video Object Tracking mobile-coral-versatile-1: - // "tflite", "edgetpu_tflite", "docker". + // * For Video Object Tracking mobile-coral-versatile-1: + // "tflite", "edgetpu_tflite", "docker". // - // - For Video Object Tracking mobile-coral-low-latency-1: - // "tflite", "edgetpu_tflite", "docker". + // * For Video Object Tracking mobile-coral-low-latency-1: + // "tflite", "edgetpu_tflite", "docker". // - // - For Video Object Tracking mobile-jetson-versatile-1: - // "tf_saved_model", "docker". + // * For Video Object Tracking mobile-jetson-versatile-1: + // "tf_saved_model", "docker". // - // - For Tables: - // "docker". + // * For Tables: + // "docker". // // Formats description: // - // - tflite - Used for Android mobile devices. - // - edgetpu_tflite - Used for [Edge TPU](https://cloud.google.com/edge-tpu/) - // devices. - // - tf_saved_model - A tensorflow model in SavedModel format. - // - tf_js - A [TensorFlow.js](https://www.tensorflow.org/js) model that can - // be used in the browser and in Node.js using JavaScript. - // - docker - Used for Docker containers. Use the params field to customize - // the container. The container is verified to work correctly on - // ubuntu 16.04 operating system. See more at - // [containers + // * tflite - Used for Android mobile devices. + // * edgetpu_tflite - Used for [Edge TPU](https://cloud.google.com/edge-tpu/) + // devices. + // * tf_saved_model - A tensorflow model in SavedModel format. + // * tf_js - A [TensorFlow.js](https://www.tensorflow.org/js) model that can + // be used in the browser and in Node.js using JavaScript. + // * docker - Used for Docker containers. Use the params field to customize + // the container. The container is verified to work correctly on + // ubuntu 16.04 operating system. See more at + // [containers // // quickstart](https: // //cloud.google.com/vision/automl/docs/containers-gcs-quickstart) @@ -1445,7 +1440,7 @@ type ModelExportOutputConfig struct { // requirements for the to be exported model files, any string must be up to // 25000 characters long. // - // - For `docker` format: + // * For `docker` format: // `cpu_architecture` - (string) "x86_64" (default). // `gpu_architecture` - (string) "none" (default), "nvidia". Params map[string]string `protobuf:"bytes,2,rep,name=params,proto3" json:"params,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` @@ -1525,22 +1520,20 @@ type isModelExportOutputConfig_Destination interface { type ModelExportOutputConfig_GcsDestination struct { // The Google Cloud Storage location where the model is to be written to. // This location may only be set for the following model formats: + // "tflite", "edgetpu_tflite", "tf_saved_model", "tf_js", "core_ml". // - // "tflite", "edgetpu_tflite", "tf_saved_model", "tf_js", "core_ml". - // - // Under the directory given as the destination a new one with name - // "model-export--", - // where timestamp is in YYYY-MM-DDThh:mm:ss.sssZ ISO-8601 format, - // will be created. Inside the model and any of its supporting files - // will be written. + // Under the directory given as the destination a new one with name + // "model-export--", + // where timestamp is in YYYY-MM-DDThh:mm:ss.sssZ ISO-8601 format, + // will be created. Inside the model and any of its supporting files + // will be written. GcsDestination *GcsDestination `protobuf:"bytes,1,opt,name=gcs_destination,json=gcsDestination,proto3,oneof"` } type ModelExportOutputConfig_GcrDestination struct { // The GCR location where model image is to be pushed to. This location // may only be set for the following model formats: - // - // "docker". + // "docker". // // The model image will be created under the given URI. GcrDestination *GcrDestination `protobuf:"bytes,3,opt,name=gcr_destination,json=gcrDestination,proto3,oneof"` @@ -1590,7 +1583,6 @@ type ExportEvaluatedExamplesOutputConfig struct { // Required. The destination of the output. // // Types that are assignable to Destination: - // // *ExportEvaluatedExamplesOutputConfig_BigqueryDestination Destination isExportEvaluatedExamplesOutputConfig_Destination `protobuf_oneof:"destination"` } diff --git a/automl/apiv1beta1/automlpb/model.pb.go b/automl/apiv1beta1/automlpb/model.pb.go index e01bb50c399f..9856039cb24f 100644 --- a/automl/apiv1beta1/automlpb/model.pb.go +++ b/automl/apiv1beta1/automlpb/model.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/automl/v1beta1/model.proto package automlpb @@ -101,7 +101,6 @@ type Model struct { // Must match the metadata type of the dataset used to train the model. // // Types that are assignable to ModelMetadata: - // // *Model_TranslationModelMetadata // *Model_ImageClassificationModelMetadata // *Model_TextClassificationModelMetadata diff --git a/automl/apiv1beta1/automlpb/model_evaluation.pb.go b/automl/apiv1beta1/automlpb/model_evaluation.pb.go index 456c5640ed51..8e9114fd30a8 100644 --- a/automl/apiv1beta1/automlpb/model_evaluation.pb.go +++ b/automl/apiv1beta1/automlpb/model_evaluation.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/automl/v1beta1/model_evaluation.proto package automlpb @@ -46,7 +46,6 @@ type ModelEvaluation struct { // Output only. Problem type specific evaluation metrics. // // Types that are assignable to Metrics: - // // *ModelEvaluation_ClassificationEvaluationMetrics // *ModelEvaluation_RegressionEvaluationMetrics // *ModelEvaluation_TranslationEvaluationMetrics diff --git a/automl/apiv1beta1/automlpb/operations.pb.go b/automl/apiv1beta1/automlpb/operations.pb.go index b0ebf8af525f..f8388ac87bf5 100644 --- a/automl/apiv1beta1/automlpb/operations.pb.go +++ b/automl/apiv1beta1/automlpb/operations.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/automl/v1beta1/operations.proto package automlpb @@ -47,7 +47,6 @@ type OperationMetadata struct { // the presence allows to distinguish different types of operations. // // Types that are assignable to Details: - // // *OperationMetadata_DeleteDetails // *OperationMetadata_DeployModelDetails // *OperationMetadata_UndeployModelDetails @@ -683,7 +682,6 @@ type ExportDataOperationMetadata_ExportDataOutputInfo struct { // The output location to which the exported data is written. // // Types that are assignable to OutputLocation: - // // *ExportDataOperationMetadata_ExportDataOutputInfo_GcsOutputDirectory // *ExportDataOperationMetadata_ExportDataOutputInfo_BigqueryOutputDataset OutputLocation isExportDataOperationMetadata_ExportDataOutputInfo_OutputLocation `protobuf_oneof:"output_location"` @@ -776,7 +774,6 @@ type BatchPredictOperationMetadata_BatchPredictOutputInfo struct { // The output location into which prediction output is written. // // Types that are assignable to OutputLocation: - // // *BatchPredictOperationMetadata_BatchPredictOutputInfo_GcsOutputDirectory // *BatchPredictOperationMetadata_BatchPredictOutputInfo_BigqueryOutputDataset OutputLocation isBatchPredictOperationMetadata_BatchPredictOutputInfo_OutputLocation `protobuf_oneof:"output_location"` diff --git a/automl/apiv1beta1/automlpb/prediction_service.pb.go b/automl/apiv1beta1/automlpb/prediction_service.pb.go index 445281be14d7..4b4def986557 100644 --- a/automl/apiv1beta1/automlpb/prediction_service.pb.go +++ b/automl/apiv1beta1/automlpb/prediction_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/automl/v1beta1/prediction_service.proto package automlpb @@ -57,21 +57,21 @@ type PredictRequest struct { // // * For Image Classification: // - // `score_threshold` - (float) A value from 0.0 to 1.0. When the model - // makes predictions for an image, it will only produce results that have - // at least this confidence score. The default is 0.5. + // `score_threshold` - (float) A value from 0.0 to 1.0. When the model + // makes predictions for an image, it will only produce results that have + // at least this confidence score. The default is 0.5. // - // * For Image Object Detection: - // `score_threshold` - (float) When Model detects objects on the image, - // it will only produce bounding boxes which have at least this - // confidence score. Value in 0 to 1 range, default is 0.5. - // `max_bounding_box_count` - (int64) No more than this number of bounding - // boxes will be returned in the response. Default is 100, the - // requested value may be limited by server. - // - For Tables: - // feature_importance - (boolean) Whether feature importance - // should be populated in the returned TablesAnnotation. - // The default is false. + // * For Image Object Detection: + // `score_threshold` - (float) When Model detects objects on the image, + // it will only produce bounding boxes which have at least this + // confidence score. Value in 0 to 1 range, default is 0.5. + // `max_bounding_box_count` - (int64) No more than this number of bounding + // boxes will be returned in the response. Default is 100, the + // requested value may be limited by server. + // * For Tables: + // feature_importance - (boolean) Whether feature importance + // should be populated in the returned TablesAnnotation. + // The default is false. Params map[string]string `protobuf:"bytes,3,rep,name=params,proto3" json:"params,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` } @@ -139,25 +139,25 @@ type PredictResponse struct { Payload []*AnnotationPayload `protobuf:"bytes,1,rep,name=payload,proto3" json:"payload,omitempty"` // The preprocessed example that AutoML actually makes prediction on. // Empty if AutoML does not preprocess the input example. - // - For Text Extraction: - // If the input is a .pdf file, the OCR'ed text will be provided in - // [document_text][google.cloud.automl.v1beta1.Document.document_text]. + // * For Text Extraction: + // If the input is a .pdf file, the OCR'ed text will be provided in + // [document_text][google.cloud.automl.v1beta1.Document.document_text]. PreprocessedInput *ExamplePayload `protobuf:"bytes,3,opt,name=preprocessed_input,json=preprocessedInput,proto3" json:"preprocessed_input,omitempty"` // Additional domain-specific prediction response metadata. // - // - For Image Object Detection: - // `max_bounding_box_count` - (int64) At most that many bounding boxes per - // image could have been returned. + // * For Image Object Detection: + // `max_bounding_box_count` - (int64) At most that many bounding boxes per + // image could have been returned. // - // - For Text Sentiment: - // `sentiment_score` - (float, deprecated) A value between -1 and 1, - // -1 maps to least positive sentiment, while 1 maps to the most positive - // one and the higher the score, the more positive the sentiment in the - // document is. Yet these values are relative to the training data, so - // e.g. if all data was positive then -1 will be also positive (though - // the least). - // The sentiment_score shouldn't be confused with "score" or "magnitude" - // from the previous Natural Language Sentiment Analysis API. + // * For Text Sentiment: + // `sentiment_score` - (float, deprecated) A value between -1 and 1, + // -1 maps to least positive sentiment, while 1 maps to the most positive + // one and the higher the score, the more positive the sentiment in the + // document is. Yet these values are relative to the training data, so + // e.g. if all data was positive then -1 will be also positive (though + // the least). + // The sentiment_score shouldn't be confused with "score" or "magnitude" + // from the previous Natural Language Sentiment Analysis API. Metadata map[string]string `protobuf:"bytes,2,rep,name=metadata,proto3" json:"metadata,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` } @@ -232,71 +232,71 @@ type BatchPredictRequest struct { // // * For Text Classification: // - // `score_threshold` - (float) A value from 0.0 to 1.0. When the model - // makes predictions for a text snippet, it will only produce results - // that have at least this confidence score. The default is 0.5. + // `score_threshold` - (float) A value from 0.0 to 1.0. When the model + // makes predictions for a text snippet, it will only produce results + // that have at least this confidence score. The default is 0.5. // // * For Image Classification: // - // `score_threshold` - (float) A value from 0.0 to 1.0. When the model - // makes predictions for an image, it will only produce results that - // have at least this confidence score. The default is 0.5. + // `score_threshold` - (float) A value from 0.0 to 1.0. When the model + // makes predictions for an image, it will only produce results that + // have at least this confidence score. The default is 0.5. // // * For Image Object Detection: // - // `score_threshold` - (float) When Model detects objects on the image, - // it will only produce bounding boxes which have at least this - // confidence score. Value in 0 to 1 range, default is 0.5. - // `max_bounding_box_count` - (int64) No more than this number of bounding - // boxes will be produced per image. Default is 100, the - // requested value may be limited by server. + // `score_threshold` - (float) When Model detects objects on the image, + // it will only produce bounding boxes which have at least this + // confidence score. Value in 0 to 1 range, default is 0.5. + // `max_bounding_box_count` - (int64) No more than this number of bounding + // boxes will be produced per image. Default is 100, the + // requested value may be limited by server. // // * For Video Classification : // - // `score_threshold` - (float) A value from 0.0 to 1.0. When the model - // makes predictions for a video, it will only produce results that - // have at least this confidence score. The default is 0.5. - // `segment_classification` - (boolean) Set to true to request - // segment-level classification. AutoML Video Intelligence returns - // labels and their confidence scores for the entire segment of the - // video that user specified in the request configuration. - // The default is "true". - // `shot_classification` - (boolean) Set to true to request shot-level - // classification. AutoML Video Intelligence determines the boundaries - // for each camera shot in the entire segment of the video that user - // specified in the request configuration. AutoML Video Intelligence - // then returns labels and their confidence scores for each detected - // shot, along with the start and end time of the shot. - // WARNING: Model evaluation is not done for this classification type, - // the quality of it depends on training data, but there are no metrics - // provided to describe that quality. The default is "false". - // `1s_interval_classification` - (boolean) Set to true to request - // classification for a video at one-second intervals. AutoML Video - // Intelligence returns labels and their confidence scores for each - // second of the entire segment of the video that user specified in the - // request configuration. - // WARNING: Model evaluation is not done for this classification - // type, the quality of it depends on training data, but there are no - // metrics provided to describe that quality. The default is - // "false". + // `score_threshold` - (float) A value from 0.0 to 1.0. When the model + // makes predictions for a video, it will only produce results that + // have at least this confidence score. The default is 0.5. + // `segment_classification` - (boolean) Set to true to request + // segment-level classification. AutoML Video Intelligence returns + // labels and their confidence scores for the entire segment of the + // video that user specified in the request configuration. + // The default is "true". + // `shot_classification` - (boolean) Set to true to request shot-level + // classification. AutoML Video Intelligence determines the boundaries + // for each camera shot in the entire segment of the video that user + // specified in the request configuration. AutoML Video Intelligence + // then returns labels and their confidence scores for each detected + // shot, along with the start and end time of the shot. + // WARNING: Model evaluation is not done for this classification type, + // the quality of it depends on training data, but there are no metrics + // provided to describe that quality. The default is "false". + // `1s_interval_classification` - (boolean) Set to true to request + // classification for a video at one-second intervals. AutoML Video + // Intelligence returns labels and their confidence scores for each + // second of the entire segment of the video that user specified in the + // request configuration. + // WARNING: Model evaluation is not done for this classification + // type, the quality of it depends on training data, but there are no + // metrics provided to describe that quality. The default is + // "false". // // * For Tables: // - // feature_importance - (boolean) Whether feature importance - // should be populated in the returned TablesAnnotations. The - // default is false. + // feature_importance - (boolean) Whether feature importance + // should be populated in the returned TablesAnnotations. The + // default is false. // // * For Video Object Tracking: // - // `score_threshold` - (float) When Model detects objects on video frames, - // it will only produce bounding boxes which have at least this - // confidence score. Value in 0 to 1 range, default is 0.5. - // `max_bounding_box_count` - (int64) No more than this number of bounding - // boxes will be returned per frame. Default is 100, the requested - // value may be limited by server. - // `min_bounding_box_size` - (float) Only bounding boxes with shortest edge - // at least that long as a relative value of video frame size will be - // returned. Value in 0 to 1 range. Default is 0. + // `score_threshold` - (float) When Model detects objects on video frames, + // it will only produce bounding boxes which have at least this + // confidence score. Value in 0 to 1 range, default is 0.5. + // `max_bounding_box_count` - (int64) No more than this number of bounding + // boxes will be returned per frame. Default is 100, the requested + // value may be limited by server. + // `min_bounding_box_size` - (float) Only bounding boxes with shortest edge + // at least that long as a relative value of video frame size will be + // returned. Value in 0 to 1 range. Default is 0. Params map[string]string `protobuf:"bytes,5,rep,name=params,proto3" json:"params,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` } @@ -370,13 +370,13 @@ type BatchPredictResult struct { // Additional domain-specific prediction response metadata. // - // - For Image Object Detection: - // `max_bounding_box_count` - (int64) At most that many bounding boxes per - // image could have been returned. + // * For Image Object Detection: + // `max_bounding_box_count` - (int64) At most that many bounding boxes per + // image could have been returned. // - // - For Video Object Tracking: - // `max_bounding_box_count` - (int64) At most that many bounding boxes per - // frame could have been returned. + // * For Video Object Tracking: + // `max_bounding_box_count` - (int64) At most that many bounding boxes per + // frame could have been returned. Metadata map[string]string `protobuf:"bytes,1,rep,name=metadata,proto3" json:"metadata,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` } @@ -717,22 +717,22 @@ type PredictionServiceClient interface { // Perform an online prediction. The prediction result will be directly // returned in the response. // Available for following ML problems, and their expected request payloads: - // - Image Classification - Image in .JPEG, .GIF or .PNG format, image_bytes - // up to 30MB. - // - Image Object Detection - Image in .JPEG, .GIF or .PNG format, image_bytes - // up to 30MB. - // - Text Classification - TextSnippet, content up to 60,000 characters, - // UTF-8 encoded. - // - Text Extraction - TextSnippet, content up to 30,000 characters, - // UTF-8 NFC encoded. - // - Translation - TextSnippet, content up to 25,000 characters, UTF-8 - // encoded. - // - Tables - Row, with column values matching the columns of the model, - // up to 5MB. Not available for FORECASTING + // * Image Classification - Image in .JPEG, .GIF or .PNG format, image_bytes + // up to 30MB. + // * Image Object Detection - Image in .JPEG, .GIF or .PNG format, image_bytes + // up to 30MB. + // * Text Classification - TextSnippet, content up to 60,000 characters, + // UTF-8 encoded. + // * Text Extraction - TextSnippet, content up to 30,000 characters, + // UTF-8 NFC encoded. + // * Translation - TextSnippet, content up to 25,000 characters, UTF-8 + // encoded. + // * Tables - Row, with column values matching the columns of the model, + // up to 5MB. Not available for FORECASTING // // [prediction_type][google.cloud.automl.v1beta1.TablesModelMetadata.prediction_type]. - // - Text Sentiment - TextSnippet, content up 500 characters, UTF-8 - // encoded. + // * Text Sentiment - TextSnippet, content up 500 characters, UTF-8 + // encoded. Predict(ctx context.Context, in *PredictRequest, opts ...grpc.CallOption) (*PredictResponse, error) // Perform a batch prediction. Unlike the online [Predict][google.cloud.automl.v1beta1.PredictionService.Predict], batch // prediction result won't be immediately available in the response. Instead, @@ -780,22 +780,22 @@ type PredictionServiceServer interface { // Perform an online prediction. The prediction result will be directly // returned in the response. // Available for following ML problems, and their expected request payloads: - // - Image Classification - Image in .JPEG, .GIF or .PNG format, image_bytes - // up to 30MB. - // - Image Object Detection - Image in .JPEG, .GIF or .PNG format, image_bytes - // up to 30MB. - // - Text Classification - TextSnippet, content up to 60,000 characters, - // UTF-8 encoded. - // - Text Extraction - TextSnippet, content up to 30,000 characters, - // UTF-8 NFC encoded. - // - Translation - TextSnippet, content up to 25,000 characters, UTF-8 - // encoded. - // - Tables - Row, with column values matching the columns of the model, - // up to 5MB. Not available for FORECASTING + // * Image Classification - Image in .JPEG, .GIF or .PNG format, image_bytes + // up to 30MB. + // * Image Object Detection - Image in .JPEG, .GIF or .PNG format, image_bytes + // up to 30MB. + // * Text Classification - TextSnippet, content up to 60,000 characters, + // UTF-8 encoded. + // * Text Extraction - TextSnippet, content up to 30,000 characters, + // UTF-8 NFC encoded. + // * Translation - TextSnippet, content up to 25,000 characters, UTF-8 + // encoded. + // * Tables - Row, with column values matching the columns of the model, + // up to 5MB. Not available for FORECASTING // // [prediction_type][google.cloud.automl.v1beta1.TablesModelMetadata.prediction_type]. - // - Text Sentiment - TextSnippet, content up 500 characters, UTF-8 - // encoded. + // * Text Sentiment - TextSnippet, content up 500 characters, UTF-8 + // encoded. Predict(context.Context, *PredictRequest) (*PredictResponse, error) // Perform a batch prediction. Unlike the online [Predict][google.cloud.automl.v1beta1.PredictionService.Predict], batch // prediction result won't be immediately available in the response. Instead, diff --git a/automl/apiv1beta1/automlpb/ranges.pb.go b/automl/apiv1beta1/automlpb/ranges.pb.go index a4208d3c4fb9..fb766c7da9f7 100644 --- a/automl/apiv1beta1/automlpb/ranges.pb.go +++ b/automl/apiv1beta1/automlpb/ranges.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/automl/v1beta1/ranges.proto package automlpb diff --git a/automl/apiv1beta1/automlpb/regression.pb.go b/automl/apiv1beta1/automlpb/regression.pb.go index ede121ca3c49..e8b76b9bdc56 100644 --- a/automl/apiv1beta1/automlpb/regression.pb.go +++ b/automl/apiv1beta1/automlpb/regression.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/automl/v1beta1/regression.proto package automlpb diff --git a/automl/apiv1beta1/automlpb/service.pb.go b/automl/apiv1beta1/automlpb/service.pb.go index 1f5ea84fe037..21eab94340e5 100644 --- a/automl/apiv1beta1/automlpb/service.pb.go +++ b/automl/apiv1beta1/automlpb/service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/automl/v1beta1/service.proto package automlpb @@ -159,12 +159,12 @@ type ListDatasetsRequest struct { Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // An expression for filtering the results of the request. // - // - `dataset_metadata` - for existence of the case (e.g. - // `image_classification_dataset_metadata:*`). Some examples of - // using the filter are: + // * `dataset_metadata` - for existence of the case (e.g. + // `image_classification_dataset_metadata:*`). Some examples of + // using the filter are: // - // - `translation_dataset_metadata:*` --> The dataset has - // `translation_dataset_metadata`. + // * `translation_dataset_metadata:*` --> The dataset has + // `translation_dataset_metadata`. Filter string `protobuf:"bytes,3,opt,name=filter,proto3" json:"filter,omitempty"` // Requested page size. Server may return fewer results than requested. // If unspecified, server will pick a default size. @@ -1214,15 +1214,13 @@ type ListModelsRequest struct { Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // An expression for filtering the results of the request. // - // - `model_metadata` - for existence of the case (e.g. - // `video_classification_model_metadata:*`). + // * `model_metadata` - for existence of the case (e.g. + // `video_classification_model_metadata:*`). + // * `dataset_id` - for = or !=. Some examples of using the filter are: // - // - `dataset_id` - for = or !=. Some examples of using the filter are: - // - // - `image_classification_model_metadata:*` --> The model has - // `image_classification_model_metadata`. - // - // - `dataset_id=5` --> The model was created from a dataset with ID 5. + // * `image_classification_model_metadata:*` --> The model has + // `image_classification_model_metadata`. + // * `dataset_id=5` --> The model was created from a dataset with ID 5. Filter string `protobuf:"bytes,3,opt,name=filter,proto3" json:"filter,omitempty"` // Requested page size. PageSize int32 `protobuf:"varint,4,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"` @@ -1410,7 +1408,6 @@ type DeployModelRequest struct { // The per-domain specific deployment parameters. // // Types that are assignable to ModelDeploymentMetadata: - // // *DeployModelRequest_ImageObjectDetectionModelDeploymentMetadata // *DeployModelRequest_ImageClassificationModelDeploymentMetadata ModelDeploymentMetadata isDeployModelRequest_ModelDeploymentMetadata `protobuf_oneof:"model_deployment_metadata"` @@ -1727,15 +1724,15 @@ type ListModelEvaluationsRequest struct { Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // An expression for filtering the results of the request. // - // - `annotation_spec_id` - for =, != or existence. See example below for - // the last. + // * `annotation_spec_id` - for =, != or existence. See example below for + // the last. // // Some examples of using the filter are: // - // - `annotation_spec_id!=4` --> The model evaluation was done for - // annotation spec with ID different than 4. - // - `NOT annotation_spec_id:*` --> The model evaluation was done for - // aggregate of all annotation specs. + // * `annotation_spec_id!=4` --> The model evaluation was done for + // annotation spec with ID different than 4. + // * `NOT annotation_spec_id:*` --> The model evaluation was done for + // aggregate of all annotation specs. Filter string `protobuf:"bytes,3,opt,name=filter,proto3" json:"filter,omitempty"` // Requested page size. PageSize int32 `protobuf:"varint,4,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"` @@ -3089,9 +3086,7 @@ type AutoMlClient interface { // For Tables: // * A // [schema_inference_version][google.cloud.automl.v1beta1.InputConfig.params] - // - // parameter must be explicitly set. - // + // parameter must be explicitly set. // Returns an empty response in the // [response][google.longrunning.Operation.response] field when it completes. ImportData(ctx context.Context, in *ImportDataRequest, opts ...grpc.CallOption) (*longrunning.Operation, error) @@ -3134,8 +3129,7 @@ type AutoMlClient interface { // (as e.g. changing // // [node_number][google.cloud.automl.v1beta1.ImageObjectDetectionModelDeploymentMetadata.node_number]) - // - // will reset the deployment state without pausing the model's availability. + // will reset the deployment state without pausing the model's availability. // // Only applicable for Text Classification, Image Object Detection , Tables, and Image Segmentation; all other domains manage // deployment automatically. @@ -3427,9 +3421,7 @@ type AutoMlServer interface { // For Tables: // * A // [schema_inference_version][google.cloud.automl.v1beta1.InputConfig.params] - // - // parameter must be explicitly set. - // + // parameter must be explicitly set. // Returns an empty response in the // [response][google.longrunning.Operation.response] field when it completes. ImportData(context.Context, *ImportDataRequest) (*longrunning.Operation, error) @@ -3472,8 +3464,7 @@ type AutoMlServer interface { // (as e.g. changing // // [node_number][google.cloud.automl.v1beta1.ImageObjectDetectionModelDeploymentMetadata.node_number]) - // - // will reset the deployment state without pausing the model's availability. + // will reset the deployment state without pausing the model's availability. // // Only applicable for Text Classification, Image Object Detection , Tables, and Image Segmentation; all other domains manage // deployment automatically. diff --git a/automl/apiv1beta1/automlpb/table_spec.pb.go b/automl/apiv1beta1/automlpb/table_spec.pb.go index f639a1f8c75a..cc8e183f5e0c 100644 --- a/automl/apiv1beta1/automlpb/table_spec.pb.go +++ b/automl/apiv1beta1/automlpb/table_spec.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/automl/v1beta1/table_spec.proto package automlpb diff --git a/automl/apiv1beta1/automlpb/tables.pb.go b/automl/apiv1beta1/automlpb/tables.pb.go index 5ce8f1b24104..96fecd816756 100644 --- a/automl/apiv1beta1/automlpb/tables.pb.go +++ b/automl/apiv1beta1/automlpb/tables.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/automl/v1beta1/tables.proto package automlpb @@ -65,9 +65,7 @@ type TablesDatasetMetadata struct { // during model training. // Required type: FLOAT64. // Allowed values: 0 to 10000, inclusive on both ends; 0 means the row is - // - // ignored for training. - // + // ignored for training. // If not set all rows are assumed to have equal weight of 1. // NOTE: Updates of this field will instantly affect any other users // concurrently working with the dataset. @@ -191,7 +189,6 @@ type TablesModelMetadata struct { // otherwise unused. // // Types that are assignable to AdditionalOptimizationObjectiveConfig: - // // *TablesModelMetadata_OptimizationObjectiveRecallValue // *TablesModelMetadata_OptimizationObjectivePrecisionValue AdditionalOptimizationObjectiveConfig isTablesModelMetadata_AdditionalOptimizationObjectiveConfig `protobuf_oneof:"additional_optimization_objective_config"` @@ -199,11 +196,9 @@ type TablesModelMetadata struct { // predicting. Snapshotted when model creation started. // Only 3 fields are used: // name - May be set on CreateModel, if it's not then the ColumnSpec - // - // corresponding to the current target_column_spec_id of the dataset - // the model is trained from is used. - // If neither is set, CreateModel will error. - // + // corresponding to the current target_column_spec_id of the dataset + // the model is trained from is used. + // If neither is set, CreateModel will error. // display_name - Output only. // data_type - Output only. TargetColumnSpec *ColumnSpec `protobuf:"bytes,2,opt,name=target_column_spec,json=targetColumnSpec,proto3" json:"target_column_spec,omitempty"` @@ -222,9 +217,9 @@ type TablesModelMetadata struct { // // Only 3 fields are used: // - // - name - May be set on CreateModel, if set only the columns specified are - // used, otherwise all primary table's columns (except the ones listed - // above) are used for the training and prediction input. + // * name - May be set on CreateModel, if set only the columns specified are + // used, otherwise all primary table's columns (except the ones listed + // above) are used for the training and prediction input. // // * display_name - Output only. // @@ -238,25 +233,23 @@ type TablesModelMetadata struct { // If the field is not set, a default objective function is used. // // CLASSIFICATION_BINARY: - // - // "MAXIMIZE_AU_ROC" (default) - Maximize the area under the receiver - // operating characteristic (ROC) curve. - // "MINIMIZE_LOG_LOSS" - Minimize log loss. - // "MAXIMIZE_AU_PRC" - Maximize the area under the precision-recall curve. - // "MAXIMIZE_PRECISION_AT_RECALL" - Maximize precision for a specified - // recall value. - // "MAXIMIZE_RECALL_AT_PRECISION" - Maximize recall for a specified - // precision value. + // "MAXIMIZE_AU_ROC" (default) - Maximize the area under the receiver + // operating characteristic (ROC) curve. + // "MINIMIZE_LOG_LOSS" - Minimize log loss. + // "MAXIMIZE_AU_PRC" - Maximize the area under the precision-recall curve. + // "MAXIMIZE_PRECISION_AT_RECALL" - Maximize precision for a specified + // recall value. + // "MAXIMIZE_RECALL_AT_PRECISION" - Maximize recall for a specified + // precision value. // // CLASSIFICATION_MULTI_CLASS : + // "MINIMIZE_LOG_LOSS" (default) - Minimize log loss. // - // "MINIMIZE_LOG_LOSS" (default) - Minimize log loss. // // REGRESSION: - // - // "MINIMIZE_RMSE" (default) - Minimize root-mean-squared error (RMSE). - // "MINIMIZE_MAE" - Minimize mean-absolute error (MAE). - // "MINIMIZE_RMSLE" - Minimize root-mean-squared log error (RMSLE). + // "MINIMIZE_RMSE" (default) - Minimize root-mean-squared error (RMSE). + // "MINIMIZE_MAE" - Minimize mean-absolute error (MAE). + // "MINIMIZE_RMSLE" - Minimize root-mean-squared log error (RMSLE). OptimizationObjective string `protobuf:"bytes,4,opt,name=optimization_objective,json=optimizationObjective,proto3" json:"optimization_objective,omitempty"` // Output only. Auxiliary information for each of the // input_feature_column_specs with respect to this particular model. @@ -434,8 +427,8 @@ type TablesAnnotation struct { // [target_column][google.cloud.automl.v1beta1.TablesModelMetadata.target_column_spec]. // The value depends on the column's DataType: // - // - CATEGORY - the predicted (with the above confidence `score`) CATEGORY - // value. + // * CATEGORY - the predicted (with the above confidence `score`) CATEGORY + // value. // // * FLOAT64 - the predicted (with above `prediction_interval`) FLOAT64 value. Value *structpb.Value `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"` diff --git a/automl/apiv1beta1/automlpb/temporal.pb.go b/automl/apiv1beta1/automlpb/temporal.pb.go index 13dbc51b8429..6488ec958a5c 100644 --- a/automl/apiv1beta1/automlpb/temporal.pb.go +++ b/automl/apiv1beta1/automlpb/temporal.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/automl/v1beta1/temporal.proto package automlpb diff --git a/automl/apiv1beta1/automlpb/text.pb.go b/automl/apiv1beta1/automlpb/text.pb.go index b9e233f7ab4f..3337d641800b 100644 --- a/automl/apiv1beta1/automlpb/text.pb.go +++ b/automl/apiv1beta1/automlpb/text.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/automl/v1beta1/text.proto package automlpb @@ -182,8 +182,8 @@ type TextExtractionModelMetadata struct { // // * `default`: Use to train a general text extraction model. Default value. // - // - `health_care`: Use to train a text extraction model that is tuned for - // healthcare applications. + // * `health_care`: Use to train a text extraction model that is tuned for + // healthcare applications. ModelHint string `protobuf:"bytes,3,opt,name=model_hint,json=modelHint,proto3" json:"model_hint,omitempty"` } diff --git a/automl/apiv1beta1/automlpb/text_extraction.pb.go b/automl/apiv1beta1/automlpb/text_extraction.pb.go index 7ef37c03073f..56044da9367f 100644 --- a/automl/apiv1beta1/automlpb/text_extraction.pb.go +++ b/automl/apiv1beta1/automlpb/text_extraction.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/automl/v1beta1/text_extraction.proto package automlpb @@ -45,7 +45,6 @@ type TextExtractionAnnotation struct { // text relation. // // Types that are assignable to Annotation: - // // *TextExtractionAnnotation_TextSegment Annotation isTextExtractionAnnotation_Annotation `protobuf_oneof:"annotation"` // Output only. A confidence estimate between 0.0 and 1.0. A higher value diff --git a/automl/apiv1beta1/automlpb/text_segment.pb.go b/automl/apiv1beta1/automlpb/text_segment.pb.go index 1fd88fe696f2..25969689311e 100644 --- a/automl/apiv1beta1/automlpb/text_segment.pb.go +++ b/automl/apiv1beta1/automlpb/text_segment.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/automl/v1beta1/text_segment.proto package automlpb diff --git a/automl/apiv1beta1/automlpb/text_sentiment.pb.go b/automl/apiv1beta1/automlpb/text_sentiment.pb.go index caaa5b2ab7a2..c3dcc985c6d9 100644 --- a/automl/apiv1beta1/automlpb/text_sentiment.pb.go +++ b/automl/apiv1beta1/automlpb/text_sentiment.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/automl/v1beta1/text_sentiment.proto package automlpb @@ -49,9 +49,7 @@ type TextSentimentAnnotation struct { // with higher value meaning more positive sentiment. They are completely // relative, i.e. 0 means least positive sentiment and sentiment_max means // the most positive from the sentiments present in the train data. Therefore - // - // e.g. if train data had only negative sentiment, then sentiment_max, would - // + // e.g. if train data had only negative sentiment, then sentiment_max, would // be still negative (although least negative). // The sentiment shouldn't be confused with "score" or "magnitude" // from the previous Natural Language Sentiment Analysis API. diff --git a/automl/apiv1beta1/automlpb/translation.pb.go b/automl/apiv1beta1/automlpb/translation.pb.go index bc93b5a733a1..9857575000b8 100644 --- a/automl/apiv1beta1/automlpb/translation.pb.go +++ b/automl/apiv1beta1/automlpb/translation.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/automl/v1beta1/translation.proto package automlpb diff --git a/automl/apiv1beta1/automlpb/video.pb.go b/automl/apiv1beta1/automlpb/video.pb.go index 2da325f0e9b0..e1a17ff6d5b8 100644 --- a/automl/apiv1beta1/automlpb/video.pb.go +++ b/automl/apiv1beta1/automlpb/video.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/automl/v1beta1/video.proto package automlpb diff --git a/automl/apiv1beta1/prediction_client.go b/automl/apiv1beta1/prediction_client.go index e74c2c498339..075d06891dbb 100644 --- a/automl/apiv1beta1/prediction_client.go +++ b/automl/apiv1beta1/prediction_client.go @@ -456,6 +456,11 @@ func (c *predictionRESTClient) Predict(ctx context.Context, req *automlpb.Predic } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:predict", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -531,6 +536,11 @@ func (c *predictionRESTClient) BatchPredict(ctx context.Context, req *automlpb.B } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:batchPredict", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) diff --git a/baremetalsolution/apiv2/bare_metal_solution_client.go b/baremetalsolution/apiv2/bare_metal_solution_client.go index 4158783a73e0..427781d26daa 100644 --- a/baremetalsolution/apiv2/bare_metal_solution_client.go +++ b/baremetalsolution/apiv2/bare_metal_solution_client.go @@ -17,9 +17,12 @@ package baremetalsolution import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,14 +30,17 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -105,6 +111,33 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + ListInstances: []gax.CallOption{}, + GetInstance: []gax.CallOption{}, + UpdateInstance: []gax.CallOption{}, + ResetInstance: []gax.CallOption{}, + StartInstance: []gax.CallOption{}, + StopInstance: []gax.CallOption{}, + DetachLun: []gax.CallOption{}, + ListVolumes: []gax.CallOption{}, + GetVolume: []gax.CallOption{}, + UpdateVolume: []gax.CallOption{}, + ResizeVolume: []gax.CallOption{}, + ListNetworks: []gax.CallOption{}, + ListNetworkUsage: []gax.CallOption{}, + GetNetwork: []gax.CallOption{}, + UpdateNetwork: []gax.CallOption{}, + GetLun: []gax.CallOption{}, + ListLuns: []gax.CallOption{}, + GetNfsShare: []gax.CallOption{}, + ListNfsShares: []gax.CallOption{}, + UpdateNfsShare: []gax.CallOption{}, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + } +} + // internalClient is an interface that defines the methods available from Bare Metal Solution API. type internalClient interface { Close() error @@ -463,6 +496,96 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new bare metal solution rest client. +// +// Performs management operations on Bare Metal Solution servers. +// +// The baremetalsolution.googleapis.com service provides management +// capabilities for Bare Metal Solution servers. To access the API methods, you +// must assign Bare Metal Solution IAM roles containing the desired permissions +// to your staff in your Google Cloud project. You must also enable the Bare +// Metal Solution API. Once enabled, the methods act +// upon specific servers in your Bare Metal Solution environment. +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://baremetalsolution.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://baremetalsolution.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://baremetalsolution.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) ListInstances(ctx context.Context, req *baremetalsolutionpb.ListInstancesRequest, opts ...gax.CallOption) *InstanceIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1098,139 +1221,1760 @@ func (c *gRPCClient) ListLocations(ctx context.Context, req *locationpb.ListLoca return it } -// DetachLunOperation manages a long-running operation from DetachLun. -type DetachLunOperation struct { - lro *longrunning.Operation -} +// ListInstances list servers in a given project and location. +func (c *restClient) ListInstances(ctx context.Context, req *baremetalsolutionpb.ListInstancesRequest, opts ...gax.CallOption) *InstanceIterator { + it := &InstanceIterator{} + req = proto.Clone(req).(*baremetalsolutionpb.ListInstancesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*baremetalsolutionpb.Instance, string, error) { + resp := &baremetalsolutionpb.ListInstancesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/instances", req.GetParent()) -// DetachLunOperation returns a new DetachLunOperation from a given name. -// The name must be that of a previously created DetachLunOperation, possibly from a different process. -func (c *gRPCClient) DetachLunOperation(name string) *DetachLunOperation { - return &DetachLunOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *DetachLunOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*baremetalsolutionpb.Instance, error) { - var resp baremetalsolutionpb.Instance - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { - return nil, err + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetInstances(), resp.GetNextPageToken(), nil } - return &resp, nil -} -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *DetachLunOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*baremetalsolutionpb.Instance, error) { - var resp baremetalsolutionpb.Instance - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { - return nil, err - } - if !op.Done() { - return nil, 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 } - return &resp, nil + + it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it } -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *DetachLunOperation) Metadata() (*baremetalsolutionpb.OperationMetadata, error) { - var meta baremetalsolutionpb.OperationMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { +// GetInstance get details about a single server. +func (c *restClient) GetInstance(ctx context.Context, req *baremetalsolutionpb.GetInstanceRequest, opts ...gax.CallOption) (*baremetalsolutionpb.Instance, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - return &meta, nil -} + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) -// Done reports whether the long-running operation has completed. -func (op *DetachLunOperation) Done() bool { - return op.lro.Done() -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") -// 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 *DetachLunOperation) Name() string { - return op.lro.Name() -} + baseUrl.RawQuery = params.Encode() -// ResetInstanceOperation manages a long-running operation from ResetInstance. -type ResetInstanceOperation struct { - lro *longrunning.Operation -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) -// ResetInstanceOperation returns a new ResetInstanceOperation from a given name. -// The name must be that of a previously created ResetInstanceOperation, possibly from a different process. -func (c *gRPCClient) ResetInstanceOperation(name string) *ResetInstanceOperation { - return &ResetInstanceOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetInstance[0:len((*c.CallOptions).GetInstance):len((*c.CallOptions).GetInstance)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &baremetalsolutionpb.Instance{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e } + return resp, nil } -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *ResetInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*baremetalsolutionpb.ResetInstanceResponse, error) { - var resp baremetalsolutionpb.ResetInstanceResponse - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { +// UpdateInstance update details of a single server. +func (c *restClient) UpdateInstance(ctx context.Context, req *baremetalsolutionpb.UpdateInstanceRequest, opts ...gax.CallOption) (*UpdateInstanceOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetInstance() + jsonReq, err := m.Marshal(body) + if err != nil { return nil, err } - return &resp, nil -} -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *ResetInstanceOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*baremetalsolutionpb.ResetInstanceResponse, error) { - var resp baremetalsolutionpb.ResetInstanceResponse - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - if !op.Done() { - return nil, nil - } - return &resp, nil -} + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetInstance().GetName()) -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *ResetInstanceOperation) Metadata() (*baremetalsolutionpb.OperationMetadata, error) { - var meta baremetalsolutionpb.OperationMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { - return nil, err + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) } - return &meta, nil -} -// Done reports whether the long-running operation has completed. -func (op *ResetInstanceOperation) Done() bool { - return op.lro.Done() -} + baseUrl.RawQuery = params.Encode() -// Name returns the name of the long-running operation. + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "instance.name", url.QueryEscape(req.GetInstance().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &UpdateInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ResetInstance perform an ungraceful, hard reset on a server. Equivalent to shutting the +// power off and then turning it back on. +func (c *restClient) ResetInstance(ctx context.Context, req *baremetalsolutionpb.ResetInstanceRequest, opts ...gax.CallOption) (*ResetInstanceOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:reset", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &ResetInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// StartInstance starts a server that was shutdown. +func (c *restClient) StartInstance(ctx context.Context, req *baremetalsolutionpb.StartInstanceRequest, opts ...gax.CallOption) (*StartInstanceOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:start", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &StartInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// StopInstance stop a running server. +func (c *restClient) StopInstance(ctx context.Context, req *baremetalsolutionpb.StopInstanceRequest, opts ...gax.CallOption) (*StopInstanceOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:stop", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &StopInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DetachLun detach LUN from Instance. +func (c *restClient) DetachLun(ctx context.Context, req *baremetalsolutionpb.DetachLunRequest, opts ...gax.CallOption) (*DetachLunOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:detachLun", req.GetInstance()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "instance", url.QueryEscape(req.GetInstance()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &DetachLunOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListVolumes list storage volumes in a given project and location. +func (c *restClient) ListVolumes(ctx context.Context, req *baremetalsolutionpb.ListVolumesRequest, opts ...gax.CallOption) *VolumeIterator { + it := &VolumeIterator{} + req = proto.Clone(req).(*baremetalsolutionpb.ListVolumesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*baremetalsolutionpb.Volume, string, error) { + resp := &baremetalsolutionpb.ListVolumesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/volumes", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetVolumes(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetVolume get details of a single storage volume. +func (c *restClient) GetVolume(ctx context.Context, req *baremetalsolutionpb.GetVolumeRequest, opts ...gax.CallOption) (*baremetalsolutionpb.Volume, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetVolume[0:len((*c.CallOptions).GetVolume):len((*c.CallOptions).GetVolume)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &baremetalsolutionpb.Volume{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateVolume update details of a single storage volume. +func (c *restClient) UpdateVolume(ctx context.Context, req *baremetalsolutionpb.UpdateVolumeRequest, opts ...gax.CallOption) (*UpdateVolumeOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetVolume() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetVolume().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "volume.name", url.QueryEscape(req.GetVolume().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &UpdateVolumeOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ResizeVolume emergency Volume resize. +func (c *restClient) ResizeVolume(ctx context.Context, req *baremetalsolutionpb.ResizeVolumeRequest, opts ...gax.CallOption) (*ResizeVolumeOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:resize", req.GetVolume()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "volume", url.QueryEscape(req.GetVolume()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &ResizeVolumeOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListNetworks list network in a given project and location. +func (c *restClient) ListNetworks(ctx context.Context, req *baremetalsolutionpb.ListNetworksRequest, opts ...gax.CallOption) *NetworkIterator { + it := &NetworkIterator{} + req = proto.Clone(req).(*baremetalsolutionpb.ListNetworksRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*baremetalsolutionpb.Network, string, error) { + resp := &baremetalsolutionpb.ListNetworksResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/networks", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetNetworks(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// ListNetworkUsage list all Networks (and used IPs for each Network) in the vendor account +// associated with the specified project. +func (c *restClient) ListNetworkUsage(ctx context.Context, req *baremetalsolutionpb.ListNetworkUsageRequest, opts ...gax.CallOption) (*baremetalsolutionpb.ListNetworkUsageResponse, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/networks:listNetworkUsage", req.GetLocation()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "location", url.QueryEscape(req.GetLocation()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).ListNetworkUsage[0:len((*c.CallOptions).ListNetworkUsage):len((*c.CallOptions).ListNetworkUsage)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &baremetalsolutionpb.ListNetworkUsageResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetNetwork get details of a single network. +func (c *restClient) GetNetwork(ctx context.Context, req *baremetalsolutionpb.GetNetworkRequest, opts ...gax.CallOption) (*baremetalsolutionpb.Network, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetNetwork[0:len((*c.CallOptions).GetNetwork):len((*c.CallOptions).GetNetwork)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &baremetalsolutionpb.Network{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateNetwork update details of a single network. +func (c *restClient) UpdateNetwork(ctx context.Context, req *baremetalsolutionpb.UpdateNetworkRequest, opts ...gax.CallOption) (*UpdateNetworkOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetNetwork() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetNetwork().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "network.name", url.QueryEscape(req.GetNetwork().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &UpdateNetworkOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetLun get details of a single storage logical unit number(LUN). +func (c *restClient) GetLun(ctx context.Context, req *baremetalsolutionpb.GetLunRequest, opts ...gax.CallOption) (*baremetalsolutionpb.Lun, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLun[0:len((*c.CallOptions).GetLun):len((*c.CallOptions).GetLun)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &baremetalsolutionpb.Lun{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLuns list storage volume luns for given storage volume. +func (c *restClient) ListLuns(ctx context.Context, req *baremetalsolutionpb.ListLunsRequest, opts ...gax.CallOption) *LunIterator { + it := &LunIterator{} + req = proto.Clone(req).(*baremetalsolutionpb.ListLunsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*baremetalsolutionpb.Lun, string, error) { + resp := &baremetalsolutionpb.ListLunsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/luns", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLuns(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetNfsShare get details of a single NFS share. +func (c *restClient) GetNfsShare(ctx context.Context, req *baremetalsolutionpb.GetNfsShareRequest, opts ...gax.CallOption) (*baremetalsolutionpb.NfsShare, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetNfsShare[0:len((*c.CallOptions).GetNfsShare):len((*c.CallOptions).GetNfsShare)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &baremetalsolutionpb.NfsShare{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListNfsShares list NFS shares. +func (c *restClient) ListNfsShares(ctx context.Context, req *baremetalsolutionpb.ListNfsSharesRequest, opts ...gax.CallOption) *NfsShareIterator { + it := &NfsShareIterator{} + req = proto.Clone(req).(*baremetalsolutionpb.ListNfsSharesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*baremetalsolutionpb.NfsShare, string, error) { + resp := &baremetalsolutionpb.ListNfsSharesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/nfsShares", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetNfsShares(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// UpdateNfsShare update details of a single NFS share. +func (c *restClient) UpdateNfsShare(ctx context.Context, req *baremetalsolutionpb.UpdateNfsShareRequest, opts ...gax.CallOption) (*UpdateNfsShareOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetNfsShare() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetNfsShare().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "nfs_share.name", url.QueryEscape(req.GetNfsShare().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &UpdateNfsShareOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetLocation gets information about a location. +func (c *restClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *restClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// DetachLunOperation manages a long-running operation from DetachLun. +type DetachLunOperation struct { + lro *longrunning.Operation + pollPath string +} + +// DetachLunOperation returns a new DetachLunOperation from a given name. +// The name must be that of a previously created DetachLunOperation, possibly from a different process. +func (c *gRPCClient) DetachLunOperation(name string) *DetachLunOperation { + return &DetachLunOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// DetachLunOperation returns a new DetachLunOperation from a given name. +// The name must be that of a previously created DetachLunOperation, possibly from a different process. +func (c *restClient) DetachLunOperation(name string) *DetachLunOperation { + override := fmt.Sprintf("/v2/%s", name) + return &DetachLunOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *DetachLunOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*baremetalsolutionpb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp baremetalsolutionpb.Instance + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *DetachLunOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*baremetalsolutionpb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp baremetalsolutionpb.Instance + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *DetachLunOperation) Metadata() (*baremetalsolutionpb.OperationMetadata, error) { + var meta baremetalsolutionpb.OperationMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *DetachLunOperation) Done() bool { + return op.lro.Done() +} + +// 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 *DetachLunOperation) Name() string { + return op.lro.Name() +} + +// ResetInstanceOperation manages a long-running operation from ResetInstance. +type ResetInstanceOperation struct { + lro *longrunning.Operation + pollPath string +} + +// ResetInstanceOperation returns a new ResetInstanceOperation from a given name. +// The name must be that of a previously created ResetInstanceOperation, possibly from a different process. +func (c *gRPCClient) ResetInstanceOperation(name string) *ResetInstanceOperation { + return &ResetInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// ResetInstanceOperation returns a new ResetInstanceOperation from a given name. +// The name must be that of a previously created ResetInstanceOperation, possibly from a different process. +func (c *restClient) ResetInstanceOperation(name string) *ResetInstanceOperation { + override := fmt.Sprintf("/v2/%s", name) + return &ResetInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *ResetInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*baremetalsolutionpb.ResetInstanceResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp baremetalsolutionpb.ResetInstanceResponse + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *ResetInstanceOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*baremetalsolutionpb.ResetInstanceResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp baremetalsolutionpb.ResetInstanceResponse + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *ResetInstanceOperation) Metadata() (*baremetalsolutionpb.OperationMetadata, error) { + var meta baremetalsolutionpb.OperationMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *ResetInstanceOperation) Done() bool { + return op.lro.Done() +} + +// 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 *ResetInstanceOperation) Name() string { return op.lro.Name() @@ -1238,7 +2982,8 @@ func (op *ResetInstanceOperation) Name() string { // ResizeVolumeOperation manages a long-running operation from ResizeVolume. type ResizeVolumeOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // ResizeVolumeOperation returns a new ResizeVolumeOperation from a given name. @@ -1249,10 +2994,21 @@ func (c *gRPCClient) ResizeVolumeOperation(name string) *ResizeVolumeOperation { } } +// ResizeVolumeOperation returns a new ResizeVolumeOperation from a given name. +// The name must be that of a previously created ResizeVolumeOperation, possibly from a different process. +func (c *restClient) ResizeVolumeOperation(name string) *ResizeVolumeOperation { + override := fmt.Sprintf("/v2/%s", name) + return &ResizeVolumeOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *ResizeVolumeOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*baremetalsolutionpb.Volume, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp baremetalsolutionpb.Volume if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1270,6 +3026,7 @@ func (op *ResizeVolumeOperation) Wait(ctx context.Context, opts ...gax.CallOptio // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *ResizeVolumeOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*baremetalsolutionpb.Volume, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp baremetalsolutionpb.Volume if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1307,7 +3064,8 @@ func (op *ResizeVolumeOperation) Name() string { // StartInstanceOperation manages a long-running operation from StartInstance. type StartInstanceOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // StartInstanceOperation returns a new StartInstanceOperation from a given name. @@ -1318,10 +3076,21 @@ func (c *gRPCClient) StartInstanceOperation(name string) *StartInstanceOperation } } +// StartInstanceOperation returns a new StartInstanceOperation from a given name. +// The name must be that of a previously created StartInstanceOperation, possibly from a different process. +func (c *restClient) StartInstanceOperation(name string) *StartInstanceOperation { + override := fmt.Sprintf("/v2/%s", name) + return &StartInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *StartInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*baremetalsolutionpb.StartInstanceResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp baremetalsolutionpb.StartInstanceResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1339,6 +3108,7 @@ func (op *StartInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOpti // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *StartInstanceOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*baremetalsolutionpb.StartInstanceResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp baremetalsolutionpb.StartInstanceResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1376,7 +3146,8 @@ func (op *StartInstanceOperation) Name() string { // StopInstanceOperation manages a long-running operation from StopInstance. type StopInstanceOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // StopInstanceOperation returns a new StopInstanceOperation from a given name. @@ -1387,10 +3158,21 @@ func (c *gRPCClient) StopInstanceOperation(name string) *StopInstanceOperation { } } +// StopInstanceOperation returns a new StopInstanceOperation from a given name. +// The name must be that of a previously created StopInstanceOperation, possibly from a different process. +func (c *restClient) StopInstanceOperation(name string) *StopInstanceOperation { + override := fmt.Sprintf("/v2/%s", name) + return &StopInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *StopInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*baremetalsolutionpb.StopInstanceResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp baremetalsolutionpb.StopInstanceResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1408,6 +3190,7 @@ func (op *StopInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOptio // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *StopInstanceOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*baremetalsolutionpb.StopInstanceResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp baremetalsolutionpb.StopInstanceResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1445,7 +3228,8 @@ func (op *StopInstanceOperation) Name() string { // UpdateInstanceOperation manages a long-running operation from UpdateInstance. type UpdateInstanceOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateInstanceOperation returns a new UpdateInstanceOperation from a given name. @@ -1456,10 +3240,21 @@ func (c *gRPCClient) UpdateInstanceOperation(name string) *UpdateInstanceOperati } } +// UpdateInstanceOperation returns a new UpdateInstanceOperation from a given name. +// The name must be that of a previously created UpdateInstanceOperation, possibly from a different process. +func (c *restClient) UpdateInstanceOperation(name string) *UpdateInstanceOperation { + override := fmt.Sprintf("/v2/%s", name) + return &UpdateInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*baremetalsolutionpb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp baremetalsolutionpb.Instance if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1477,6 +3272,7 @@ func (op *UpdateInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOpt // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateInstanceOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*baremetalsolutionpb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp baremetalsolutionpb.Instance if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1514,7 +3310,8 @@ func (op *UpdateInstanceOperation) Name() string { // UpdateNetworkOperation manages a long-running operation from UpdateNetwork. type UpdateNetworkOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateNetworkOperation returns a new UpdateNetworkOperation from a given name. @@ -1525,10 +3322,21 @@ func (c *gRPCClient) UpdateNetworkOperation(name string) *UpdateNetworkOperation } } +// UpdateNetworkOperation returns a new UpdateNetworkOperation from a given name. +// The name must be that of a previously created UpdateNetworkOperation, possibly from a different process. +func (c *restClient) UpdateNetworkOperation(name string) *UpdateNetworkOperation { + override := fmt.Sprintf("/v2/%s", name) + return &UpdateNetworkOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateNetworkOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*baremetalsolutionpb.Network, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp baremetalsolutionpb.Network if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1546,6 +3354,7 @@ func (op *UpdateNetworkOperation) Wait(ctx context.Context, opts ...gax.CallOpti // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateNetworkOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*baremetalsolutionpb.Network, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp baremetalsolutionpb.Network if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1583,7 +3392,8 @@ func (op *UpdateNetworkOperation) Name() string { // UpdateNfsShareOperation manages a long-running operation from UpdateNfsShare. type UpdateNfsShareOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateNfsShareOperation returns a new UpdateNfsShareOperation from a given name. @@ -1594,10 +3404,21 @@ func (c *gRPCClient) UpdateNfsShareOperation(name string) *UpdateNfsShareOperati } } +// UpdateNfsShareOperation returns a new UpdateNfsShareOperation from a given name. +// The name must be that of a previously created UpdateNfsShareOperation, possibly from a different process. +func (c *restClient) UpdateNfsShareOperation(name string) *UpdateNfsShareOperation { + override := fmt.Sprintf("/v2/%s", name) + return &UpdateNfsShareOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateNfsShareOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*baremetalsolutionpb.NfsShare, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp baremetalsolutionpb.NfsShare if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1615,6 +3436,7 @@ func (op *UpdateNfsShareOperation) Wait(ctx context.Context, opts ...gax.CallOpt // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateNfsShareOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*baremetalsolutionpb.NfsShare, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp baremetalsolutionpb.NfsShare if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1652,7 +3474,8 @@ func (op *UpdateNfsShareOperation) Name() string { // UpdateVolumeOperation manages a long-running operation from UpdateVolume. type UpdateVolumeOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateVolumeOperation returns a new UpdateVolumeOperation from a given name. @@ -1663,10 +3486,21 @@ func (c *gRPCClient) UpdateVolumeOperation(name string) *UpdateVolumeOperation { } } +// UpdateVolumeOperation returns a new UpdateVolumeOperation from a given name. +// The name must be that of a previously created UpdateVolumeOperation, possibly from a different process. +func (c *restClient) UpdateVolumeOperation(name string) *UpdateVolumeOperation { + override := fmt.Sprintf("/v2/%s", name) + return &UpdateVolumeOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateVolumeOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*baremetalsolutionpb.Volume, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp baremetalsolutionpb.Volume if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1684,6 +3518,7 @@ func (op *UpdateVolumeOperation) Wait(ctx context.Context, opts ...gax.CallOptio // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateVolumeOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*baremetalsolutionpb.Volume, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp baremetalsolutionpb.Volume if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/baremetalsolution/apiv2/bare_metal_solution_client_example_test.go b/baremetalsolution/apiv2/bare_metal_solution_client_example_test.go index 2e13fa206179..9bb5fda5c82b 100644 --- a/baremetalsolution/apiv2/bare_metal_solution_client_example_test.go +++ b/baremetalsolution/apiv2/bare_metal_solution_client_example_test.go @@ -42,6 +42,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := baremetalsolution.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_ListInstances() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/baremetalsolution/apiv2/baremetalsolutionpb/baremetalsolution.pb.go b/baremetalsolution/apiv2/baremetalsolutionpb/baremetalsolution.pb.go index 0e83d2bc4719..d510c97d2e29 100644 --- a/baremetalsolution/apiv2/baremetalsolutionpb/baremetalsolution.pb.go +++ b/baremetalsolution/apiv2/baremetalsolutionpb/baremetalsolution.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/baremetalsolution/v2/baremetalsolution.proto package baremetalsolutionpb diff --git a/baremetalsolution/apiv2/baremetalsolutionpb/instance.pb.go b/baremetalsolution/apiv2/baremetalsolutionpb/instance.pb.go index c7f512b6b0b3..92cc339dbec8 100644 --- a/baremetalsolution/apiv2/baremetalsolutionpb/instance.pb.go +++ b/baremetalsolution/apiv2/baremetalsolutionpb/instance.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/baremetalsolution/v2/instance.proto package baremetalsolutionpb @@ -549,10 +549,9 @@ type UpdateInstanceRequest struct { Instance *Instance `protobuf:"bytes,1,opt,name=instance,proto3" json:"instance,omitempty"` // The list of fields to update. // The currently supported fields are: - // - // `labels` - // `hyperthreading_enabled` - // `os_image` + // `labels` + // `hyperthreading_enabled` + // `os_image` UpdateMask *fieldmaskpb.FieldMask `protobuf:"bytes,2,opt,name=update_mask,json=updateMask,proto3" json:"update_mask,omitempty"` } diff --git a/baremetalsolution/apiv2/baremetalsolutionpb/lun.pb.go b/baremetalsolution/apiv2/baremetalsolutionpb/lun.pb.go index 23a70eeec75a..815f40bfbda1 100644 --- a/baremetalsolution/apiv2/baremetalsolutionpb/lun.pb.go +++ b/baremetalsolution/apiv2/baremetalsolutionpb/lun.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/baremetalsolution/v2/lun.proto package baremetalsolutionpb diff --git a/baremetalsolution/apiv2/baremetalsolutionpb/network.pb.go b/baremetalsolution/apiv2/baremetalsolutionpb/network.pb.go index 96ce0cbba80e..2925ae8adeab 100644 --- a/baremetalsolution/apiv2/baremetalsolutionpb/network.pb.go +++ b/baremetalsolution/apiv2/baremetalsolutionpb/network.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/baremetalsolution/v2/network.proto package baremetalsolutionpb @@ -775,8 +775,7 @@ type UpdateNetworkRequest struct { Network *Network `protobuf:"bytes,1,opt,name=network,proto3" json:"network,omitempty"` // The list of fields to update. // The only currently supported fields are: - // - // `labels`, `reservations` + // `labels`, `reservations` UpdateMask *fieldmaskpb.FieldMask `protobuf:"bytes,2,opt,name=update_mask,json=updateMask,proto3" json:"update_mask,omitempty"` } diff --git a/baremetalsolution/apiv2/baremetalsolutionpb/nfs_share.pb.go b/baremetalsolution/apiv2/baremetalsolutionpb/nfs_share.pb.go index 840e3354d4a2..6ea3b0af3571 100644 --- a/baremetalsolution/apiv2/baremetalsolutionpb/nfs_share.pb.go +++ b/baremetalsolution/apiv2/baremetalsolutionpb/nfs_share.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/baremetalsolution/v2/nfs_share.proto package baremetalsolutionpb @@ -439,8 +439,7 @@ type UpdateNfsShareRequest struct { NfsShare *NfsShare `protobuf:"bytes,1,opt,name=nfs_share,json=nfsShare,proto3" json:"nfs_share,omitempty"` // The list of fields to update. // The only currently supported fields are: - // - // `labels` + // `labels` UpdateMask *fieldmaskpb.FieldMask `protobuf:"bytes,2,opt,name=update_mask,json=updateMask,proto3" json:"update_mask,omitempty"` } diff --git a/baremetalsolution/apiv2/baremetalsolutionpb/volume.pb.go b/baremetalsolution/apiv2/baremetalsolutionpb/volume.pb.go index 614ae51a5944..fda368b4e639 100644 --- a/baremetalsolution/apiv2/baremetalsolutionpb/volume.pb.go +++ b/baremetalsolution/apiv2/baremetalsolutionpb/volume.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/baremetalsolution/v2/volume.proto package baremetalsolutionpb @@ -587,12 +587,11 @@ type UpdateVolumeRequest struct { Volume *Volume `protobuf:"bytes,1,opt,name=volume,proto3" json:"volume,omitempty"` // The list of fields to update. // The only currently supported fields are: - // - // `snapshot_auto_delete_behavior` - // `snapshot_schedule_policy_name` - // 'labels' - // 'snapshot_enabled' - // 'snapshot_reservation_detail.reserved_space_percent' + // `snapshot_auto_delete_behavior` + // `snapshot_schedule_policy_name` + // 'labels' + // 'snapshot_enabled' + // 'snapshot_reservation_detail.reserved_space_percent' UpdateMask *fieldmaskpb.FieldMask `protobuf:"bytes,2,opt,name=update_mask,json=updateMask,proto3" json:"update_mask,omitempty"` } diff --git a/baremetalsolution/apiv2/doc.go b/baremetalsolution/apiv2/doc.go index 63d87c7c880b..0760a26814c6 100644 --- a/baremetalsolution/apiv2/doc.go +++ b/baremetalsolution/apiv2/doc.go @@ -89,6 +89,8 @@ package baremetalsolution // import "cloud.google.com/go/baremetalsolution/apiv2 import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -177,3 +179,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/baremetalsolution/apiv2/gapic_metadata.json b/baremetalsolution/apiv2/gapic_metadata.json index 3f40fd7c8d91..0995838173e3 100644 --- a/baremetalsolution/apiv2/gapic_metadata.json +++ b/baremetalsolution/apiv2/gapic_metadata.json @@ -121,6 +121,121 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "DetachLun": { + "methods": [ + "DetachLun" + ] + }, + "GetInstance": { + "methods": [ + "GetInstance" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "GetLun": { + "methods": [ + "GetLun" + ] + }, + "GetNetwork": { + "methods": [ + "GetNetwork" + ] + }, + "GetNfsShare": { + "methods": [ + "GetNfsShare" + ] + }, + "GetVolume": { + "methods": [ + "GetVolume" + ] + }, + "ListInstances": { + "methods": [ + "ListInstances" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListLuns": { + "methods": [ + "ListLuns" + ] + }, + "ListNetworkUsage": { + "methods": [ + "ListNetworkUsage" + ] + }, + "ListNetworks": { + "methods": [ + "ListNetworks" + ] + }, + "ListNfsShares": { + "methods": [ + "ListNfsShares" + ] + }, + "ListVolumes": { + "methods": [ + "ListVolumes" + ] + }, + "ResetInstance": { + "methods": [ + "ResetInstance" + ] + }, + "ResizeVolume": { + "methods": [ + "ResizeVolume" + ] + }, + "StartInstance": { + "methods": [ + "StartInstance" + ] + }, + "StopInstance": { + "methods": [ + "StopInstance" + ] + }, + "UpdateInstance": { + "methods": [ + "UpdateInstance" + ] + }, + "UpdateNetwork": { + "methods": [ + "UpdateNetwork" + ] + }, + "UpdateNfsShare": { + "methods": [ + "UpdateNfsShare" + ] + }, + "UpdateVolume": { + "methods": [ + "UpdateVolume" + ] + } + } } } } diff --git a/batch/apiv1/batch_client.go b/batch/apiv1/batch_client.go index 183019e4d075..58fd825a907b 100644 --- a/batch/apiv1/batch_client.go +++ b/batch/apiv1/batch_client.go @@ -17,9 +17,12 @@ package batch import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,16 +30,19 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" iampb "google.golang.org/genproto/googleapis/iam/v1" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -133,6 +139,62 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + CreateJob: []gax.CallOption{}, + GetJob: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeleteJob: []gax.CallOption{}, + ListJobs: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetTask: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListTasks: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + GetIamPolicy: []gax.CallOption{}, + SetIamPolicy: []gax.CallOption{}, + TestIamPermissions: []gax.CallOption{}, + CancelOperation: []gax.CallOption{}, + DeleteOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalClient is an interface that defines the methods available from Batch API. type internalClient interface { Close() error @@ -398,6 +460,91 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new batch service rest client. +// +// Google Batch Service. +// The service manages user submitted batch jobs and allocates Google Compute +// Engine VM instances to run the jobs. +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://batch.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://batch.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://batch.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) CreateJob(ctx context.Context, req *batchpb.CreateJobRequest, opts ...gax.CallOption) (*batchpb.Job, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) @@ -779,16 +926,1048 @@ func (c *gRPCClient) ListOperations(ctx context.Context, req *longrunningpb.List return it } -// DeleteJobOperation manages a long-running operation from DeleteJob. -type DeleteJobOperation struct { - lro *longrunning.Operation +// CreateJob create a Job. +func (c *restClient) CreateJob(ctx context.Context, req *batchpb.CreateJobRequest, opts ...gax.CallOption) (*batchpb.Job, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetJob() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/jobs", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetJobId() != "" { + params.Add("jobId", fmt.Sprintf("%v", req.GetJobId())) + } + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateJob[0:len((*c.CallOptions).CreateJob):len((*c.CallOptions).CreateJob)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &batchpb.Job{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil } -// DeleteJobOperation returns a new DeleteJobOperation from a given name. -// The name must be that of a previously created DeleteJobOperation, possibly from a different process. -func (c *gRPCClient) DeleteJobOperation(name string) *DeleteJobOperation { +// GetJob get a Job specified by its resource name. +func (c *restClient) GetJob(ctx context.Context, req *batchpb.GetJobRequest, opts ...gax.CallOption) (*batchpb.Job, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetJob[0:len((*c.CallOptions).GetJob):len((*c.CallOptions).GetJob)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &batchpb.Job{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteJob delete a Job. +func (c *restClient) DeleteJob(ctx context.Context, req *batchpb.DeleteJobRequest, opts ...gax.CallOption) (*DeleteJobOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetReason() != "" { + params.Add("reason", fmt.Sprintf("%v", req.GetReason())) + } + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) return &DeleteJobOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListJobs list all Jobs for a project within a region. +func (c *restClient) ListJobs(ctx context.Context, req *batchpb.ListJobsRequest, opts ...gax.CallOption) *JobIterator { + it := &JobIterator{} + req = proto.Clone(req).(*batchpb.ListJobsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*batchpb.Job, string, error) { + resp := &batchpb.ListJobsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/jobs", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetJobs(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetTask return a single Task. +func (c *restClient) GetTask(ctx context.Context, req *batchpb.GetTaskRequest, opts ...gax.CallOption) (*batchpb.Task, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetTask[0:len((*c.CallOptions).GetTask):len((*c.CallOptions).GetTask)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &batchpb.Task{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListTasks list Tasks associated with a job. +func (c *restClient) ListTasks(ctx context.Context, req *batchpb.ListTasksRequest, opts ...gax.CallOption) *TaskIterator { + it := &TaskIterator{} + req = proto.Clone(req).(*batchpb.ListTasksRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*batchpb.Task, string, error) { + resp := &batchpb.ListTasksResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/tasks", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetTasks(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetLocation gets information about a location. +func (c *restClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *restClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetIamPolicy gets the access control policy for a resource. Returns an empty policy +// if the resource exists and does not have a policy set. +func (c *restClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:getIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetOptions().GetRequestedPolicyVersion() != 0 { + params.Add("options.requestedPolicyVersion", fmt.Sprintf("%v", req.GetOptions().GetRequestedPolicyVersion())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SetIamPolicy sets the access control policy on the specified resource. Replaces +// any existing policy. +// +// Can return NOT_FOUND, INVALID_ARGUMENT, and PERMISSION_DENIED +// errors. +func (c *restClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:setIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// TestIamPermissions returns permissions that a caller has on the specified resource. If the +// resource does not exist, this will return an empty set of +// permissions, not a NOT_FOUND error. +// +// Note: This operation is designed to be used for building +// permission-aware UIs and command-line tools, not for authorization +// checking. This operation may “fail open” without warning. +func (c *restClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:testIamPermissions", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.TestIamPermissionsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *restClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// DeleteOperation is a utility method from google.longrunning.Operations. +func (c *restClient) DeleteOperation(ctx context.Context, req *longrunningpb.DeleteOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *restClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *restClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// DeleteJobOperation manages a long-running operation from DeleteJob. +type DeleteJobOperation struct { + lro *longrunning.Operation + pollPath string +} + +// DeleteJobOperation returns a new DeleteJobOperation from a given name. +// The name must be that of a previously created DeleteJobOperation, possibly from a different process. +func (c *gRPCClient) DeleteJobOperation(name string) *DeleteJobOperation { + return &DeleteJobOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// DeleteJobOperation returns a new DeleteJobOperation from a given name. +// The name must be that of a previously created DeleteJobOperation, possibly from a different process. +func (c *restClient) DeleteJobOperation(name string) *DeleteJobOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteJobOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, } } @@ -796,6 +1975,7 @@ func (c *gRPCClient) DeleteJobOperation(name string) *DeleteJobOperation { // // See documentation of Poll for error-handling information. func (op *DeleteJobOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -809,6 +1989,7 @@ func (op *DeleteJobOperation) Wait(ctx context.Context, opts ...gax.CallOption) // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteJobOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } diff --git a/batch/apiv1/batch_client_example_test.go b/batch/apiv1/batch_client_example_test.go index 1ddcc9a896bd..c25645f72546 100644 --- a/batch/apiv1/batch_client_example_test.go +++ b/batch/apiv1/batch_client_example_test.go @@ -44,6 +44,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := batch.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_CreateJob() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/batch/apiv1/batchpb/batch.pb.go b/batch/apiv1/batchpb/batch.pb.go index 1ea1c843d18d..1f93ac93b48f 100644 --- a/batch/apiv1/batchpb/batch.pb.go +++ b/batch/apiv1/batchpb/batch.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/batch/v1/batch.proto package batchpb diff --git a/batch/apiv1/batchpb/job.pb.go b/batch/apiv1/batchpb/job.pb.go index 1e3d404f79da..896c800f5170 100644 --- a/batch/apiv1/batchpb/job.pb.go +++ b/batch/apiv1/batchpb/job.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/batch/v1/job.proto package batchpb @@ -300,12 +300,10 @@ type Job struct { AllocationPolicy *AllocationPolicy `protobuf:"bytes,7,opt,name=allocation_policy,json=allocationPolicy,proto3" json:"allocation_policy,omitempty"` // Labels for the Job. Labels could be user provided or system generated. // For example, - // - // "labels": { - // "department": "finance", - // "environment": "test" - // } - // + // "labels": { + // "department": "finance", + // "environment": "test" + // } // You can assign up to 64 labels. [Google Compute Engine label // restrictions](https://cloud.google.com/compute/docs/labeling-resources#restrictions) // apply. @@ -1177,7 +1175,6 @@ type AllocationPolicy_Disk struct { // A data source from which a PD will be created. // // Types that are assignable to DataSource: - // // *AllocationPolicy_Disk_Image // *AllocationPolicy_Disk_Snapshot DataSource isAllocationPolicy_Disk_DataSource `protobuf_oneof:"data_source"` @@ -1295,7 +1292,6 @@ type AllocationPolicy_AttachedDisk struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Attached: - // // *AllocationPolicy_AttachedDisk_NewDisk // *AllocationPolicy_AttachedDisk_ExistingDisk Attached isAllocationPolicy_AttachedDisk_Attached `protobuf_oneof:"attached"` @@ -1551,7 +1547,6 @@ type AllocationPolicy_InstancePolicyOrTemplate struct { unknownFields protoimpl.UnknownFields // Types that are assignable to PolicyTemplate: - // // *AllocationPolicy_InstancePolicyOrTemplate_Policy // *AllocationPolicy_InstancePolicyOrTemplate_InstanceTemplate PolicyTemplate isAllocationPolicy_InstancePolicyOrTemplate_PolicyTemplate `protobuf_oneof:"policy_template"` diff --git a/batch/apiv1/batchpb/task.pb.go b/batch/apiv1/batchpb/task.pb.go index 2115c51f1ba2..615c54663cff 100644 --- a/batch/apiv1/batchpb/task.pb.go +++ b/batch/apiv1/batchpb/task.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/batch/v1/task.proto package batchpb @@ -418,7 +418,6 @@ type Runnable struct { // The script or container to run. // // Types that are assignable to Executable: - // // *Runnable_Container_ // *Runnable_Script_ // *Runnable_Barrier_ @@ -1002,7 +1001,6 @@ type Runnable_Script struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Command: - // // *Runnable_Script_Path // *Runnable_Script_Text Command isRunnable_Script_Command `protobuf_oneof:"command"` diff --git a/batch/apiv1/batchpb/volume.pb.go b/batch/apiv1/batchpb/volume.pb.go index c9d5b7ac6c57..61426601566d 100644 --- a/batch/apiv1/batchpb/volume.pb.go +++ b/batch/apiv1/batchpb/volume.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/batch/v1/volume.proto package batchpb @@ -44,7 +44,6 @@ type Volume struct { // The source for the volume. // // Types that are assignable to Source: - // // *Volume_Nfs // *Volume_Gcs // *Volume_DeviceName diff --git a/batch/apiv1/doc.go b/batch/apiv1/doc.go index 29f812859561..ca7afec9833c 100644 --- a/batch/apiv1/doc.go +++ b/batch/apiv1/doc.go @@ -82,6 +82,8 @@ package batch // import "cloud.google.com/go/batch/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -170,3 +172,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/batch/apiv1/gapic_metadata.json b/batch/apiv1/gapic_metadata.json index e9c9a7360980..4d1b72fdfaf5 100644 --- a/batch/apiv1/gapic_metadata.json +++ b/batch/apiv1/gapic_metadata.json @@ -86,6 +86,86 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "CreateJob": { + "methods": [ + "CreateJob" + ] + }, + "DeleteJob": { + "methods": [ + "DeleteJob" + ] + }, + "DeleteOperation": { + "methods": [ + "DeleteOperation" + ] + }, + "GetIamPolicy": { + "methods": [ + "GetIamPolicy" + ] + }, + "GetJob": { + "methods": [ + "GetJob" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "GetTask": { + "methods": [ + "GetTask" + ] + }, + "ListJobs": { + "methods": [ + "ListJobs" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "ListTasks": { + "methods": [ + "ListTasks" + ] + }, + "SetIamPolicy": { + "methods": [ + "SetIamPolicy" + ] + }, + "TestIamPermissions": { + "methods": [ + "TestIamPermissions" + ] + } + } } } } diff --git a/beyondcorp/appconnections/apiv1/app_connections_client.go b/beyondcorp/appconnections/apiv1/app_connections_client.go index d74e1ce8095b..cc8f0f9c44e2 100644 --- a/beyondcorp/appconnections/apiv1/app_connections_client.go +++ b/beyondcorp/appconnections/apiv1/app_connections_client.go @@ -17,9 +17,12 @@ package appconnections import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,15 +30,18 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" iampb "google.golang.org/genproto/googleapis/iam/v1" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -92,6 +98,26 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + ListAppConnections: []gax.CallOption{}, + GetAppConnection: []gax.CallOption{}, + CreateAppConnection: []gax.CallOption{}, + UpdateAppConnection: []gax.CallOption{}, + DeleteAppConnection: []gax.CallOption{}, + ResolveAppConnections: []gax.CallOption{}, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + GetIamPolicy: []gax.CallOption{}, + SetIamPolicy: []gax.CallOption{}, + TestIamPermissions: []gax.CallOption{}, + CancelOperation: []gax.CallOption{}, + DeleteOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalClient is an interface that defines the methods available from BeyondCorp API. type internalClient interface { Close() error @@ -395,6 +421,102 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new app connections service rest client. +// +// API Overview: +// +// The beyondcorp.googleapis.com service implements the Google Cloud +// BeyondCorp API. +// +// Data Model: +// +// The AppConnectionsService exposes the following resources: +// +// AppConnections, named as follows: +// projects/{project_id}/locations/{location_id}/appConnections/{app_connection_id}. +// +// The AppConnectionsService service provides methods to manage +// (create/read/update/delete) BeyondCorp AppConnections. +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://beyondcorp.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://beyondcorp.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://beyondcorp.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) ListAppConnections(ctx context.Context, req *appconnectionspb.ListAppConnectionsRequest, opts ...gax.CallOption) *AppConnectionIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -760,136 +882,1221 @@ func (c *gRPCClient) ListOperations(ctx context.Context, req *longrunningpb.List return it } -// CreateAppConnectionOperation manages a long-running operation from CreateAppConnection. -type CreateAppConnectionOperation struct { - lro *longrunning.Operation -} +// ListAppConnections lists AppConnections in a given project and location. +func (c *restClient) ListAppConnections(ctx context.Context, req *appconnectionspb.ListAppConnectionsRequest, opts ...gax.CallOption) *AppConnectionIterator { + it := &AppConnectionIterator{} + req = proto.Clone(req).(*appconnectionspb.ListAppConnectionsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*appconnectionspb.AppConnection, string, error) { + resp := &appconnectionspb.ListAppConnectionsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/appConnections", req.GetParent()) -// CreateAppConnectionOperation returns a new CreateAppConnectionOperation from a given name. -// The name must be that of a previously created CreateAppConnectionOperation, possibly from a different process. -func (c *gRPCClient) CreateAppConnectionOperation(name string) *CreateAppConnectionOperation { - return &CreateAppConnectionOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *CreateAppConnectionOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*appconnectionspb.AppConnection, error) { - var resp appconnectionspb.AppConnection - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { - return nil, err + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetAppConnections(), resp.GetNextPageToken(), nil } - return &resp, nil -} -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *CreateAppConnectionOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*appconnectionspb.AppConnection, error) { - var resp appconnectionspb.AppConnection - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { - return nil, err - } - if !op.Done() { - return nil, 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 } - return &resp, nil + + it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it } -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *CreateAppConnectionOperation) Metadata() (*appconnectionspb.AppConnectionOperationMetadata, error) { - var meta appconnectionspb.AppConnectionOperationMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { +// GetAppConnection gets details of a single AppConnection. +func (c *restClient) GetAppConnection(ctx context.Context, req *appconnectionspb.GetAppConnectionRequest, opts ...gax.CallOption) (*appconnectionspb.AppConnection, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - return &meta, nil -} + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) -// Done reports whether the long-running operation has completed. -func (op *CreateAppConnectionOperation) Done() bool { - return op.lro.Done() -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") -// 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 *CreateAppConnectionOperation) Name() string { - return op.lro.Name() -} + baseUrl.RawQuery = params.Encode() -// DeleteAppConnectionOperation manages a long-running operation from DeleteAppConnection. -type DeleteAppConnectionOperation struct { - lro *longrunning.Operation -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) -// DeleteAppConnectionOperation returns a new DeleteAppConnectionOperation from a given name. -// The name must be that of a previously created DeleteAppConnectionOperation, possibly from a different process. -func (c *gRPCClient) DeleteAppConnectionOperation(name string) *DeleteAppConnectionOperation { - return &DeleteAppConnectionOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetAppConnection[0:len((*c.CallOptions).GetAppConnection):len((*c.CallOptions).GetAppConnection)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &appconnectionspb.AppConnection{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *DeleteAppConnectionOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { - return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) -} + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *DeleteAppConnectionOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { - return op.lro.Poll(ctx, nil, opts...) + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil } -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *DeleteAppConnectionOperation) Metadata() (*appconnectionspb.AppConnectionOperationMetadata, error) { - var meta appconnectionspb.AppConnectionOperationMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { +// CreateAppConnection creates a new AppConnection in a given project and location. +func (c *restClient) CreateAppConnection(ctx context.Context, req *appconnectionspb.CreateAppConnectionRequest, opts ...gax.CallOption) (*CreateAppConnectionOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetAppConnection() + jsonReq, err := m.Marshal(body) + if err != nil { return nil, err } - return &meta, nil -} -// Done reports whether the long-running operation has completed. -func (op *DeleteAppConnectionOperation) Done() bool { - return op.lro.Done() -} + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/appConnections", req.GetParent()) -// 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 *DeleteAppConnectionOperation) Name() string { - return op.lro.Name() -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetAppConnectionId() != "" { + params.Add("appConnectionId", fmt.Sprintf("%v", req.GetAppConnectionId())) + } + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } -// UpdateAppConnectionOperation manages a long-running operation from UpdateAppConnection. -type UpdateAppConnectionOperation struct { - lro *longrunning.Operation + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateAppConnectionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateAppConnection updates the parameters of a single AppConnection. +func (c *restClient) UpdateAppConnection(ctx context.Context, req *appconnectionspb.UpdateAppConnectionRequest, opts ...gax.CallOption) (*UpdateAppConnectionOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetAppConnection() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetAppConnection().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetAllowMissing() { + params.Add("allowMissing", fmt.Sprintf("%v", req.GetAllowMissing())) + } + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "app_connection.name", url.QueryEscape(req.GetAppConnection().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateAppConnectionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteAppConnection deletes a single AppConnection. +func (c *restClient) DeleteAppConnection(ctx context.Context, req *appconnectionspb.DeleteAppConnectionRequest, opts ...gax.CallOption) (*DeleteAppConnectionOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteAppConnectionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ResolveAppConnections resolves AppConnections details for a given AppConnector. +// An internal method called by a connector to find AppConnections to connect +// to. +func (c *restClient) ResolveAppConnections(ctx context.Context, req *appconnectionspb.ResolveAppConnectionsRequest, opts ...gax.CallOption) *ResolveAppConnectionsResponse_AppConnectionDetailsIterator { + it := &ResolveAppConnectionsResponse_AppConnectionDetailsIterator{} + req = proto.Clone(req).(*appconnectionspb.ResolveAppConnectionsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*appconnectionspb.ResolveAppConnectionsResponse_AppConnectionDetails, string, error) { + resp := &appconnectionspb.ResolveAppConnectionsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/appConnections:resolve", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("appConnectorId", fmt.Sprintf("%v", req.GetAppConnectorId())) + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetAppConnectionDetails(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetLocation gets information about a location. +func (c *restClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *restClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetIamPolicy gets the access control policy for a resource. Returns an empty policy +// if the resource exists and does not have a policy set. +func (c *restClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:getIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetOptions().GetRequestedPolicyVersion() != 0 { + params.Add("options.requestedPolicyVersion", fmt.Sprintf("%v", req.GetOptions().GetRequestedPolicyVersion())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SetIamPolicy sets the access control policy on the specified resource. Replaces +// any existing policy. +// +// Can return NOT_FOUND, INVALID_ARGUMENT, and PERMISSION_DENIED +// errors. +func (c *restClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:setIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// TestIamPermissions returns permissions that a caller has on the specified resource. If the +// resource does not exist, this will return an empty set of +// permissions, not a NOT_FOUND error. +// +// Note: This operation is designed to be used for building +// permission-aware UIs and command-line tools, not for authorization +// checking. This operation may “fail open” without warning. +func (c *restClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:testIamPermissions", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.TestIamPermissionsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *restClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// DeleteOperation is a utility method from google.longrunning.Operations. +func (c *restClient) DeleteOperation(ctx context.Context, req *longrunningpb.DeleteOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *restClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *restClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CreateAppConnectionOperation manages a long-running operation from CreateAppConnection. +type CreateAppConnectionOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateAppConnectionOperation returns a new CreateAppConnectionOperation from a given name. +// The name must be that of a previously created CreateAppConnectionOperation, possibly from a different process. +func (c *gRPCClient) CreateAppConnectionOperation(name string) *CreateAppConnectionOperation { + return &CreateAppConnectionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateAppConnectionOperation returns a new CreateAppConnectionOperation from a given name. +// The name must be that of a previously created CreateAppConnectionOperation, possibly from a different process. +func (c *restClient) CreateAppConnectionOperation(name string) *CreateAppConnectionOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateAppConnectionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CreateAppConnectionOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*appconnectionspb.AppConnection, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp appconnectionspb.AppConnection + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *CreateAppConnectionOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*appconnectionspb.AppConnection, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp appconnectionspb.AppConnection + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *CreateAppConnectionOperation) Metadata() (*appconnectionspb.AppConnectionOperationMetadata, error) { + var meta appconnectionspb.AppConnectionOperationMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *CreateAppConnectionOperation) Done() bool { + return op.lro.Done() +} + +// 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 *CreateAppConnectionOperation) Name() string { + return op.lro.Name() +} + +// DeleteAppConnectionOperation manages a long-running operation from DeleteAppConnection. +type DeleteAppConnectionOperation struct { + lro *longrunning.Operation + pollPath string +} + +// DeleteAppConnectionOperation returns a new DeleteAppConnectionOperation from a given name. +// The name must be that of a previously created DeleteAppConnectionOperation, possibly from a different process. +func (c *gRPCClient) DeleteAppConnectionOperation(name string) *DeleteAppConnectionOperation { + return &DeleteAppConnectionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// DeleteAppConnectionOperation returns a new DeleteAppConnectionOperation from a given name. +// The name must be that of a previously created DeleteAppConnectionOperation, possibly from a different process. +func (c *restClient) DeleteAppConnectionOperation(name string) *DeleteAppConnectionOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteAppConnectionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *DeleteAppConnectionOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *DeleteAppConnectionOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + return op.lro.Poll(ctx, nil, opts...) +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *DeleteAppConnectionOperation) Metadata() (*appconnectionspb.AppConnectionOperationMetadata, error) { + var meta appconnectionspb.AppConnectionOperationMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *DeleteAppConnectionOperation) Done() bool { + return op.lro.Done() +} + +// 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 *DeleteAppConnectionOperation) Name() string { + return op.lro.Name() +} + +// UpdateAppConnectionOperation manages a long-running operation from UpdateAppConnection. +type UpdateAppConnectionOperation struct { + lro *longrunning.Operation + pollPath string } // UpdateAppConnectionOperation returns a new UpdateAppConnectionOperation from a given name. @@ -900,10 +2107,21 @@ func (c *gRPCClient) UpdateAppConnectionOperation(name string) *UpdateAppConnect } } +// UpdateAppConnectionOperation returns a new UpdateAppConnectionOperation from a given name. +// The name must be that of a previously created UpdateAppConnectionOperation, possibly from a different process. +func (c *restClient) UpdateAppConnectionOperation(name string) *UpdateAppConnectionOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateAppConnectionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateAppConnectionOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*appconnectionspb.AppConnection, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp appconnectionspb.AppConnection if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -921,6 +2139,7 @@ func (op *UpdateAppConnectionOperation) Wait(ctx context.Context, opts ...gax.Ca // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateAppConnectionOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*appconnectionspb.AppConnection, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp appconnectionspb.AppConnection if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/beyondcorp/appconnections/apiv1/app_connections_client_example_test.go b/beyondcorp/appconnections/apiv1/app_connections_client_example_test.go index 2e8fc59a3a4b..aa8a0481c9ac 100644 --- a/beyondcorp/appconnections/apiv1/app_connections_client_example_test.go +++ b/beyondcorp/appconnections/apiv1/app_connections_client_example_test.go @@ -44,6 +44,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := appconnections.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_ListAppConnections() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/beyondcorp/appconnections/apiv1/appconnectionspb/app_connections_service.pb.go b/beyondcorp/appconnections/apiv1/appconnectionspb/app_connections_service.pb.go index a0ce2a499844..18d708731e50 100644 --- a/beyondcorp/appconnections/apiv1/appconnectionspb/app_connections_service.pb.go +++ b/beyondcorp/appconnections/apiv1/appconnectionspb/app_connections_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/beyondcorp/appconnections/v1/app_connections_service.proto package appconnectionspb @@ -432,9 +432,9 @@ type CreateAppConnectionRequest struct { // form: `projects/{project_id}/locations/{location_id}` Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // Optional. User-settable AppConnection resource ID. - // - Must start with a letter. - // - Must contain between 4-63 characters from `/[a-z][0-9]-/`. - // - Must end with a number or a letter. + // * Must start with a letter. + // * Must contain between 4-63 characters from `/[a-z][0-9]-/`. + // * Must end with a number or a letter. AppConnectionId string `protobuf:"bytes,2,opt,name=app_connection_id,json=appConnectionId,proto3" json:"app_connection_id,omitempty"` // Required. A BeyondCorp AppConnection resource. AppConnection *AppConnection `protobuf:"bytes,3,opt,name=app_connection,json=appConnection,proto3" json:"app_connection,omitempty"` diff --git a/beyondcorp/appconnections/apiv1/doc.go b/beyondcorp/appconnections/apiv1/doc.go index ff95100cb2ef..4a9e73ee4b78 100644 --- a/beyondcorp/appconnections/apiv1/doc.go +++ b/beyondcorp/appconnections/apiv1/doc.go @@ -91,6 +91,8 @@ package appconnections // import "cloud.google.com/go/beyondcorp/appconnections/ import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -179,3 +181,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/beyondcorp/appconnections/apiv1/gapic_metadata.json b/beyondcorp/appconnections/apiv1/gapic_metadata.json index 6c61c4de13ed..011a49b9c6f5 100644 --- a/beyondcorp/appconnections/apiv1/gapic_metadata.json +++ b/beyondcorp/appconnections/apiv1/gapic_metadata.json @@ -86,6 +86,86 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "CreateAppConnection": { + "methods": [ + "CreateAppConnection" + ] + }, + "DeleteAppConnection": { + "methods": [ + "DeleteAppConnection" + ] + }, + "DeleteOperation": { + "methods": [ + "DeleteOperation" + ] + }, + "GetAppConnection": { + "methods": [ + "GetAppConnection" + ] + }, + "GetIamPolicy": { + "methods": [ + "GetIamPolicy" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ListAppConnections": { + "methods": [ + "ListAppConnections" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "ResolveAppConnections": { + "methods": [ + "ResolveAppConnections" + ] + }, + "SetIamPolicy": { + "methods": [ + "SetIamPolicy" + ] + }, + "TestIamPermissions": { + "methods": [ + "TestIamPermissions" + ] + }, + "UpdateAppConnection": { + "methods": [ + "UpdateAppConnection" + ] + } + } } } } diff --git a/beyondcorp/appconnectors/apiv1/app_connectors_client.go b/beyondcorp/appconnectors/apiv1/app_connectors_client.go index 7a29a1c5fa8f..9d808364f366 100644 --- a/beyondcorp/appconnectors/apiv1/app_connectors_client.go +++ b/beyondcorp/appconnectors/apiv1/app_connectors_client.go @@ -17,9 +17,12 @@ package appconnectors import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,15 +30,18 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" iampb "google.golang.org/genproto/googleapis/iam/v1" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -92,6 +98,26 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + ListAppConnectors: []gax.CallOption{}, + GetAppConnector: []gax.CallOption{}, + CreateAppConnector: []gax.CallOption{}, + UpdateAppConnector: []gax.CallOption{}, + DeleteAppConnector: []gax.CallOption{}, + ReportStatus: []gax.CallOption{}, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + GetIamPolicy: []gax.CallOption{}, + SetIamPolicy: []gax.CallOption{}, + TestIamPermissions: []gax.CallOption{}, + CancelOperation: []gax.CallOption{}, + DeleteOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalClient is an interface that defines the methods available from BeyondCorp API. type internalClient interface { Close() error @@ -400,6 +426,102 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new app connectors service rest client. +// +// API Overview: +// +// The beyondcorp.googleapis.com service implements the Google Cloud +// BeyondCorp API. +// +// Data Model: +// +// The AppConnectorsService exposes the following resource: +// +// AppConnectors, named as follows: +// projects/{project_id}/locations/{location_id}/appConnectors/{app_connector_id}. +// +// The AppConnectorsService provides methods to manage +// (create/read/update/delete) BeyondCorp AppConnectors. +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://beyondcorp.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://beyondcorp.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://beyondcorp.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) ListAppConnectors(ctx context.Context, req *appconnectorspb.ListAppConnectorsRequest, opts ...gax.CallOption) *AppConnectorIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -739,136 +861,1195 @@ func (c *gRPCClient) ListOperations(ctx context.Context, req *longrunningpb.List return it } -// CreateAppConnectorOperation manages a long-running operation from CreateAppConnector. -type CreateAppConnectorOperation struct { - lro *longrunning.Operation -} +// ListAppConnectors lists AppConnectors in a given project and location. +func (c *restClient) ListAppConnectors(ctx context.Context, req *appconnectorspb.ListAppConnectorsRequest, opts ...gax.CallOption) *AppConnectorIterator { + it := &AppConnectorIterator{} + req = proto.Clone(req).(*appconnectorspb.ListAppConnectorsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*appconnectorspb.AppConnector, string, error) { + resp := &appconnectorspb.ListAppConnectorsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/appConnectors", req.GetParent()) -// CreateAppConnectorOperation returns a new CreateAppConnectorOperation from a given name. -// The name must be that of a previously created CreateAppConnectorOperation, possibly from a different process. -func (c *gRPCClient) CreateAppConnectorOperation(name string) *CreateAppConnectorOperation { - return &CreateAppConnectorOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *CreateAppConnectorOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*appconnectorspb.AppConnector, error) { - var resp appconnectorspb.AppConnector - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { - return nil, err + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetAppConnectors(), resp.GetNextPageToken(), nil } - return &resp, nil -} -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *CreateAppConnectorOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*appconnectorspb.AppConnector, error) { - var resp appconnectorspb.AppConnector - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { - return nil, err - } - if !op.Done() { - return nil, 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 } - return &resp, nil + + it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it } -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *CreateAppConnectorOperation) Metadata() (*appconnectorspb.AppConnectorOperationMetadata, error) { - var meta appconnectorspb.AppConnectorOperationMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { +// GetAppConnector gets details of a single AppConnector. +func (c *restClient) GetAppConnector(ctx context.Context, req *appconnectorspb.GetAppConnectorRequest, opts ...gax.CallOption) (*appconnectorspb.AppConnector, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - return &meta, nil -} + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) -// Done reports whether the long-running operation has completed. -func (op *CreateAppConnectorOperation) Done() bool { - return op.lro.Done() -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") -// 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 *CreateAppConnectorOperation) Name() string { - return op.lro.Name() -} + baseUrl.RawQuery = params.Encode() -// DeleteAppConnectorOperation manages a long-running operation from DeleteAppConnector. -type DeleteAppConnectorOperation struct { - lro *longrunning.Operation -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) -// DeleteAppConnectorOperation returns a new DeleteAppConnectorOperation from a given name. -// The name must be that of a previously created DeleteAppConnectorOperation, possibly from a different process. -func (c *gRPCClient) DeleteAppConnectorOperation(name string) *DeleteAppConnectorOperation { - return &DeleteAppConnectorOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetAppConnector[0:len((*c.CallOptions).GetAppConnector):len((*c.CallOptions).GetAppConnector)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &appconnectorspb.AppConnector{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *DeleteAppConnectorOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { - return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) -} + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *DeleteAppConnectorOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { - return op.lro.Poll(ctx, nil, opts...) + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil } -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *DeleteAppConnectorOperation) Metadata() (*appconnectorspb.AppConnectorOperationMetadata, error) { - var meta appconnectorspb.AppConnectorOperationMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { +// CreateAppConnector creates a new AppConnector in a given project and location. +func (c *restClient) CreateAppConnector(ctx context.Context, req *appconnectorspb.CreateAppConnectorRequest, opts ...gax.CallOption) (*CreateAppConnectorOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetAppConnector() + jsonReq, err := m.Marshal(body) + if err != nil { return nil, err } - return &meta, nil -} -// Done reports whether the long-running operation has completed. -func (op *DeleteAppConnectorOperation) Done() bool { - return op.lro.Done() -} + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/appConnectors", req.GetParent()) -// 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 *DeleteAppConnectorOperation) Name() string { - return op.lro.Name() -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetAppConnectorId() != "" { + params.Add("appConnectorId", fmt.Sprintf("%v", req.GetAppConnectorId())) + } + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } -// ReportStatusOperation manages a long-running operation from ReportStatus. -type ReportStatusOperation struct { - lro *longrunning.Operation + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateAppConnectorOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateAppConnector updates the parameters of a single AppConnector. +func (c *restClient) UpdateAppConnector(ctx context.Context, req *appconnectorspb.UpdateAppConnectorRequest, opts ...gax.CallOption) (*UpdateAppConnectorOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetAppConnector() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetAppConnector().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "app_connector.name", url.QueryEscape(req.GetAppConnector().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateAppConnectorOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteAppConnector deletes a single AppConnector. +func (c *restClient) DeleteAppConnector(ctx context.Context, req *appconnectorspb.DeleteAppConnectorRequest, opts ...gax.CallOption) (*DeleteAppConnectorOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteAppConnectorOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ReportStatus report status for a given connector. +func (c *restClient) ReportStatus(ctx context.Context, req *appconnectorspb.ReportStatusRequest, opts ...gax.CallOption) (*ReportStatusOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:reportStatus", req.GetAppConnector()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "app_connector", url.QueryEscape(req.GetAppConnector()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &ReportStatusOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetLocation gets information about a location. +func (c *restClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *restClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetIamPolicy gets the access control policy for a resource. Returns an empty policy +// if the resource exists and does not have a policy set. +func (c *restClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:getIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetOptions().GetRequestedPolicyVersion() != 0 { + params.Add("options.requestedPolicyVersion", fmt.Sprintf("%v", req.GetOptions().GetRequestedPolicyVersion())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SetIamPolicy sets the access control policy on the specified resource. Replaces +// any existing policy. +// +// Can return NOT_FOUND, INVALID_ARGUMENT, and PERMISSION_DENIED +// errors. +func (c *restClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:setIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// TestIamPermissions returns permissions that a caller has on the specified resource. If the +// resource does not exist, this will return an empty set of +// permissions, not a NOT_FOUND error. +// +// Note: This operation is designed to be used for building +// permission-aware UIs and command-line tools, not for authorization +// checking. This operation may “fail open” without warning. +func (c *restClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:testIamPermissions", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.TestIamPermissionsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *restClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// DeleteOperation is a utility method from google.longrunning.Operations. +func (c *restClient) DeleteOperation(ctx context.Context, req *longrunningpb.DeleteOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *restClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *restClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CreateAppConnectorOperation manages a long-running operation from CreateAppConnector. +type CreateAppConnectorOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateAppConnectorOperation returns a new CreateAppConnectorOperation from a given name. +// The name must be that of a previously created CreateAppConnectorOperation, possibly from a different process. +func (c *gRPCClient) CreateAppConnectorOperation(name string) *CreateAppConnectorOperation { + return &CreateAppConnectorOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateAppConnectorOperation returns a new CreateAppConnectorOperation from a given name. +// The name must be that of a previously created CreateAppConnectorOperation, possibly from a different process. +func (c *restClient) CreateAppConnectorOperation(name string) *CreateAppConnectorOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateAppConnectorOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CreateAppConnectorOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*appconnectorspb.AppConnector, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp appconnectorspb.AppConnector + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *CreateAppConnectorOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*appconnectorspb.AppConnector, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp appconnectorspb.AppConnector + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *CreateAppConnectorOperation) Metadata() (*appconnectorspb.AppConnectorOperationMetadata, error) { + var meta appconnectorspb.AppConnectorOperationMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *CreateAppConnectorOperation) Done() bool { + return op.lro.Done() +} + +// 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 *CreateAppConnectorOperation) Name() string { + return op.lro.Name() +} + +// DeleteAppConnectorOperation manages a long-running operation from DeleteAppConnector. +type DeleteAppConnectorOperation struct { + lro *longrunning.Operation + pollPath string +} + +// DeleteAppConnectorOperation returns a new DeleteAppConnectorOperation from a given name. +// The name must be that of a previously created DeleteAppConnectorOperation, possibly from a different process. +func (c *gRPCClient) DeleteAppConnectorOperation(name string) *DeleteAppConnectorOperation { + return &DeleteAppConnectorOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// DeleteAppConnectorOperation returns a new DeleteAppConnectorOperation from a given name. +// The name must be that of a previously created DeleteAppConnectorOperation, possibly from a different process. +func (c *restClient) DeleteAppConnectorOperation(name string) *DeleteAppConnectorOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteAppConnectorOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *DeleteAppConnectorOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *DeleteAppConnectorOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + return op.lro.Poll(ctx, nil, opts...) +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *DeleteAppConnectorOperation) Metadata() (*appconnectorspb.AppConnectorOperationMetadata, error) { + var meta appconnectorspb.AppConnectorOperationMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *DeleteAppConnectorOperation) Done() bool { + return op.lro.Done() +} + +// 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 *DeleteAppConnectorOperation) Name() string { + return op.lro.Name() +} + +// ReportStatusOperation manages a long-running operation from ReportStatus. +type ReportStatusOperation struct { + lro *longrunning.Operation + pollPath string } // ReportStatusOperation returns a new ReportStatusOperation from a given name. @@ -879,10 +2060,21 @@ func (c *gRPCClient) ReportStatusOperation(name string) *ReportStatusOperation { } } +// ReportStatusOperation returns a new ReportStatusOperation from a given name. +// The name must be that of a previously created ReportStatusOperation, possibly from a different process. +func (c *restClient) ReportStatusOperation(name string) *ReportStatusOperation { + override := fmt.Sprintf("/v1/%s", name) + return &ReportStatusOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *ReportStatusOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*appconnectorspb.AppConnector, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp appconnectorspb.AppConnector if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -900,6 +2092,7 @@ func (op *ReportStatusOperation) Wait(ctx context.Context, opts ...gax.CallOptio // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *ReportStatusOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*appconnectorspb.AppConnector, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp appconnectorspb.AppConnector if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -937,7 +2130,8 @@ func (op *ReportStatusOperation) Name() string { // UpdateAppConnectorOperation manages a long-running operation from UpdateAppConnector. type UpdateAppConnectorOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateAppConnectorOperation returns a new UpdateAppConnectorOperation from a given name. @@ -948,10 +2142,21 @@ func (c *gRPCClient) UpdateAppConnectorOperation(name string) *UpdateAppConnecto } } +// UpdateAppConnectorOperation returns a new UpdateAppConnectorOperation from a given name. +// The name must be that of a previously created UpdateAppConnectorOperation, possibly from a different process. +func (c *restClient) UpdateAppConnectorOperation(name string) *UpdateAppConnectorOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateAppConnectorOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateAppConnectorOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*appconnectorspb.AppConnector, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp appconnectorspb.AppConnector if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -969,6 +2174,7 @@ func (op *UpdateAppConnectorOperation) Wait(ctx context.Context, opts ...gax.Cal // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateAppConnectorOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*appconnectorspb.AppConnector, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp appconnectorspb.AppConnector if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/beyondcorp/appconnectors/apiv1/app_connectors_client_example_test.go b/beyondcorp/appconnectors/apiv1/app_connectors_client_example_test.go index 78eb443d6be2..1acb4da55da1 100644 --- a/beyondcorp/appconnectors/apiv1/app_connectors_client_example_test.go +++ b/beyondcorp/appconnectors/apiv1/app_connectors_client_example_test.go @@ -44,6 +44,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := appconnectors.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_ListAppConnectors() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/beyondcorp/appconnectors/apiv1/appconnectorspb/app_connector_instance_config.pb.go b/beyondcorp/appconnectors/apiv1/appconnectorspb/app_connector_instance_config.pb.go index 193747de567d..048ff5646d75 100644 --- a/beyondcorp/appconnectors/apiv1/appconnectorspb/app_connector_instance_config.pb.go +++ b/beyondcorp/appconnectors/apiv1/appconnectorspb/app_connector_instance_config.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/beyondcorp/appconnectors/v1/app_connector_instance_config.proto package appconnectorspb @@ -124,7 +124,6 @@ type NotificationConfig struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Config: - // // *NotificationConfig_PubsubNotification Config isNotificationConfig_Config `protobuf_oneof:"config"` } diff --git a/beyondcorp/appconnectors/apiv1/appconnectorspb/app_connectors_service.pb.go b/beyondcorp/appconnectors/apiv1/appconnectorspb/app_connectors_service.pb.go index 31fcc2097ed4..b01720d049ac 100644 --- a/beyondcorp/appconnectors/apiv1/appconnectorspb/app_connectors_service.pb.go +++ b/beyondcorp/appconnectors/apiv1/appconnectorspb/app_connectors_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/beyondcorp/appconnectors/v1/app_connectors_service.proto package appconnectorspb @@ -333,9 +333,9 @@ type CreateAppConnectorRequest struct { Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // Optional. User-settable AppConnector resource ID. // - // - Must start with a letter. - // - Must contain between 4-63 characters from `/[a-z][0-9]-/`. - // - Must end with a number or a letter. + // * Must start with a letter. + // * Must contain between 4-63 characters from `/[a-z][0-9]-/`. + // * Must end with a number or a letter. AppConnectorId string `protobuf:"bytes,2,opt,name=app_connector_id,json=appConnectorId,proto3" json:"app_connector_id,omitempty"` // Required. A BeyondCorp AppConnector resource. AppConnector *AppConnector `protobuf:"bytes,3,opt,name=app_connector,json=appConnector,proto3" json:"app_connector,omitempty"` @@ -932,7 +932,6 @@ type AppConnector_PrincipalInfo struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Type: - // // *AppConnector_PrincipalInfo_ServiceAccount_ Type isAppConnector_PrincipalInfo_Type `protobuf_oneof:"type"` } diff --git a/beyondcorp/appconnectors/apiv1/appconnectorspb/resource_info.pb.go b/beyondcorp/appconnectors/apiv1/appconnectorspb/resource_info.pb.go index bba75a2ffbee..a80396117e51 100644 --- a/beyondcorp/appconnectors/apiv1/appconnectorspb/resource_info.pb.go +++ b/beyondcorp/appconnectors/apiv1/appconnectorspb/resource_info.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/beyondcorp/appconnectors/v1/resource_info.proto package appconnectorspb diff --git a/beyondcorp/appconnectors/apiv1/doc.go b/beyondcorp/appconnectors/apiv1/doc.go index 4b3248fa4888..06d703bbc423 100644 --- a/beyondcorp/appconnectors/apiv1/doc.go +++ b/beyondcorp/appconnectors/apiv1/doc.go @@ -91,6 +91,8 @@ package appconnectors // import "cloud.google.com/go/beyondcorp/appconnectors/ap import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -179,3 +181,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/beyondcorp/appconnectors/apiv1/gapic_metadata.json b/beyondcorp/appconnectors/apiv1/gapic_metadata.json index 782b03350947..84b555cdb4d8 100644 --- a/beyondcorp/appconnectors/apiv1/gapic_metadata.json +++ b/beyondcorp/appconnectors/apiv1/gapic_metadata.json @@ -86,6 +86,86 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "CreateAppConnector": { + "methods": [ + "CreateAppConnector" + ] + }, + "DeleteAppConnector": { + "methods": [ + "DeleteAppConnector" + ] + }, + "DeleteOperation": { + "methods": [ + "DeleteOperation" + ] + }, + "GetAppConnector": { + "methods": [ + "GetAppConnector" + ] + }, + "GetIamPolicy": { + "methods": [ + "GetIamPolicy" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ListAppConnectors": { + "methods": [ + "ListAppConnectors" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "ReportStatus": { + "methods": [ + "ReportStatus" + ] + }, + "SetIamPolicy": { + "methods": [ + "SetIamPolicy" + ] + }, + "TestIamPermissions": { + "methods": [ + "TestIamPermissions" + ] + }, + "UpdateAppConnector": { + "methods": [ + "UpdateAppConnector" + ] + } + } } } } diff --git a/beyondcorp/appgateways/apiv1/app_gateways_client.go b/beyondcorp/appgateways/apiv1/app_gateways_client.go index dd3aac8ec585..c02f0a9b44b6 100644 --- a/beyondcorp/appgateways/apiv1/app_gateways_client.go +++ b/beyondcorp/appgateways/apiv1/app_gateways_client.go @@ -17,9 +17,12 @@ package appgateways import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,15 +30,18 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" iampb "google.golang.org/genproto/googleapis/iam/v1" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -88,6 +94,24 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + ListAppGateways: []gax.CallOption{}, + GetAppGateway: []gax.CallOption{}, + CreateAppGateway: []gax.CallOption{}, + DeleteAppGateway: []gax.CallOption{}, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + GetIamPolicy: []gax.CallOption{}, + SetIamPolicy: []gax.CallOption{}, + TestIamPermissions: []gax.CallOption{}, + CancelOperation: []gax.CallOption{}, + DeleteOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalClient is an interface that defines the methods available from BeyondCorp API. type internalClient interface { Close() error @@ -370,6 +394,102 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new app gateways service rest client. +// +// API Overview: +// +// The beyondcorp.googleapis.com service implements the Google Cloud +// BeyondCorp API. +// +// Data Model: +// +// The AppGatewaysService exposes the following resources: +// +// AppGateways, named as follows: +// projects/{project_id}/locations/{location_id}/appGateways/{app_gateway_id}. +// +// The AppGatewaysService service provides methods to manage +// (create/read/update/delete) BeyondCorp AppGateways. +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://beyondcorp.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://beyondcorp.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://beyondcorp.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) ListAppGateways(ctx context.Context, req *appgatewayspb.ListAppGatewaysRequest, opts ...gax.CallOption) *AppGatewayIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -671,85 +791,991 @@ func (c *gRPCClient) ListOperations(ctx context.Context, req *longrunningpb.List return it } -// CreateAppGatewayOperation manages a long-running operation from CreateAppGateway. -type CreateAppGatewayOperation struct { - lro *longrunning.Operation -} +// ListAppGateways lists AppGateways in a given project and location. +func (c *restClient) ListAppGateways(ctx context.Context, req *appgatewayspb.ListAppGatewaysRequest, opts ...gax.CallOption) *AppGatewayIterator { + it := &AppGatewayIterator{} + req = proto.Clone(req).(*appgatewayspb.ListAppGatewaysRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*appgatewayspb.AppGateway, string, error) { + resp := &appgatewayspb.ListAppGatewaysResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/appGateways", req.GetParent()) -// CreateAppGatewayOperation returns a new CreateAppGatewayOperation from a given name. -// The name must be that of a previously created CreateAppGatewayOperation, possibly from a different process. -func (c *gRPCClient) CreateAppGatewayOperation(name string) *CreateAppGatewayOperation { - return &CreateAppGatewayOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetAppGateways(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it } -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *CreateAppGatewayOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*appgatewayspb.AppGateway, error) { - var resp appgatewayspb.AppGateway - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { +// GetAppGateway gets details of a single AppGateway. +func (c *restClient) GetAppGateway(ctx context.Context, req *appgatewayspb.GetAppGatewayRequest, opts ...gax.CallOption) (*appgatewayspb.AppGateway, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - return &resp, nil + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetAppGateway[0:len((*c.CallOptions).GetAppGateway):len((*c.CallOptions).GetAppGateway)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &appgatewayspb.AppGateway{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil } -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *CreateAppGatewayOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*appgatewayspb.AppGateway, error) { - var resp appgatewayspb.AppGateway - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { +// CreateAppGateway creates a new AppGateway in a given project and location. +func (c *restClient) CreateAppGateway(ctx context.Context, req *appgatewayspb.CreateAppGatewayRequest, opts ...gax.CallOption) (*CreateAppGatewayOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetAppGateway() + jsonReq, err := m.Marshal(body) + if err != nil { return nil, err } - if !op.Done() { - return nil, nil + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err } - return &resp, nil + baseUrl.Path += fmt.Sprintf("/v1/%v/appGateways", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetAppGatewayId() != "" { + params.Add("appGatewayId", fmt.Sprintf("%v", req.GetAppGatewayId())) + } + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateAppGatewayOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil } -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *CreateAppGatewayOperation) Metadata() (*appgatewayspb.AppGatewayOperationMetadata, error) { - var meta appgatewayspb.AppGatewayOperationMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { +// DeleteAppGateway deletes a single AppGateway. +func (c *restClient) DeleteAppGateway(ctx context.Context, req *appgatewayspb.DeleteAppGatewayRequest, opts ...gax.CallOption) (*DeleteAppGatewayOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - return &meta, nil -} + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) -// Done reports whether the long-running operation has completed. -func (op *CreateAppGatewayOperation) Done() bool { - return op.lro.Done() -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } -// 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 *CreateAppGatewayOperation) Name() string { - return op.lro.Name() -} + baseUrl.RawQuery = params.Encode() -// DeleteAppGatewayOperation manages a long-running operation from DeleteAppGateway. -type DeleteAppGatewayOperation struct { - lro *longrunning.Operation -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) -// DeleteAppGatewayOperation returns a new DeleteAppGatewayOperation from a given name. -// The name must be that of a previously created DeleteAppGatewayOperation, possibly from a different process. -func (c *gRPCClient) DeleteAppGatewayOperation(name string) *DeleteAppGatewayOperation { - return &DeleteAppGatewayOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteAppGatewayOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetLocation gets information about a location. +func (c *restClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *restClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetIamPolicy gets the access control policy for a resource. Returns an empty policy +// if the resource exists and does not have a policy set. +func (c *restClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:getIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetOptions().GetRequestedPolicyVersion() != 0 { + params.Add("options.requestedPolicyVersion", fmt.Sprintf("%v", req.GetOptions().GetRequestedPolicyVersion())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SetIamPolicy sets the access control policy on the specified resource. Replaces +// any existing policy. +// +// Can return NOT_FOUND, INVALID_ARGUMENT, and PERMISSION_DENIED +// errors. +func (c *restClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:setIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// TestIamPermissions returns permissions that a caller has on the specified resource. If the +// resource does not exist, this will return an empty set of +// permissions, not a NOT_FOUND error. +// +// Note: This operation is designed to be used for building +// permission-aware UIs and command-line tools, not for authorization +// checking. This operation may “fail open” without warning. +func (c *restClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:testIamPermissions", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.TestIamPermissionsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *restClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// DeleteOperation is a utility method from google.longrunning.Operations. +func (c *restClient) DeleteOperation(ctx context.Context, req *longrunningpb.DeleteOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *restClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *restClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CreateAppGatewayOperation manages a long-running operation from CreateAppGateway. +type CreateAppGatewayOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateAppGatewayOperation returns a new CreateAppGatewayOperation from a given name. +// The name must be that of a previously created CreateAppGatewayOperation, possibly from a different process. +func (c *gRPCClient) CreateAppGatewayOperation(name string) *CreateAppGatewayOperation { + return &CreateAppGatewayOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateAppGatewayOperation returns a new CreateAppGatewayOperation from a given name. +// The name must be that of a previously created CreateAppGatewayOperation, possibly from a different process. +func (c *restClient) CreateAppGatewayOperation(name string) *CreateAppGatewayOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateAppGatewayOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CreateAppGatewayOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*appgatewayspb.AppGateway, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp appgatewayspb.AppGateway + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *CreateAppGatewayOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*appgatewayspb.AppGateway, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp appgatewayspb.AppGateway + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *CreateAppGatewayOperation) Metadata() (*appgatewayspb.AppGatewayOperationMetadata, error) { + var meta appgatewayspb.AppGatewayOperationMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *CreateAppGatewayOperation) Done() bool { + return op.lro.Done() +} + +// 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 *CreateAppGatewayOperation) Name() string { + return op.lro.Name() +} + +// DeleteAppGatewayOperation manages a long-running operation from DeleteAppGateway. +type DeleteAppGatewayOperation struct { + lro *longrunning.Operation + pollPath string +} + +// DeleteAppGatewayOperation returns a new DeleteAppGatewayOperation from a given name. +// The name must be that of a previously created DeleteAppGatewayOperation, possibly from a different process. +func (c *gRPCClient) DeleteAppGatewayOperation(name string) *DeleteAppGatewayOperation { + return &DeleteAppGatewayOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// DeleteAppGatewayOperation returns a new DeleteAppGatewayOperation from a given name. +// The name must be that of a previously created DeleteAppGatewayOperation, possibly from a different process. +func (c *restClient) DeleteAppGatewayOperation(name string) *DeleteAppGatewayOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteAppGatewayOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, } } @@ -757,6 +1783,7 @@ func (c *gRPCClient) DeleteAppGatewayOperation(name string) *DeleteAppGatewayOpe // // See documentation of Poll for error-handling information. func (op *DeleteAppGatewayOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -770,6 +1797,7 @@ func (op *DeleteAppGatewayOperation) Wait(ctx context.Context, opts ...gax.CallO // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteAppGatewayOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } diff --git a/beyondcorp/appgateways/apiv1/app_gateways_client_example_test.go b/beyondcorp/appgateways/apiv1/app_gateways_client_example_test.go index 2790bf6fb92e..a37e1c2c215c 100644 --- a/beyondcorp/appgateways/apiv1/app_gateways_client_example_test.go +++ b/beyondcorp/appgateways/apiv1/app_gateways_client_example_test.go @@ -44,6 +44,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := appgateways.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_ListAppGateways() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/beyondcorp/appgateways/apiv1/appgatewayspb/app_gateways_service.pb.go b/beyondcorp/appgateways/apiv1/appgatewayspb/app_gateways_service.pb.go index 9dc0136ceed8..2df8978dec91 100644 --- a/beyondcorp/appgateways/apiv1/appgatewayspb/app_gateways_service.pb.go +++ b/beyondcorp/appgateways/apiv1/appgatewayspb/app_gateways_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/beyondcorp/appgateways/v1/app_gateways_service.proto package appgatewayspb @@ -431,9 +431,9 @@ type CreateAppGatewayRequest struct { // form: `projects/{project_id}/locations/{location_id}` Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // Optional. User-settable AppGateway resource ID. - // - Must start with a letter. - // - Must contain between 4-63 characters from `/[a-z][0-9]-/`. - // - Must end with a number or a letter. + // * Must start with a letter. + // * Must contain between 4-63 characters from `/[a-z][0-9]-/`. + // * Must end with a number or a letter. AppGatewayId string `protobuf:"bytes,2,opt,name=app_gateway_id,json=appGatewayId,proto3" json:"app_gateway_id,omitempty"` // Required. A BeyondCorp AppGateway resource. AppGateway *AppGateway `protobuf:"bytes,3,opt,name=app_gateway,json=appGateway,proto3" json:"app_gateway,omitempty"` diff --git a/beyondcorp/appgateways/apiv1/doc.go b/beyondcorp/appgateways/apiv1/doc.go index debab1fa729e..95e6266c3de2 100644 --- a/beyondcorp/appgateways/apiv1/doc.go +++ b/beyondcorp/appgateways/apiv1/doc.go @@ -91,6 +91,8 @@ package appgateways // import "cloud.google.com/go/beyondcorp/appgateways/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -179,3 +181,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/beyondcorp/appgateways/apiv1/gapic_metadata.json b/beyondcorp/appgateways/apiv1/gapic_metadata.json index 82c71686b14f..d1629922e987 100644 --- a/beyondcorp/appgateways/apiv1/gapic_metadata.json +++ b/beyondcorp/appgateways/apiv1/gapic_metadata.json @@ -76,6 +76,76 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "CreateAppGateway": { + "methods": [ + "CreateAppGateway" + ] + }, + "DeleteAppGateway": { + "methods": [ + "DeleteAppGateway" + ] + }, + "DeleteOperation": { + "methods": [ + "DeleteOperation" + ] + }, + "GetAppGateway": { + "methods": [ + "GetAppGateway" + ] + }, + "GetIamPolicy": { + "methods": [ + "GetIamPolicy" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ListAppGateways": { + "methods": [ + "ListAppGateways" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "SetIamPolicy": { + "methods": [ + "SetIamPolicy" + ] + }, + "TestIamPermissions": { + "methods": [ + "TestIamPermissions" + ] + } + } } } } diff --git a/beyondcorp/clientconnectorservices/apiv1/client_connector_services_client.go b/beyondcorp/clientconnectorservices/apiv1/client_connector_services_client.go index 7744e5bb4b82..8c39ed4e4649 100644 --- a/beyondcorp/clientconnectorservices/apiv1/client_connector_services_client.go +++ b/beyondcorp/clientconnectorservices/apiv1/client_connector_services_client.go @@ -17,9 +17,12 @@ package clientconnectorservices import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,15 +30,18 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" iampb "google.golang.org/genproto/googleapis/iam/v1" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -90,6 +96,25 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + ListClientConnectorServices: []gax.CallOption{}, + GetClientConnectorService: []gax.CallOption{}, + CreateClientConnectorService: []gax.CallOption{}, + UpdateClientConnectorService: []gax.CallOption{}, + DeleteClientConnectorService: []gax.CallOption{}, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + GetIamPolicy: []gax.CallOption{}, + SetIamPolicy: []gax.CallOption{}, + TestIamPermissions: []gax.CallOption{}, + CancelOperation: []gax.CallOption{}, + DeleteOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalClient is an interface that defines the methods available from BeyondCorp API. type internalClient interface { Close() error @@ -379,6 +404,99 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new client connector services service rest client. +// +// API Overview: +// +// The beyondcorp.googleapis.com service implements the Google Cloud +// BeyondCorp API. +// +// Data Model: +// +// The ClientConnectorServicesService exposes the following resources: +// +// Client Connector Services, named as follows: +// projects/{project_id}/locations/{location_id}/client_connector_services/{client_connector_service_id}. +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://beyondcorp.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://beyondcorp.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://beyondcorp.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) ListClientConnectorServices(ctx context.Context, req *clientconnectorservicespb.ListClientConnectorServicesRequest, opts ...gax.CallOption) *ClientConnectorServiceIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -699,150 +817,1155 @@ func (c *gRPCClient) ListOperations(ctx context.Context, req *longrunningpb.List return it } -// CreateClientConnectorServiceOperation manages a long-running operation from CreateClientConnectorService. -type CreateClientConnectorServiceOperation struct { - lro *longrunning.Operation -} +// ListClientConnectorServices lists ClientConnectorServices in a given project and location. +func (c *restClient) ListClientConnectorServices(ctx context.Context, req *clientconnectorservicespb.ListClientConnectorServicesRequest, opts ...gax.CallOption) *ClientConnectorServiceIterator { + it := &ClientConnectorServiceIterator{} + req = proto.Clone(req).(*clientconnectorservicespb.ListClientConnectorServicesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*clientconnectorservicespb.ClientConnectorService, string, error) { + resp := &clientconnectorservicespb.ListClientConnectorServicesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/clientConnectorServices", req.GetParent()) -// CreateClientConnectorServiceOperation returns a new CreateClientConnectorServiceOperation from a given name. -// The name must be that of a previously created CreateClientConnectorServiceOperation, possibly from a different process. -func (c *gRPCClient) CreateClientConnectorServiceOperation(name string) *CreateClientConnectorServiceOperation { - return &CreateClientConnectorServiceOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *CreateClientConnectorServiceOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*clientconnectorservicespb.ClientConnectorService, error) { - var resp clientconnectorservicespb.ClientConnectorService - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { - return nil, err + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetClientConnectorServices(), resp.GetNextPageToken(), nil } - return &resp, nil -} -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *CreateClientConnectorServiceOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*clientconnectorservicespb.ClientConnectorService, error) { - var resp clientconnectorservicespb.ClientConnectorService - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { - return nil, err - } - if !op.Done() { - return nil, 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 } - return &resp, nil + + it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it } -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *CreateClientConnectorServiceOperation) Metadata() (*clientconnectorservicespb.ClientConnectorServiceOperationMetadata, error) { - var meta clientconnectorservicespb.ClientConnectorServiceOperationMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { +// GetClientConnectorService gets details of a single ClientConnectorService. +func (c *restClient) GetClientConnectorService(ctx context.Context, req *clientconnectorservicespb.GetClientConnectorServiceRequest, opts ...gax.CallOption) (*clientconnectorservicespb.ClientConnectorService, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - return &meta, nil -} + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) -// Done reports whether the long-running operation has completed. -func (op *CreateClientConnectorServiceOperation) Done() bool { - return op.lro.Done() -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") -// 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 *CreateClientConnectorServiceOperation) Name() string { - return op.lro.Name() -} + baseUrl.RawQuery = params.Encode() -// DeleteClientConnectorServiceOperation manages a long-running operation from DeleteClientConnectorService. -type DeleteClientConnectorServiceOperation struct { - lro *longrunning.Operation -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) -// DeleteClientConnectorServiceOperation returns a new DeleteClientConnectorServiceOperation from a given name. -// The name must be that of a previously created DeleteClientConnectorServiceOperation, possibly from a different process. -func (c *gRPCClient) DeleteClientConnectorServiceOperation(name string) *DeleteClientConnectorServiceOperation { - return &DeleteClientConnectorServiceOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetClientConnectorService[0:len((*c.CallOptions).GetClientConnectorService):len((*c.CallOptions).GetClientConnectorService)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &clientconnectorservicespb.ClientConnectorService{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *DeleteClientConnectorServiceOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { - return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) -} + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *DeleteClientConnectorServiceOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { - return op.lro.Poll(ctx, nil, opts...) + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil } -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *DeleteClientConnectorServiceOperation) Metadata() (*clientconnectorservicespb.ClientConnectorServiceOperationMetadata, error) { - var meta clientconnectorservicespb.ClientConnectorServiceOperationMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { +// CreateClientConnectorService creates a new ClientConnectorService in a given project and location. +func (c *restClient) CreateClientConnectorService(ctx context.Context, req *clientconnectorservicespb.CreateClientConnectorServiceRequest, opts ...gax.CallOption) (*CreateClientConnectorServiceOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetClientConnectorService() + jsonReq, err := m.Marshal(body) + if err != nil { return nil, err } - return &meta, nil -} -// Done reports whether the long-running operation has completed. -func (op *DeleteClientConnectorServiceOperation) Done() bool { - return op.lro.Done() -} + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/clientConnectorServices", req.GetParent()) -// 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 *DeleteClientConnectorServiceOperation) Name() string { - return op.lro.Name() -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetClientConnectorServiceId() != "" { + params.Add("clientConnectorServiceId", fmt.Sprintf("%v", req.GetClientConnectorServiceId())) + } + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } -// UpdateClientConnectorServiceOperation manages a long-running operation from UpdateClientConnectorService. -type UpdateClientConnectorServiceOperation struct { - lro *longrunning.Operation -} + baseUrl.RawQuery = params.Encode() -// UpdateClientConnectorServiceOperation returns a new UpdateClientConnectorServiceOperation from a given name. -// The name must be that of a previously created UpdateClientConnectorServiceOperation, possibly from a different process. -func (c *gRPCClient) UpdateClientConnectorServiceOperation(name string) *UpdateClientConnectorServiceOperation { + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateClientConnectorServiceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateClientConnectorService updates the parameters of a single ClientConnectorService. +func (c *restClient) UpdateClientConnectorService(ctx context.Context, req *clientconnectorservicespb.UpdateClientConnectorServiceRequest, opts ...gax.CallOption) (*UpdateClientConnectorServiceOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetClientConnectorService() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetClientConnectorService().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetAllowMissing() { + params.Add("allowMissing", fmt.Sprintf("%v", req.GetAllowMissing())) + } + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "client_connector_service.name", url.QueryEscape(req.GetClientConnectorService().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateClientConnectorServiceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteClientConnectorService deletes a single ClientConnectorService. +func (c *restClient) DeleteClientConnectorService(ctx context.Context, req *clientconnectorservicespb.DeleteClientConnectorServiceRequest, opts ...gax.CallOption) (*DeleteClientConnectorServiceOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteClientConnectorServiceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetLocation gets information about a location. +func (c *restClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *restClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetIamPolicy gets the access control policy for a resource. Returns an empty policy +// if the resource exists and does not have a policy set. +func (c *restClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:getIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetOptions().GetRequestedPolicyVersion() != 0 { + params.Add("options.requestedPolicyVersion", fmt.Sprintf("%v", req.GetOptions().GetRequestedPolicyVersion())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SetIamPolicy sets the access control policy on the specified resource. Replaces +// any existing policy. +// +// Can return NOT_FOUND, INVALID_ARGUMENT, and PERMISSION_DENIED +// errors. +func (c *restClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:setIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// TestIamPermissions returns permissions that a caller has on the specified resource. If the +// resource does not exist, this will return an empty set of +// permissions, not a NOT_FOUND error. +// +// Note: This operation is designed to be used for building +// permission-aware UIs and command-line tools, not for authorization +// checking. This operation may “fail open” without warning. +func (c *restClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:testIamPermissions", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.TestIamPermissionsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *restClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// DeleteOperation is a utility method from google.longrunning.Operations. +func (c *restClient) DeleteOperation(ctx context.Context, req *longrunningpb.DeleteOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *restClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *restClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CreateClientConnectorServiceOperation manages a long-running operation from CreateClientConnectorService. +type CreateClientConnectorServiceOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateClientConnectorServiceOperation returns a new CreateClientConnectorServiceOperation from a given name. +// The name must be that of a previously created CreateClientConnectorServiceOperation, possibly from a different process. +func (c *gRPCClient) CreateClientConnectorServiceOperation(name string) *CreateClientConnectorServiceOperation { + return &CreateClientConnectorServiceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateClientConnectorServiceOperation returns a new CreateClientConnectorServiceOperation from a given name. +// The name must be that of a previously created CreateClientConnectorServiceOperation, possibly from a different process. +func (c *restClient) CreateClientConnectorServiceOperation(name string) *CreateClientConnectorServiceOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateClientConnectorServiceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CreateClientConnectorServiceOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*clientconnectorservicespb.ClientConnectorService, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp clientconnectorservicespb.ClientConnectorService + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *CreateClientConnectorServiceOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*clientconnectorservicespb.ClientConnectorService, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp clientconnectorservicespb.ClientConnectorService + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *CreateClientConnectorServiceOperation) Metadata() (*clientconnectorservicespb.ClientConnectorServiceOperationMetadata, error) { + var meta clientconnectorservicespb.ClientConnectorServiceOperationMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *CreateClientConnectorServiceOperation) Done() bool { + return op.lro.Done() +} + +// 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 *CreateClientConnectorServiceOperation) Name() string { + return op.lro.Name() +} + +// DeleteClientConnectorServiceOperation manages a long-running operation from DeleteClientConnectorService. +type DeleteClientConnectorServiceOperation struct { + lro *longrunning.Operation + pollPath string +} + +// DeleteClientConnectorServiceOperation returns a new DeleteClientConnectorServiceOperation from a given name. +// The name must be that of a previously created DeleteClientConnectorServiceOperation, possibly from a different process. +func (c *gRPCClient) DeleteClientConnectorServiceOperation(name string) *DeleteClientConnectorServiceOperation { + return &DeleteClientConnectorServiceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// DeleteClientConnectorServiceOperation returns a new DeleteClientConnectorServiceOperation from a given name. +// The name must be that of a previously created DeleteClientConnectorServiceOperation, possibly from a different process. +func (c *restClient) DeleteClientConnectorServiceOperation(name string) *DeleteClientConnectorServiceOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteClientConnectorServiceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *DeleteClientConnectorServiceOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *DeleteClientConnectorServiceOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + return op.lro.Poll(ctx, nil, opts...) +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *DeleteClientConnectorServiceOperation) Metadata() (*clientconnectorservicespb.ClientConnectorServiceOperationMetadata, error) { + var meta clientconnectorservicespb.ClientConnectorServiceOperationMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *DeleteClientConnectorServiceOperation) Done() bool { + return op.lro.Done() +} + +// 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 *DeleteClientConnectorServiceOperation) Name() string { + return op.lro.Name() +} + +// UpdateClientConnectorServiceOperation manages a long-running operation from UpdateClientConnectorService. +type UpdateClientConnectorServiceOperation struct { + lro *longrunning.Operation + pollPath string +} + +// UpdateClientConnectorServiceOperation returns a new UpdateClientConnectorServiceOperation from a given name. +// The name must be that of a previously created UpdateClientConnectorServiceOperation, possibly from a different process. +func (c *gRPCClient) UpdateClientConnectorServiceOperation(name string) *UpdateClientConnectorServiceOperation { return &UpdateClientConnectorServiceOperation{ lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } +// UpdateClientConnectorServiceOperation returns a new UpdateClientConnectorServiceOperation from a given name. +// The name must be that of a previously created UpdateClientConnectorServiceOperation, possibly from a different process. +func (c *restClient) UpdateClientConnectorServiceOperation(name string) *UpdateClientConnectorServiceOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateClientConnectorServiceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateClientConnectorServiceOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*clientconnectorservicespb.ClientConnectorService, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp clientconnectorservicespb.ClientConnectorService if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -860,6 +1983,7 @@ func (op *UpdateClientConnectorServiceOperation) Wait(ctx context.Context, opts // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateClientConnectorServiceOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*clientconnectorservicespb.ClientConnectorService, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp clientconnectorservicespb.ClientConnectorService if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/beyondcorp/clientconnectorservices/apiv1/client_connector_services_client_example_test.go b/beyondcorp/clientconnectorservices/apiv1/client_connector_services_client_example_test.go index 3bd50d8f0bae..875f4233cd69 100644 --- a/beyondcorp/clientconnectorservices/apiv1/client_connector_services_client_example_test.go +++ b/beyondcorp/clientconnectorservices/apiv1/client_connector_services_client_example_test.go @@ -44,6 +44,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := clientconnectorservices.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_ListClientConnectorServices() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/beyondcorp/clientconnectorservices/apiv1/clientconnectorservicespb/client_connector_services_service.pb.go b/beyondcorp/clientconnectorservices/apiv1/clientconnectorservicespb/client_connector_services_service.pb.go index 389553576fa0..c420e4072324 100644 --- a/beyondcorp/clientconnectorservices/apiv1/clientconnectorservicespb/client_connector_services_service.pb.go +++ b/beyondcorp/clientconnectorservices/apiv1/clientconnectorservicespb/client_connector_services_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/beyondcorp/clientconnectorservices/v1/client_connector_services_service.proto package clientconnectorservicespb @@ -481,9 +481,9 @@ type CreateClientConnectorServiceRequest struct { // Required. Value for parent. Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // Optional. User-settable client connector service resource ID. - // - Must start with a letter. - // - Must contain between 4-63 characters from `/[a-z][0-9]-/`. - // - Must end with a number or a letter. + // * Must start with a letter. + // * Must contain between 4-63 characters from `/[a-z][0-9]-/`. + // * Must end with a number or a letter. // // A random system generated name will be assigned // if not specified by the user. @@ -875,7 +875,6 @@ type ClientConnectorService_Ingress struct { unknownFields protoimpl.UnknownFields // Types that are assignable to IngressConfig: - // // *ClientConnectorService_Ingress_Config_ IngressConfig isClientConnectorService_Ingress_IngressConfig `protobuf_oneof:"ingress_config"` } @@ -944,7 +943,6 @@ type ClientConnectorService_Egress struct { unknownFields protoimpl.UnknownFields // Types that are assignable to DestinationType: - // // *ClientConnectorService_Egress_PeeredVpc_ DestinationType isClientConnectorService_Egress_DestinationType `protobuf_oneof:"destination_type"` } diff --git a/beyondcorp/clientconnectorservices/apiv1/doc.go b/beyondcorp/clientconnectorservices/apiv1/doc.go index d41bcbe3a3c2..875aec2cdfa3 100644 --- a/beyondcorp/clientconnectorservices/apiv1/doc.go +++ b/beyondcorp/clientconnectorservices/apiv1/doc.go @@ -91,6 +91,8 @@ package clientconnectorservices // import "cloud.google.com/go/beyondcorp/client import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -179,3 +181,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/beyondcorp/clientconnectorservices/apiv1/gapic_metadata.json b/beyondcorp/clientconnectorservices/apiv1/gapic_metadata.json index 0e24b7032096..814b48fc2d6f 100644 --- a/beyondcorp/clientconnectorservices/apiv1/gapic_metadata.json +++ b/beyondcorp/clientconnectorservices/apiv1/gapic_metadata.json @@ -81,6 +81,81 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "CreateClientConnectorService": { + "methods": [ + "CreateClientConnectorService" + ] + }, + "DeleteClientConnectorService": { + "methods": [ + "DeleteClientConnectorService" + ] + }, + "DeleteOperation": { + "methods": [ + "DeleteOperation" + ] + }, + "GetClientConnectorService": { + "methods": [ + "GetClientConnectorService" + ] + }, + "GetIamPolicy": { + "methods": [ + "GetIamPolicy" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ListClientConnectorServices": { + "methods": [ + "ListClientConnectorServices" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "SetIamPolicy": { + "methods": [ + "SetIamPolicy" + ] + }, + "TestIamPermissions": { + "methods": [ + "TestIamPermissions" + ] + }, + "UpdateClientConnectorService": { + "methods": [ + "UpdateClientConnectorService" + ] + } + } } } } diff --git a/beyondcorp/clientgateways/apiv1/client_gateways_client.go b/beyondcorp/clientgateways/apiv1/client_gateways_client.go index ac5e268b231c..7be92961e0b9 100644 --- a/beyondcorp/clientgateways/apiv1/client_gateways_client.go +++ b/beyondcorp/clientgateways/apiv1/client_gateways_client.go @@ -17,9 +17,12 @@ package clientgateways import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,15 +30,18 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" iampb "google.golang.org/genproto/googleapis/iam/v1" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -88,6 +94,24 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + ListClientGateways: []gax.CallOption{}, + GetClientGateway: []gax.CallOption{}, + CreateClientGateway: []gax.CallOption{}, + DeleteClientGateway: []gax.CallOption{}, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + GetIamPolicy: []gax.CallOption{}, + SetIamPolicy: []gax.CallOption{}, + TestIamPermissions: []gax.CallOption{}, + CancelOperation: []gax.CallOption{}, + DeleteOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalClient is an interface that defines the methods available from BeyondCorp API. type internalClient interface { Close() error @@ -364,6 +388,99 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new client gateways service rest client. +// +// API Overview: +// +// The beyondcorp.googleapis.com service implements the Google Cloud +// BeyondCorp API. +// +// Data Model: +// +// The ClientGatewaysService exposes the following resources: +// +// Client Gateways, named as follows: +// projects/{project_id}/locations/{location_id}/clientGateways/{client_gateway_id}. +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://beyondcorp.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://beyondcorp.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://beyondcorp.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) ListClientGateways(ctx context.Context, req *clientgatewayspb.ListClientGatewaysRequest, opts ...gax.CallOption) *ClientGatewayIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -665,85 +782,991 @@ func (c *gRPCClient) ListOperations(ctx context.Context, req *longrunningpb.List return it } -// CreateClientGatewayOperation manages a long-running operation from CreateClientGateway. -type CreateClientGatewayOperation struct { - lro *longrunning.Operation -} +// ListClientGateways lists ClientGateways in a given project and location. +func (c *restClient) ListClientGateways(ctx context.Context, req *clientgatewayspb.ListClientGatewaysRequest, opts ...gax.CallOption) *ClientGatewayIterator { + it := &ClientGatewayIterator{} + req = proto.Clone(req).(*clientgatewayspb.ListClientGatewaysRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*clientgatewayspb.ClientGateway, string, error) { + resp := &clientgatewayspb.ListClientGatewaysResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/clientGateways", req.GetParent()) -// CreateClientGatewayOperation returns a new CreateClientGatewayOperation from a given name. -// The name must be that of a previously created CreateClientGatewayOperation, possibly from a different process. -func (c *gRPCClient) CreateClientGatewayOperation(name string) *CreateClientGatewayOperation { - return &CreateClientGatewayOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetClientGateways(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it } -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *CreateClientGatewayOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*clientgatewayspb.ClientGateway, error) { - var resp clientgatewayspb.ClientGateway - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { +// GetClientGateway gets details of a single ClientGateway. +func (c *restClient) GetClientGateway(ctx context.Context, req *clientgatewayspb.GetClientGatewayRequest, opts ...gax.CallOption) (*clientgatewayspb.ClientGateway, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - return &resp, nil + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetClientGateway[0:len((*c.CallOptions).GetClientGateway):len((*c.CallOptions).GetClientGateway)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &clientgatewayspb.ClientGateway{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil } -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *CreateClientGatewayOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*clientgatewayspb.ClientGateway, error) { - var resp clientgatewayspb.ClientGateway - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { +// CreateClientGateway creates a new ClientGateway in a given project and location. +func (c *restClient) CreateClientGateway(ctx context.Context, req *clientgatewayspb.CreateClientGatewayRequest, opts ...gax.CallOption) (*CreateClientGatewayOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetClientGateway() + jsonReq, err := m.Marshal(body) + if err != nil { return nil, err } - if !op.Done() { - return nil, nil + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err } - return &resp, nil + baseUrl.Path += fmt.Sprintf("/v1/%v/clientGateways", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetClientGatewayId() != "" { + params.Add("clientGatewayId", fmt.Sprintf("%v", req.GetClientGatewayId())) + } + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateClientGatewayOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil } -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *CreateClientGatewayOperation) Metadata() (*clientgatewayspb.ClientGatewayOperationMetadata, error) { - var meta clientgatewayspb.ClientGatewayOperationMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { +// DeleteClientGateway deletes a single ClientGateway. +func (c *restClient) DeleteClientGateway(ctx context.Context, req *clientgatewayspb.DeleteClientGatewayRequest, opts ...gax.CallOption) (*DeleteClientGatewayOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - return &meta, nil -} + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) -// Done reports whether the long-running operation has completed. -func (op *CreateClientGatewayOperation) Done() bool { - return op.lro.Done() -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } -// 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 *CreateClientGatewayOperation) Name() string { - return op.lro.Name() -} + baseUrl.RawQuery = params.Encode() -// DeleteClientGatewayOperation manages a long-running operation from DeleteClientGateway. -type DeleteClientGatewayOperation struct { - lro *longrunning.Operation -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) -// DeleteClientGatewayOperation returns a new DeleteClientGatewayOperation from a given name. -// The name must be that of a previously created DeleteClientGatewayOperation, possibly from a different process. -func (c *gRPCClient) DeleteClientGatewayOperation(name string) *DeleteClientGatewayOperation { - return &DeleteClientGatewayOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteClientGatewayOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetLocation gets information about a location. +func (c *restClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *restClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetIamPolicy gets the access control policy for a resource. Returns an empty policy +// if the resource exists and does not have a policy set. +func (c *restClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:getIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetOptions().GetRequestedPolicyVersion() != 0 { + params.Add("options.requestedPolicyVersion", fmt.Sprintf("%v", req.GetOptions().GetRequestedPolicyVersion())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SetIamPolicy sets the access control policy on the specified resource. Replaces +// any existing policy. +// +// Can return NOT_FOUND, INVALID_ARGUMENT, and PERMISSION_DENIED +// errors. +func (c *restClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:setIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// TestIamPermissions returns permissions that a caller has on the specified resource. If the +// resource does not exist, this will return an empty set of +// permissions, not a NOT_FOUND error. +// +// Note: This operation is designed to be used for building +// permission-aware UIs and command-line tools, not for authorization +// checking. This operation may “fail open” without warning. +func (c *restClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:testIamPermissions", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.TestIamPermissionsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *restClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// DeleteOperation is a utility method from google.longrunning.Operations. +func (c *restClient) DeleteOperation(ctx context.Context, req *longrunningpb.DeleteOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *restClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *restClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CreateClientGatewayOperation manages a long-running operation from CreateClientGateway. +type CreateClientGatewayOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateClientGatewayOperation returns a new CreateClientGatewayOperation from a given name. +// The name must be that of a previously created CreateClientGatewayOperation, possibly from a different process. +func (c *gRPCClient) CreateClientGatewayOperation(name string) *CreateClientGatewayOperation { + return &CreateClientGatewayOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateClientGatewayOperation returns a new CreateClientGatewayOperation from a given name. +// The name must be that of a previously created CreateClientGatewayOperation, possibly from a different process. +func (c *restClient) CreateClientGatewayOperation(name string) *CreateClientGatewayOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateClientGatewayOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CreateClientGatewayOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*clientgatewayspb.ClientGateway, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp clientgatewayspb.ClientGateway + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *CreateClientGatewayOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*clientgatewayspb.ClientGateway, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp clientgatewayspb.ClientGateway + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *CreateClientGatewayOperation) Metadata() (*clientgatewayspb.ClientGatewayOperationMetadata, error) { + var meta clientgatewayspb.ClientGatewayOperationMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *CreateClientGatewayOperation) Done() bool { + return op.lro.Done() +} + +// 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 *CreateClientGatewayOperation) Name() string { + return op.lro.Name() +} + +// DeleteClientGatewayOperation manages a long-running operation from DeleteClientGateway. +type DeleteClientGatewayOperation struct { + lro *longrunning.Operation + pollPath string +} + +// DeleteClientGatewayOperation returns a new DeleteClientGatewayOperation from a given name. +// The name must be that of a previously created DeleteClientGatewayOperation, possibly from a different process. +func (c *gRPCClient) DeleteClientGatewayOperation(name string) *DeleteClientGatewayOperation { + return &DeleteClientGatewayOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// DeleteClientGatewayOperation returns a new DeleteClientGatewayOperation from a given name. +// The name must be that of a previously created DeleteClientGatewayOperation, possibly from a different process. +func (c *restClient) DeleteClientGatewayOperation(name string) *DeleteClientGatewayOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteClientGatewayOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, } } @@ -751,6 +1774,7 @@ func (c *gRPCClient) DeleteClientGatewayOperation(name string) *DeleteClientGate // // See documentation of Poll for error-handling information. func (op *DeleteClientGatewayOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -764,6 +1788,7 @@ func (op *DeleteClientGatewayOperation) Wait(ctx context.Context, opts ...gax.Ca // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteClientGatewayOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } diff --git a/beyondcorp/clientgateways/apiv1/client_gateways_client_example_test.go b/beyondcorp/clientgateways/apiv1/client_gateways_client_example_test.go index 710fc85cc1ed..2f23f99bcdad 100644 --- a/beyondcorp/clientgateways/apiv1/client_gateways_client_example_test.go +++ b/beyondcorp/clientgateways/apiv1/client_gateways_client_example_test.go @@ -44,6 +44,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := clientgateways.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_ListClientGateways() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/beyondcorp/clientgateways/apiv1/clientgatewayspb/client_gateways_service.pb.go b/beyondcorp/clientgateways/apiv1/clientgatewayspb/client_gateways_service.pb.go index a7687858ddb5..24a6dcbba568 100644 --- a/beyondcorp/clientgateways/apiv1/clientgatewayspb/client_gateways_service.pb.go +++ b/beyondcorp/clientgateways/apiv1/clientgatewayspb/client_gateways_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/beyondcorp/clientgateways/v1/client_gateways_service.proto package clientgatewayspb @@ -130,8 +130,7 @@ type ClientGateway struct { Id string `protobuf:"bytes,5,opt,name=id,proto3" json:"id,omitempty"` // Output only. The client connector service name that the client gateway is // associated to. Client Connector Services, named as follows: - // - // `projects/{project_id}/locations/{location_id}/client_connector_services/{client_connector_service_id}`. + // `projects/{project_id}/locations/{location_id}/client_connector_services/{client_connector_service_id}`. ClientConnectorService string `protobuf:"bytes,6,opt,name=client_connector_service,json=clientConnectorService,proto3" json:"client_connector_service,omitempty"` } @@ -420,9 +419,9 @@ type CreateClientGatewayRequest struct { // Required. Value for parent. Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // Optional. User-settable client gateway resource ID. - // - Must start with a letter. - // - Must contain between 4-63 characters from `/[a-z][0-9]-/`. - // - Must end with a number or a letter. + // * Must start with a letter. + // * Must contain between 4-63 characters from `/[a-z][0-9]-/`. + // * Must end with a number or a letter. ClientGatewayId string `protobuf:"bytes,2,opt,name=client_gateway_id,json=clientGatewayId,proto3" json:"client_gateway_id,omitempty"` // Required. The resource being created. ClientGateway *ClientGateway `protobuf:"bytes,3,opt,name=client_gateway,json=clientGateway,proto3" json:"client_gateway,omitempty"` diff --git a/beyondcorp/clientgateways/apiv1/doc.go b/beyondcorp/clientgateways/apiv1/doc.go index 31e370252197..22d562485bfd 100644 --- a/beyondcorp/clientgateways/apiv1/doc.go +++ b/beyondcorp/clientgateways/apiv1/doc.go @@ -91,6 +91,8 @@ package clientgateways // import "cloud.google.com/go/beyondcorp/clientgateways/ import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -179,3 +181,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/beyondcorp/clientgateways/apiv1/gapic_metadata.json b/beyondcorp/clientgateways/apiv1/gapic_metadata.json index 1bc3c7c5c5b9..22c04c607c53 100644 --- a/beyondcorp/clientgateways/apiv1/gapic_metadata.json +++ b/beyondcorp/clientgateways/apiv1/gapic_metadata.json @@ -76,6 +76,76 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "CreateClientGateway": { + "methods": [ + "CreateClientGateway" + ] + }, + "DeleteClientGateway": { + "methods": [ + "DeleteClientGateway" + ] + }, + "DeleteOperation": { + "methods": [ + "DeleteOperation" + ] + }, + "GetClientGateway": { + "methods": [ + "GetClientGateway" + ] + }, + "GetIamPolicy": { + "methods": [ + "GetIamPolicy" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ListClientGateways": { + "methods": [ + "ListClientGateways" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "SetIamPolicy": { + "methods": [ + "SetIamPolicy" + ] + }, + "TestIamPermissions": { + "methods": [ + "TestIamPermissions" + ] + } + } } } } diff --git a/bigquery/analyticshub/apiv1/analyticshubpb/analyticshub.pb.go b/bigquery/analyticshub/apiv1/analyticshubpb/analyticshub.pb.go index 5b1337cf3b4b..cc5f0bf6a420 100644 --- a/bigquery/analyticshub/apiv1/analyticshubpb/analyticshub.pb.go +++ b/bigquery/analyticshub/apiv1/analyticshubpb/analyticshub.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/bigquery/analyticshub/v1/analyticshub.proto package analyticshubpb @@ -595,7 +595,6 @@ type Listing struct { // Listing source. // // Types that are assignable to Source: - // // *Listing_BigqueryDataset Source isListing_Source `protobuf_oneof:"source"` // Output only. The resource name of the listing. @@ -1632,7 +1631,6 @@ type SubscribeListingRequest struct { // Resulting destination of the listing that you subscribed to. // // Types that are assignable to Destination: - // // *SubscribeListingRequest_DestinationDataset Destination isSubscribeListingRequest_Destination `protobuf_oneof:"destination"` // Required. Resource name of the listing that you want to subscribe to. diff --git a/bigquery/connection/apiv1/connection_client.go b/bigquery/connection/apiv1/connection_client.go index 1ea38e1be89a..f479aef87f1c 100644 --- a/bigquery/connection/apiv1/connection_client.go +++ b/bigquery/connection/apiv1/connection_client.go @@ -17,22 +17,28 @@ package connection import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" connectionpb "cloud.google.com/go/bigquery/connection/apiv1/connectionpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" iampb "google.golang.org/genproto/googleapis/iam/v1" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -108,6 +114,49 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + CreateConnection: []gax.CallOption{}, + GetConnection: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + ListConnections: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + UpdateConnection: []gax.CallOption{}, + DeleteConnection: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + GetIamPolicy: []gax.CallOption{}, + SetIamPolicy: []gax.CallOption{}, + TestIamPermissions: []gax.CallOption{}, + } +} + // internalClient is an interface that defines the methods available from BigQuery Connection API. type internalClient interface { Close() error @@ -291,6 +340,74 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new connection service rest client. +// +// Manages external data source connections and credentials. +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://bigqueryconnection.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://bigqueryconnection.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://bigqueryconnection.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) CreateConnection(ctx context.Context, req *connectionpb.CreateConnectionRequest, opts ...gax.CallOption) (*connectionpb.Connection, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) @@ -486,6 +603,534 @@ func (c *gRPCClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamP return resp, nil } +// CreateConnection creates a new connection. +func (c *restClient) CreateConnection(ctx context.Context, req *connectionpb.CreateConnectionRequest, opts ...gax.CallOption) (*connectionpb.Connection, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetConnection() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/connections", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetConnectionId() != "" { + params.Add("connectionId", fmt.Sprintf("%v", req.GetConnectionId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateConnection[0:len((*c.CallOptions).CreateConnection):len((*c.CallOptions).CreateConnection)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &connectionpb.Connection{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetConnection returns specified connection. +func (c *restClient) GetConnection(ctx context.Context, req *connectionpb.GetConnectionRequest, opts ...gax.CallOption) (*connectionpb.Connection, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetConnection[0:len((*c.CallOptions).GetConnection):len((*c.CallOptions).GetConnection)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &connectionpb.Connection{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListConnections returns a list of connections in the given project. +func (c *restClient) ListConnections(ctx context.Context, req *connectionpb.ListConnectionsRequest, opts ...gax.CallOption) *ConnectionIterator { + it := &ConnectionIterator{} + req = proto.Clone(req).(*connectionpb.ListConnectionsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*connectionpb.Connection, string, error) { + resp := &connectionpb.ListConnectionsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/connections", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetConnections(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// UpdateConnection updates the specified connection. For security reasons, also resets +// credential if connection properties are in the update field mask. +func (c *restClient) UpdateConnection(ctx context.Context, req *connectionpb.UpdateConnectionRequest, opts ...gax.CallOption) (*connectionpb.Connection, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetConnection() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateConnection[0:len((*c.CallOptions).UpdateConnection):len((*c.CallOptions).UpdateConnection)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &connectionpb.Connection{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteConnection deletes connection and associated credential. +func (c *restClient) DeleteConnection(ctx context.Context, req *connectionpb.DeleteConnectionRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetIamPolicy gets the access control policy for a resource. +// Returns an empty policy if the resource exists and does not have a policy +// set. +func (c *restClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:getIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SetIamPolicy sets the access control policy on the specified resource. Replaces any +// existing policy. +// +// Can return NOT_FOUND, INVALID_ARGUMENT, and PERMISSION_DENIED errors. +func (c *restClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:setIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// TestIamPermissions returns permissions that a caller has on the specified resource. +// If the resource does not exist, this will return an empty set of +// permissions, not a NOT_FOUND error. +// +// Note: This operation is designed to be used for building permission-aware +// UIs and command-line tools, not for authorization checking. This operation +// may “fail open” without warning. +func (c *restClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:testIamPermissions", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.TestIamPermissionsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + // ConnectionIterator manages a stream of *connectionpb.Connection. type ConnectionIterator struct { items []*connectionpb.Connection diff --git a/bigquery/connection/apiv1/connection_client_example_test.go b/bigquery/connection/apiv1/connection_client_example_test.go index ef16b181d4cf..465833f9b206 100644 --- a/bigquery/connection/apiv1/connection_client_example_test.go +++ b/bigquery/connection/apiv1/connection_client_example_test.go @@ -42,6 +42,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := connection.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_CreateConnection() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/bigquery/connection/apiv1/connectionpb/connection.pb.go b/bigquery/connection/apiv1/connectionpb/connection.pb.go index 9f765ec677bb..b0bc013bd964 100644 --- a/bigquery/connection/apiv1/connectionpb/connection.pb.go +++ b/bigquery/connection/apiv1/connectionpb/connection.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/bigquery/connection/v1/connection.proto package connectionpb @@ -475,7 +475,6 @@ type Connection struct { // Properties specific to the underlying data source. // // Types that are assignable to Properties: - // // *Connection_CloudSql // *Connection_Aws // *Connection_Azure @@ -859,7 +858,6 @@ type AwsProperties struct { // Authentication method chosen at connection creation. // // Types that are assignable to AuthenticationMethod: - // // *AwsProperties_CrossAccountRole // *AwsProperties_AccessRole AuthenticationMethod isAwsProperties_AuthenticationMethod `protobuf_oneof:"authentication_method"` @@ -1197,8 +1195,7 @@ type CloudResourceProperties struct { // desired resources in GCP. // // The account ID is in the form of: - // - // @gcp-sa-bigquery-cloudresource.iam.gserviceaccount.com + // @gcp-sa-bigquery-cloudresource.iam.gserviceaccount.com ServiceAccountId string `protobuf:"bytes,1,opt,name=service_account_id,json=serviceAccountId,proto3" json:"service_account_id,omitempty"` } diff --git a/bigquery/connection/apiv1/doc.go b/bigquery/connection/apiv1/doc.go index 6b55b7307bbf..346483af4095 100644 --- a/bigquery/connection/apiv1/doc.go +++ b/bigquery/connection/apiv1/doc.go @@ -80,6 +80,8 @@ package connection // import "cloud.google.com/go/bigquery/connection/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -169,3 +171,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/bigquery/connection/apiv1/gapic_metadata.json b/bigquery/connection/apiv1/gapic_metadata.json index c073c217bfb1..42fcd7f1f1d7 100644 --- a/bigquery/connection/apiv1/gapic_metadata.json +++ b/bigquery/connection/apiv1/gapic_metadata.json @@ -51,6 +51,51 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "CreateConnection": { + "methods": [ + "CreateConnection" + ] + }, + "DeleteConnection": { + "methods": [ + "DeleteConnection" + ] + }, + "GetConnection": { + "methods": [ + "GetConnection" + ] + }, + "GetIamPolicy": { + "methods": [ + "GetIamPolicy" + ] + }, + "ListConnections": { + "methods": [ + "ListConnections" + ] + }, + "SetIamPolicy": { + "methods": [ + "SetIamPolicy" + ] + }, + "TestIamPermissions": { + "methods": [ + "TestIamPermissions" + ] + }, + "UpdateConnection": { + "methods": [ + "UpdateConnection" + ] + } + } } } } diff --git a/bigquery/connection/apiv1beta1/connection_client.go b/bigquery/connection/apiv1beta1/connection_client.go index 08cc6c5ed444..aac5870ac058 100644 --- a/bigquery/connection/apiv1beta1/connection_client.go +++ b/bigquery/connection/apiv1beta1/connection_client.go @@ -621,6 +621,7 @@ func (c *restClient) CreateConnection(ctx context.Context, req *connectionpb.Cre baseUrl.Path += fmt.Sprintf("/v1beta1/%v/connections", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetConnectionId() != "" { params.Add("connectionId", fmt.Sprintf("%v", req.GetConnectionId())) } @@ -680,6 +681,11 @@ func (c *restClient) GetConnection(ctx context.Context, req *connectionpb.GetCon } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -734,6 +740,7 @@ func (c *restClient) ListConnections(ctx context.Context, req *connectionpb.List baseUrl.Path += fmt.Sprintf("/v1beta1/%v/connections", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetMaxResults() != nil { maxResults, err := protojson.Marshal(req.GetMaxResults()) if err != nil { @@ -809,6 +816,7 @@ func (c *restClient) UpdateConnection(ctx context.Context, req *connectionpb.Upd baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -879,6 +887,11 @@ func (c *restClient) UpdateConnectionCredential(ctx context.Context, req *connec } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -914,6 +927,11 @@ func (c *restClient) DeleteConnection(ctx context.Context, req *connectionpb.Del } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -957,6 +975,11 @@ func (c *restClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRe } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:getIamPolicy", req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) @@ -1019,6 +1042,11 @@ func (c *restClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRe } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:setIamPolicy", req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) @@ -1084,6 +1112,11 @@ func (c *restClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamP } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:testIamPermissions", req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) diff --git a/bigquery/connection/apiv1beta1/connectionpb/connection.pb.go b/bigquery/connection/apiv1beta1/connectionpb/connection.pb.go index 75ca9739e2cd..c1246430bed6 100644 --- a/bigquery/connection/apiv1beta1/connectionpb/connection.pb.go +++ b/bigquery/connection/apiv1beta1/connectionpb/connection.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/bigquery/connection/v1beta1/connection.proto package connectionpb @@ -535,7 +535,6 @@ type Connection struct { // Properties specific to the underlying data source. // // Types that are assignable to Properties: - // // *Connection_CloudSql Properties isConnection_Properties `protobuf_oneof:"properties"` // Output only. The creation timestamp of the connection. @@ -654,7 +653,6 @@ type ConnectionCredential struct { // Credential specific to the underlying data source. // // Types that are assignable to Credential: - // // *ConnectionCredential_CloudSql Credential isConnectionCredential_Credential `protobuf_oneof:"credential"` } diff --git a/bigquery/dataexchange/apiv1beta1/dataexchangepb/dataexchange.pb.go b/bigquery/dataexchange/apiv1beta1/dataexchangepb/dataexchange.pb.go index 04d804aa1099..282dbeba4d50 100644 --- a/bigquery/dataexchange/apiv1beta1/dataexchangepb/dataexchange.pb.go +++ b/bigquery/dataexchange/apiv1beta1/dataexchangepb/dataexchange.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/bigquery/dataexchange/v1beta1/dataexchange.proto package dataexchangepb @@ -595,7 +595,6 @@ type Listing struct { // Listing source. // // Types that are assignable to Source: - // // *Listing_BigqueryDataset Source isListing_Source `protobuf_oneof:"source"` // Output only. The resource name of the listing. @@ -1632,7 +1631,6 @@ type SubscribeListingRequest struct { // Resulting destination of the listing that you subscribed to. // // Types that are assignable to Destination: - // // *SubscribeListingRequest_DestinationDataset Destination isSubscribeListingRequest_Destination `protobuf_oneof:"destination"` // Required. Resource name of the listing that you want to subscribe to. diff --git a/bigquery/datapolicies/apiv1beta1/datapoliciespb/datapolicy.pb.go b/bigquery/datapolicies/apiv1beta1/datapoliciespb/datapolicy.pb.go index ebb0ee858052..de8b25248a54 100644 --- a/bigquery/datapolicies/apiv1beta1/datapoliciespb/datapolicy.pb.go +++ b/bigquery/datapolicies/apiv1beta1/datapoliciespb/datapolicy.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/bigquery/datapolicies/v1beta1/datapolicy.proto package datapoliciespb @@ -113,7 +113,7 @@ const ( // The default masking values for each type listed as below: // // * STRING: "" - // * BYTES: b” + // * BYTES: b'' // * INTEGER: 0 // * FLOAT: 0.0 // * NUMERIC: 0 @@ -538,13 +538,11 @@ type DataPolicy struct { // Label that is bound to this data policy. // // Types that are assignable to MatchingLabel: - // // *DataPolicy_PolicyTag MatchingLabel isDataPolicy_MatchingLabel `protobuf_oneof:"matching_label"` // The policy that is bound to this data policy. // // Types that are assignable to Policy: - // // *DataPolicy_DataMaskingPolicy Policy isDataPolicy_Policy `protobuf_oneof:"policy"` // Output only. Resource name of this data policy, in the format of @@ -671,7 +669,6 @@ type DataMaskingPolicy struct { // A masking expression to bind to the data masking rule. // // Types that are assignable to MaskingExpression: - // // *DataMaskingPolicy_PredefinedExpression_ MaskingExpression isDataMaskingPolicy_MaskingExpression `protobuf_oneof:"masking_expression"` } diff --git a/bigquery/datatransfer/apiv1/data_transfer_client.go b/bigquery/datatransfer/apiv1/data_transfer_client.go index 735b073371cb..af5a82bc34c6 100644 --- a/bigquery/datatransfer/apiv1/data_transfer_client.go +++ b/bigquery/datatransfer/apiv1/data_transfer_client.go @@ -17,21 +17,27 @@ package datatransfer import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" datatransferpb "cloud.google.com/go/bigquery/datatransfer/apiv1/datatransferpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -198,6 +204,126 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + GetDataSource: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + ListDataSources: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + CreateTransferConfig: []gax.CallOption{}, + UpdateTransferConfig: []gax.CallOption{}, + DeleteTransferConfig: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + GetTransferConfig: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + ListTransferConfigs: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + ScheduleTransferRuns: []gax.CallOption{}, + StartManualTransferRuns: []gax.CallOption{}, + GetTransferRun: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + DeleteTransferRun: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + ListTransferRuns: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + ListTransferLogs: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + CheckValidCreds: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + EnrollDataSources: []gax.CallOption{}, + } +} + // internalClient is an interface that defines the methods available from BigQuery Data Transfer API. type internalClient interface { Close() error @@ -431,6 +557,74 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new data transfer service rest client. +// +// This API allows users to manage their data transfers into BigQuery. +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://bigquerydatatransfer.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://bigquerydatatransfer.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://bigquerydatatransfer.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) GetDataSource(ctx context.Context, req *datatransferpb.GetDataSourceRequest, opts ...gax.CallOption) (*datatransferpb.DataSource, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 20000*time.Millisecond) @@ -831,6 +1025,1043 @@ func (c *gRPCClient) EnrollDataSources(ctx context.Context, req *datatransferpb. return err } +// GetDataSource retrieves a supported data source and returns its settings. +func (c *restClient) GetDataSource(ctx context.Context, req *datatransferpb.GetDataSourceRequest, opts ...gax.CallOption) (*datatransferpb.DataSource, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetDataSource[0:len((*c.CallOptions).GetDataSource):len((*c.CallOptions).GetDataSource)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &datatransferpb.DataSource{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListDataSources lists supported data sources and returns their settings. +func (c *restClient) ListDataSources(ctx context.Context, req *datatransferpb.ListDataSourcesRequest, opts ...gax.CallOption) *DataSourceIterator { + it := &DataSourceIterator{} + req = proto.Clone(req).(*datatransferpb.ListDataSourcesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*datatransferpb.DataSource, string, error) { + resp := &datatransferpb.ListDataSourcesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/dataSources", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetDataSources(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CreateTransferConfig creates a new data transfer configuration. +func (c *restClient) CreateTransferConfig(ctx context.Context, req *datatransferpb.CreateTransferConfigRequest, opts ...gax.CallOption) (*datatransferpb.TransferConfig, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetTransferConfig() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/transferConfigs", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetAuthorizationCode() != "" { + params.Add("authorizationCode", fmt.Sprintf("%v", req.GetAuthorizationCode())) + } + if req.GetServiceAccountName() != "" { + params.Add("serviceAccountName", fmt.Sprintf("%v", req.GetServiceAccountName())) + } + if req.GetVersionInfo() != "" { + params.Add("versionInfo", fmt.Sprintf("%v", req.GetVersionInfo())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateTransferConfig[0:len((*c.CallOptions).CreateTransferConfig):len((*c.CallOptions).CreateTransferConfig)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &datatransferpb.TransferConfig{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateTransferConfig updates a data transfer configuration. +// All fields must be set, even if they are not updated. +func (c *restClient) UpdateTransferConfig(ctx context.Context, req *datatransferpb.UpdateTransferConfigRequest, opts ...gax.CallOption) (*datatransferpb.TransferConfig, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetTransferConfig() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetTransferConfig().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetAuthorizationCode() != "" { + params.Add("authorizationCode", fmt.Sprintf("%v", req.GetAuthorizationCode())) + } + if req.GetServiceAccountName() != "" { + params.Add("serviceAccountName", fmt.Sprintf("%v", req.GetServiceAccountName())) + } + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + if req.GetVersionInfo() != "" { + params.Add("versionInfo", fmt.Sprintf("%v", req.GetVersionInfo())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "transfer_config.name", url.QueryEscape(req.GetTransferConfig().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateTransferConfig[0:len((*c.CallOptions).UpdateTransferConfig):len((*c.CallOptions).UpdateTransferConfig)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &datatransferpb.TransferConfig{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteTransferConfig deletes a data transfer configuration, including any associated transfer +// runs and logs. +func (c *restClient) DeleteTransferConfig(ctx context.Context, req *datatransferpb.DeleteTransferConfigRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetTransferConfig returns information about a data transfer config. +func (c *restClient) GetTransferConfig(ctx context.Context, req *datatransferpb.GetTransferConfigRequest, opts ...gax.CallOption) (*datatransferpb.TransferConfig, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetTransferConfig[0:len((*c.CallOptions).GetTransferConfig):len((*c.CallOptions).GetTransferConfig)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &datatransferpb.TransferConfig{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListTransferConfigs returns information about all transfer configs owned by a project in the +// specified location. +func (c *restClient) ListTransferConfigs(ctx context.Context, req *datatransferpb.ListTransferConfigsRequest, opts ...gax.CallOption) *TransferConfigIterator { + it := &TransferConfigIterator{} + req = proto.Clone(req).(*datatransferpb.ListTransferConfigsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*datatransferpb.TransferConfig, string, error) { + resp := &datatransferpb.ListTransferConfigsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/transferConfigs", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if items := req.GetDataSourceIds(); len(items) > 0 { + for _, item := range items { + params.Add("dataSourceIds", fmt.Sprintf("%v", item)) + } + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetTransferConfigs(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// ScheduleTransferRuns creates transfer runs for a time range [start_time, end_time]. +// For each date - or whatever granularity the data source supports - in the +// range, one transfer run is created. +// Note that runs are created per UTC time in the time range. +// DEPRECATED: use StartManualTransferRuns instead. +// +// Deprecated: ScheduleTransferRuns may be removed in a future version. +func (c *restClient) ScheduleTransferRuns(ctx context.Context, req *datatransferpb.ScheduleTransferRunsRequest, opts ...gax.CallOption) (*datatransferpb.ScheduleTransferRunsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:scheduleRuns", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).ScheduleTransferRuns[0:len((*c.CallOptions).ScheduleTransferRuns):len((*c.CallOptions).ScheduleTransferRuns)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &datatransferpb.ScheduleTransferRunsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// StartManualTransferRuns start manual transfer runs to be executed now with schedule_time equal to +// current time. The transfer runs can be created for a time range where the +// run_time is between start_time (inclusive) and end_time (exclusive), or for +// a specific run_time. +func (c *restClient) StartManualTransferRuns(ctx context.Context, req *datatransferpb.StartManualTransferRunsRequest, opts ...gax.CallOption) (*datatransferpb.StartManualTransferRunsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:startManualRuns", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).StartManualTransferRuns[0:len((*c.CallOptions).StartManualTransferRuns):len((*c.CallOptions).StartManualTransferRuns)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &datatransferpb.StartManualTransferRunsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetTransferRun returns information about the particular transfer run. +func (c *restClient) GetTransferRun(ctx context.Context, req *datatransferpb.GetTransferRunRequest, opts ...gax.CallOption) (*datatransferpb.TransferRun, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetTransferRun[0:len((*c.CallOptions).GetTransferRun):len((*c.CallOptions).GetTransferRun)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &datatransferpb.TransferRun{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteTransferRun deletes the specified transfer run. +func (c *restClient) DeleteTransferRun(ctx context.Context, req *datatransferpb.DeleteTransferRunRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// ListTransferRuns returns information about running and completed transfer runs. +func (c *restClient) ListTransferRuns(ctx context.Context, req *datatransferpb.ListTransferRunsRequest, opts ...gax.CallOption) *TransferRunIterator { + it := &TransferRunIterator{} + req = proto.Clone(req).(*datatransferpb.ListTransferRunsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*datatransferpb.TransferRun, string, error) { + resp := &datatransferpb.ListTransferRunsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/runs", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + if req.GetRunAttempt() != 0 { + params.Add("runAttempt", fmt.Sprintf("%v", req.GetRunAttempt())) + } + if items := req.GetStates(); len(items) > 0 { + for _, item := range items { + params.Add("states", fmt.Sprintf("%v", item)) + } + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetTransferRuns(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// ListTransferLogs returns log messages for the transfer run. +func (c *restClient) ListTransferLogs(ctx context.Context, req *datatransferpb.ListTransferLogsRequest, opts ...gax.CallOption) *TransferMessageIterator { + it := &TransferMessageIterator{} + req = proto.Clone(req).(*datatransferpb.ListTransferLogsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*datatransferpb.TransferMessage, string, error) { + resp := &datatransferpb.ListTransferLogsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/transferLogs", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if items := req.GetMessageTypes(); len(items) > 0 { + for _, item := range items { + params.Add("messageTypes", fmt.Sprintf("%v", item)) + } + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetTransferMessages(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CheckValidCreds returns true if valid credentials exist for the given data source and +// requesting user. +func (c *restClient) CheckValidCreds(ctx context.Context, req *datatransferpb.CheckValidCredsRequest, opts ...gax.CallOption) (*datatransferpb.CheckValidCredsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:checkValidCreds", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CheckValidCreds[0:len((*c.CallOptions).CheckValidCreds):len((*c.CallOptions).CheckValidCreds)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &datatransferpb.CheckValidCredsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// EnrollDataSources enroll data sources in a user project. This allows users to create transfer +// configurations for these data sources. They will also appear in the +// ListDataSources RPC and as such, will appear in the +// BigQuery UI (at https://console.cloud.google.com/bigquery), and the documents +// can be found in the public guide for +// BigQuery Web UI (at https://cloud.google.com/bigquery/bigquery-web-ui) and +// Data Transfer +// Service (at https://cloud.google.com/bigquery/docs/working-with-transfers). +func (c *restClient) EnrollDataSources(ctx context.Context, req *datatransferpb.EnrollDataSourcesRequest, opts ...gax.CallOption) error { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:enrollDataSources", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + // DataSourceIterator manages a stream of *datatransferpb.DataSource. type DataSourceIterator struct { items []*datatransferpb.DataSource diff --git a/bigquery/datatransfer/apiv1/data_transfer_client_example_test.go b/bigquery/datatransfer/apiv1/data_transfer_client_example_test.go index 9095907ef964..03415751a1d7 100644 --- a/bigquery/datatransfer/apiv1/data_transfer_client_example_test.go +++ b/bigquery/datatransfer/apiv1/data_transfer_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := datatransfer.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_GetDataSource() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/bigquery/datatransfer/apiv1/datatransferpb/datatransfer.pb.go b/bigquery/datatransfer/apiv1/datatransferpb/datatransfer.pb.go index f382790e0577..89eef6e8a495 100644 --- a/bigquery/datatransfer/apiv1/datatransferpb/datatransfer.pb.go +++ b/bigquery/datatransfer/apiv1/datatransferpb/datatransfer.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/bigquery/datatransfer/v1/datatransfer.proto package datatransferpb @@ -2004,7 +2004,6 @@ type StartManualTransferRunsRequest struct { // run_time. // // Types that are assignable to Time: - // // *StartManualTransferRunsRequest_RequestedTimeRange // *StartManualTransferRunsRequest_RequestedRunTime Time isStartManualTransferRunsRequest_Time `protobuf_oneof:"time"` diff --git a/bigquery/datatransfer/apiv1/datatransferpb/transfer.pb.go b/bigquery/datatransfer/apiv1/datatransferpb/transfer.pb.go index 8cb18b672411..3d21eb556770 100644 --- a/bigquery/datatransfer/apiv1/datatransferpb/transfer.pb.go +++ b/bigquery/datatransfer/apiv1/datatransferpb/transfer.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/bigquery/datatransfer/v1/transfer.proto package datatransferpb @@ -415,7 +415,6 @@ type TransferConfig struct { // The desination of the transfer config. // // Types that are assignable to Destination: - // // *TransferConfig_DestinationDatasetId Destination isTransferConfig_Destination `protobuf_oneof:"destination"` // User specified display name for the data transfer. @@ -684,7 +683,6 @@ type TransferRun struct { // Data transfer destination. // // Types that are assignable to Destination: - // // *TransferRun_DestinationDatasetId Destination isTransferRun_Destination `protobuf_oneof:"destination"` // Output only. Data source id. diff --git a/bigquery/datatransfer/apiv1/doc.go b/bigquery/datatransfer/apiv1/doc.go index 998883ea14d9..e1f694d9e26b 100644 --- a/bigquery/datatransfer/apiv1/doc.go +++ b/bigquery/datatransfer/apiv1/doc.go @@ -81,6 +81,8 @@ package datatransfer // import "cloud.google.com/go/bigquery/datatransfer/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -169,3 +171,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/bigquery/datatransfer/apiv1/gapic_metadata.json b/bigquery/datatransfer/apiv1/gapic_metadata.json index 9d71e9cc2e32..78fcdc0b7138 100644 --- a/bigquery/datatransfer/apiv1/gapic_metadata.json +++ b/bigquery/datatransfer/apiv1/gapic_metadata.json @@ -86,6 +86,86 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "CheckValidCreds": { + "methods": [ + "CheckValidCreds" + ] + }, + "CreateTransferConfig": { + "methods": [ + "CreateTransferConfig" + ] + }, + "DeleteTransferConfig": { + "methods": [ + "DeleteTransferConfig" + ] + }, + "DeleteTransferRun": { + "methods": [ + "DeleteTransferRun" + ] + }, + "EnrollDataSources": { + "methods": [ + "EnrollDataSources" + ] + }, + "GetDataSource": { + "methods": [ + "GetDataSource" + ] + }, + "GetTransferConfig": { + "methods": [ + "GetTransferConfig" + ] + }, + "GetTransferRun": { + "methods": [ + "GetTransferRun" + ] + }, + "ListDataSources": { + "methods": [ + "ListDataSources" + ] + }, + "ListTransferConfigs": { + "methods": [ + "ListTransferConfigs" + ] + }, + "ListTransferLogs": { + "methods": [ + "ListTransferLogs" + ] + }, + "ListTransferRuns": { + "methods": [ + "ListTransferRuns" + ] + }, + "ScheduleTransferRuns": { + "methods": [ + "ScheduleTransferRuns" + ] + }, + "StartManualTransferRuns": { + "methods": [ + "StartManualTransferRuns" + ] + }, + "UpdateTransferConfig": { + "methods": [ + "UpdateTransferConfig" + ] + } + } } } } diff --git a/bigquery/migration/apiv2/doc.go b/bigquery/migration/apiv2/doc.go index db3f52bb279b..bbfa7a1f53ca 100644 --- a/bigquery/migration/apiv2/doc.go +++ b/bigquery/migration/apiv2/doc.go @@ -83,6 +83,8 @@ package migration // import "cloud.google.com/go/bigquery/migration/apiv2" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -171,3 +173,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/bigquery/migration/apiv2/gapic_metadata.json b/bigquery/migration/apiv2/gapic_metadata.json index 5d3658ff9fd1..15aa003d9c37 100644 --- a/bigquery/migration/apiv2/gapic_metadata.json +++ b/bigquery/migration/apiv2/gapic_metadata.json @@ -46,6 +46,46 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "CreateMigrationWorkflow": { + "methods": [ + "CreateMigrationWorkflow" + ] + }, + "DeleteMigrationWorkflow": { + "methods": [ + "DeleteMigrationWorkflow" + ] + }, + "GetMigrationSubtask": { + "methods": [ + "GetMigrationSubtask" + ] + }, + "GetMigrationWorkflow": { + "methods": [ + "GetMigrationWorkflow" + ] + }, + "ListMigrationSubtasks": { + "methods": [ + "ListMigrationSubtasks" + ] + }, + "ListMigrationWorkflows": { + "methods": [ + "ListMigrationWorkflows" + ] + }, + "StartMigrationWorkflow": { + "methods": [ + "StartMigrationWorkflow" + ] + } + } } } } diff --git a/bigquery/migration/apiv2/migration_client.go b/bigquery/migration/apiv2/migration_client.go index 09ab9bbba54a..606ac0504fbe 100644 --- a/bigquery/migration/apiv2/migration_client.go +++ b/bigquery/migration/apiv2/migration_client.go @@ -17,21 +17,27 @@ package migration import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" migrationpb "cloud.google.com/go/bigquery/migration/apiv2/migrationpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -102,6 +108,45 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + CreateMigrationWorkflow: []gax.CallOption{}, + GetMigrationWorkflow: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListMigrationWorkflows: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeleteMigrationWorkflow: []gax.CallOption{}, + StartMigrationWorkflow: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetMigrationSubtask: []gax.CallOption{}, + ListMigrationSubtasks: []gax.CallOption{}, + } +} + // internalClient is an interface that defines the methods available from BigQuery Migration API. type internalClient interface { Close() error @@ -270,6 +315,74 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new migration service rest client. +// +// Service to handle EDW migrations. +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://bigquerymigration.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://bigquerymigration.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://bigquerymigration.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) CreateMigrationWorkflow(ctx context.Context, req *migrationpb.CreateMigrationWorkflowRequest, opts ...gax.CallOption) (*migrationpb.MigrationWorkflow, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) @@ -457,6 +570,464 @@ func (c *gRPCClient) ListMigrationSubtasks(ctx context.Context, req *migrationpb return it } +// CreateMigrationWorkflow creates a migration workflow. +func (c *restClient) CreateMigrationWorkflow(ctx context.Context, req *migrationpb.CreateMigrationWorkflowRequest, opts ...gax.CallOption) (*migrationpb.MigrationWorkflow, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetMigrationWorkflow() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/workflows", req.GetParent()) + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateMigrationWorkflow[0:len((*c.CallOptions).CreateMigrationWorkflow):len((*c.CallOptions).CreateMigrationWorkflow)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &migrationpb.MigrationWorkflow{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetMigrationWorkflow gets a previously created migration workflow. +func (c *restClient) GetMigrationWorkflow(ctx context.Context, req *migrationpb.GetMigrationWorkflowRequest, opts ...gax.CallOption) (*migrationpb.MigrationWorkflow, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + if req.GetReadMask() != nil { + readMask, err := protojson.Marshal(req.GetReadMask()) + if err != nil { + return nil, err + } + params.Add("readMask", string(readMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetMigrationWorkflow[0:len((*c.CallOptions).GetMigrationWorkflow):len((*c.CallOptions).GetMigrationWorkflow)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &migrationpb.MigrationWorkflow{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListMigrationWorkflows lists previously created migration workflow. +func (c *restClient) ListMigrationWorkflows(ctx context.Context, req *migrationpb.ListMigrationWorkflowsRequest, opts ...gax.CallOption) *MigrationWorkflowIterator { + it := &MigrationWorkflowIterator{} + req = proto.Clone(req).(*migrationpb.ListMigrationWorkflowsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*migrationpb.MigrationWorkflow, string, error) { + resp := &migrationpb.ListMigrationWorkflowsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/workflows", req.GetParent()) + + params := url.Values{} + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + if req.GetReadMask() != nil { + readMask, err := protojson.Marshal(req.GetReadMask()) + if err != nil { + return nil, "", err + } + params.Add("readMask", string(readMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetMigrationWorkflows(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// DeleteMigrationWorkflow deletes a migration workflow by name. +func (c *restClient) DeleteMigrationWorkflow(ctx context.Context, req *migrationpb.DeleteMigrationWorkflowRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// StartMigrationWorkflow starts a previously created migration workflow. I.e., the state transitions +// from DRAFT to RUNNING. This is a no-op if the state is already RUNNING. +// An error will be signaled if the state is anything other than DRAFT or +// RUNNING. +func (c *restClient) StartMigrationWorkflow(ctx context.Context, req *migrationpb.StartMigrationWorkflowRequest, opts ...gax.CallOption) error { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:start", req.GetName()) + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetMigrationSubtask gets a previously created migration subtask. +func (c *restClient) GetMigrationSubtask(ctx context.Context, req *migrationpb.GetMigrationSubtaskRequest, opts ...gax.CallOption) (*migrationpb.MigrationSubtask, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + if req.GetReadMask() != nil { + readMask, err := protojson.Marshal(req.GetReadMask()) + if err != nil { + return nil, err + } + params.Add("readMask", string(readMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetMigrationSubtask[0:len((*c.CallOptions).GetMigrationSubtask):len((*c.CallOptions).GetMigrationSubtask)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &migrationpb.MigrationSubtask{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListMigrationSubtasks lists previously created migration subtasks. +func (c *restClient) ListMigrationSubtasks(ctx context.Context, req *migrationpb.ListMigrationSubtasksRequest, opts ...gax.CallOption) *MigrationSubtaskIterator { + it := &MigrationSubtaskIterator{} + req = proto.Clone(req).(*migrationpb.ListMigrationSubtasksRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*migrationpb.MigrationSubtask, string, error) { + resp := &migrationpb.ListMigrationSubtasksResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/subtasks", req.GetParent()) + + params := url.Values{} + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + if req.GetReadMask() != nil { + readMask, err := protojson.Marshal(req.GetReadMask()) + if err != nil { + return nil, "", err + } + params.Add("readMask", string(readMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetMigrationSubtasks(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + // MigrationSubtaskIterator manages a stream of *migrationpb.MigrationSubtask. type MigrationSubtaskIterator struct { items []*migrationpb.MigrationSubtask diff --git a/bigquery/migration/apiv2/migration_client_example_test.go b/bigquery/migration/apiv2/migration_client_example_test.go index 1960943a7cb3..42ab9f94dbc3 100644 --- a/bigquery/migration/apiv2/migration_client_example_test.go +++ b/bigquery/migration/apiv2/migration_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := migration.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_CreateMigrationWorkflow() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/bigquery/migration/apiv2/migrationpb/migration_entities.pb.go b/bigquery/migration/apiv2/migrationpb/migration_entities.pb.go index 776b784dccd3..8868fcf70578 100644 --- a/bigquery/migration/apiv2/migrationpb/migration_entities.pb.go +++ b/bigquery/migration/apiv2/migrationpb/migration_entities.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/bigquery/migration/v2/migration_entities.proto package migrationpb @@ -350,7 +350,6 @@ type MigrationTask struct { // The details of the task. // // Types that are assignable to TaskDetails: - // // *MigrationTask_TranslationConfigDetails TaskDetails isMigrationTask_TaskDetails `protobuf_oneof:"task_details"` // Output only. Immutable. The unique identifier for the migration task. The diff --git a/bigquery/migration/apiv2/migrationpb/migration_error_details.pb.go b/bigquery/migration/apiv2/migrationpb/migration_error_details.pb.go index c938951c5e85..836d189bc4de 100644 --- a/bigquery/migration/apiv2/migrationpb/migration_error_details.pb.go +++ b/bigquery/migration/apiv2/migrationpb/migration_error_details.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/bigquery/migration/v2/migration_error_details.proto package migrationpb diff --git a/bigquery/migration/apiv2/migrationpb/migration_metrics.pb.go b/bigquery/migration/apiv2/migrationpb/migration_metrics.pb.go index d04c1e279004..0b129f4f4855 100644 --- a/bigquery/migration/apiv2/migrationpb/migration_metrics.pb.go +++ b/bigquery/migration/apiv2/migrationpb/migration_metrics.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/bigquery/migration/v2/migration_metrics.proto package migrationpb @@ -112,14 +112,14 @@ func (x *TimeSeries) GetValueType() metric.MetricDescriptor_ValueType { if x != nil { return x.ValueType } - return metric.MetricDescriptor_VALUE_TYPE_UNSPECIFIED + return metric.MetricDescriptor_ValueType(0) } func (x *TimeSeries) GetMetricKind() metric.MetricDescriptor_MetricKind { if x != nil { return x.MetricKind } - return metric.MetricDescriptor_METRIC_KIND_UNSPECIFIED + return metric.MetricDescriptor_MetricKind(0) } func (x *TimeSeries) GetPoints() []*Point { @@ -266,7 +266,6 @@ type TypedValue struct { // The typed value field. // // Types that are assignable to Value: - // // *TypedValue_BoolValue // *TypedValue_Int64Value // *TypedValue_DoubleValue diff --git a/bigquery/migration/apiv2/migrationpb/migration_service.pb.go b/bigquery/migration/apiv2/migrationpb/migration_service.pb.go index e4b286e5eb90..ceebb52ca46c 100644 --- a/bigquery/migration/apiv2/migrationpb/migration_service.pb.go +++ b/bigquery/migration/apiv2/migrationpb/migration_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/bigquery/migration/v2/migration_service.proto package migrationpb diff --git a/bigquery/migration/apiv2/migrationpb/translation_config.pb.go b/bigquery/migration/apiv2/migrationpb/translation_config.pb.go index 3b31d73105b1..808391182897 100644 --- a/bigquery/migration/apiv2/migrationpb/translation_config.pb.go +++ b/bigquery/migration/apiv2/migrationpb/translation_config.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/bigquery/migration/v2/translation_config.proto package migrationpb @@ -171,13 +171,11 @@ type TranslationConfigDetails struct { // The chosen path where the source for input files will be found. // // Types that are assignable to SourceLocation: - // // *TranslationConfigDetails_GcsSourcePath SourceLocation isTranslationConfigDetails_SourceLocation `protobuf_oneof:"source_location"` // The chosen path where the destination for output files will be found. // // Types that are assignable to TargetLocation: - // // *TranslationConfigDetails_GcsTargetPath TargetLocation isTranslationConfigDetails_TargetLocation `protobuf_oneof:"target_location"` // The dialect of the input files. @@ -188,7 +186,6 @@ type TranslationConfigDetails struct { // desired output. // // Types that are assignable to OutputNameMapping: - // // *TranslationConfigDetails_NameMappingList OutputNameMapping isTranslationConfigDetails_OutputNameMapping `protobuf_oneof:"output_name_mapping"` // The default source environment values for the translation. @@ -332,7 +329,6 @@ type Dialect struct { // The possible dialect options that this message represents. // // Types that are assignable to DialectValue: - // // *Dialect_BigqueryDialect // *Dialect_HiveqlDialect // *Dialect_RedshiftDialect diff --git a/bigquery/migration/apiv2alpha/doc.go b/bigquery/migration/apiv2alpha/doc.go index 287884fb4015..49bff94447b4 100644 --- a/bigquery/migration/apiv2alpha/doc.go +++ b/bigquery/migration/apiv2alpha/doc.go @@ -83,6 +83,8 @@ package migration // import "cloud.google.com/go/bigquery/migration/apiv2alpha" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -171,3 +173,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/bigquery/migration/apiv2alpha/gapic_metadata.json b/bigquery/migration/apiv2alpha/gapic_metadata.json index 507831a6888f..fe8228e24d0f 100644 --- a/bigquery/migration/apiv2alpha/gapic_metadata.json +++ b/bigquery/migration/apiv2alpha/gapic_metadata.json @@ -46,6 +46,46 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "CreateMigrationWorkflow": { + "methods": [ + "CreateMigrationWorkflow" + ] + }, + "DeleteMigrationWorkflow": { + "methods": [ + "DeleteMigrationWorkflow" + ] + }, + "GetMigrationSubtask": { + "methods": [ + "GetMigrationSubtask" + ] + }, + "GetMigrationWorkflow": { + "methods": [ + "GetMigrationWorkflow" + ] + }, + "ListMigrationSubtasks": { + "methods": [ + "ListMigrationSubtasks" + ] + }, + "ListMigrationWorkflows": { + "methods": [ + "ListMigrationWorkflows" + ] + }, + "StartMigrationWorkflow": { + "methods": [ + "StartMigrationWorkflow" + ] + } + } } } }, @@ -60,6 +100,16 @@ ] } } + }, + "rest": { + "libraryClient": "SqlTranslationClient", + "rpcs": { + "TranslateQuery": { + "methods": [ + "TranslateQuery" + ] + } + } } } } diff --git a/bigquery/migration/apiv2alpha/migration_client.go b/bigquery/migration/apiv2alpha/migration_client.go index b549ea041c2b..99e97336d389 100644 --- a/bigquery/migration/apiv2alpha/migration_client.go +++ b/bigquery/migration/apiv2alpha/migration_client.go @@ -17,21 +17,27 @@ package migration import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" migrationpb "cloud.google.com/go/bigquery/migration/apiv2alpha/migrationpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -122,6 +128,63 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + CreateMigrationWorkflow: []gax.CallOption{}, + GetMigrationWorkflow: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListMigrationWorkflows: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeleteMigrationWorkflow: []gax.CallOption{}, + StartMigrationWorkflow: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetMigrationSubtask: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListMigrationSubtasks: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + } +} + // internalClient is an interface that defines the methods available from BigQuery Migration API. type internalClient interface { Close() error @@ -290,6 +353,74 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new migration service rest client. +// +// Service to handle EDW migrations. +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://bigquerymigration.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://bigquerymigration.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://bigquerymigration.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) CreateMigrationWorkflow(ctx context.Context, req *migrationpb.CreateMigrationWorkflowRequest, opts ...gax.CallOption) (*migrationpb.MigrationWorkflow, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) @@ -482,6 +613,464 @@ func (c *gRPCClient) ListMigrationSubtasks(ctx context.Context, req *migrationpb return it } +// CreateMigrationWorkflow creates a migration workflow. +func (c *restClient) CreateMigrationWorkflow(ctx context.Context, req *migrationpb.CreateMigrationWorkflowRequest, opts ...gax.CallOption) (*migrationpb.MigrationWorkflow, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetMigrationWorkflow() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2alpha/%v/workflows", req.GetParent()) + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateMigrationWorkflow[0:len((*c.CallOptions).CreateMigrationWorkflow):len((*c.CallOptions).CreateMigrationWorkflow)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &migrationpb.MigrationWorkflow{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetMigrationWorkflow gets a previously created migration workflow. +func (c *restClient) GetMigrationWorkflow(ctx context.Context, req *migrationpb.GetMigrationWorkflowRequest, opts ...gax.CallOption) (*migrationpb.MigrationWorkflow, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2alpha/%v", req.GetName()) + + params := url.Values{} + if req.GetReadMask() != nil { + readMask, err := protojson.Marshal(req.GetReadMask()) + if err != nil { + return nil, err + } + params.Add("readMask", string(readMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetMigrationWorkflow[0:len((*c.CallOptions).GetMigrationWorkflow):len((*c.CallOptions).GetMigrationWorkflow)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &migrationpb.MigrationWorkflow{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListMigrationWorkflows lists previously created migration workflow. +func (c *restClient) ListMigrationWorkflows(ctx context.Context, req *migrationpb.ListMigrationWorkflowsRequest, opts ...gax.CallOption) *MigrationWorkflowIterator { + it := &MigrationWorkflowIterator{} + req = proto.Clone(req).(*migrationpb.ListMigrationWorkflowsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*migrationpb.MigrationWorkflow, string, error) { + resp := &migrationpb.ListMigrationWorkflowsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2alpha/%v/workflows", req.GetParent()) + + params := url.Values{} + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + if req.GetReadMask() != nil { + readMask, err := protojson.Marshal(req.GetReadMask()) + if err != nil { + return nil, "", err + } + params.Add("readMask", string(readMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetMigrationWorkflows(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// DeleteMigrationWorkflow deletes a migration workflow by name. +func (c *restClient) DeleteMigrationWorkflow(ctx context.Context, req *migrationpb.DeleteMigrationWorkflowRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2alpha/%v", req.GetName()) + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// StartMigrationWorkflow starts a previously created migration workflow. I.e., the state transitions +// from DRAFT to RUNNING. This is a no-op if the state is already RUNNING. +// An error will be signaled if the state is anything other than DRAFT or +// RUNNING. +func (c *restClient) StartMigrationWorkflow(ctx context.Context, req *migrationpb.StartMigrationWorkflowRequest, opts ...gax.CallOption) error { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2alpha/%v:start", req.GetName()) + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetMigrationSubtask gets a previously created migration subtask. +func (c *restClient) GetMigrationSubtask(ctx context.Context, req *migrationpb.GetMigrationSubtaskRequest, opts ...gax.CallOption) (*migrationpb.MigrationSubtask, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2alpha/%v", req.GetName()) + + params := url.Values{} + if req.GetReadMask() != nil { + readMask, err := protojson.Marshal(req.GetReadMask()) + if err != nil { + return nil, err + } + params.Add("readMask", string(readMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetMigrationSubtask[0:len((*c.CallOptions).GetMigrationSubtask):len((*c.CallOptions).GetMigrationSubtask)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &migrationpb.MigrationSubtask{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListMigrationSubtasks lists previously created migration subtasks. +func (c *restClient) ListMigrationSubtasks(ctx context.Context, req *migrationpb.ListMigrationSubtasksRequest, opts ...gax.CallOption) *MigrationSubtaskIterator { + it := &MigrationSubtaskIterator{} + req = proto.Clone(req).(*migrationpb.ListMigrationSubtasksRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*migrationpb.MigrationSubtask, string, error) { + resp := &migrationpb.ListMigrationSubtasksResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2alpha/%v/subtasks", req.GetParent()) + + params := url.Values{} + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + if req.GetReadMask() != nil { + readMask, err := protojson.Marshal(req.GetReadMask()) + if err != nil { + return nil, "", err + } + params.Add("readMask", string(readMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetMigrationSubtasks(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + // MigrationSubtaskIterator manages a stream of *migrationpb.MigrationSubtask. type MigrationSubtaskIterator struct { items []*migrationpb.MigrationSubtask diff --git a/bigquery/migration/apiv2alpha/migration_client_example_test.go b/bigquery/migration/apiv2alpha/migration_client_example_test.go index 4d5cad89031f..f8202ad838e4 100644 --- a/bigquery/migration/apiv2alpha/migration_client_example_test.go +++ b/bigquery/migration/apiv2alpha/migration_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := migration.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_CreateMigrationWorkflow() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/bigquery/migration/apiv2alpha/migrationpb/assessment_task.pb.go b/bigquery/migration/apiv2alpha/migrationpb/assessment_task.pb.go index 8b4cf3186281..5023b8ce8e13 100644 --- a/bigquery/migration/apiv2alpha/migrationpb/assessment_task.pb.go +++ b/bigquery/migration/apiv2alpha/migrationpb/assessment_task.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/bigquery/migration/v2alpha/assessment_task.proto package migrationpb diff --git a/bigquery/migration/apiv2alpha/migrationpb/migration_entities.pb.go b/bigquery/migration/apiv2alpha/migrationpb/migration_entities.pb.go index 346f97fe26e9..09d22299e6e4 100644 --- a/bigquery/migration/apiv2alpha/migrationpb/migration_entities.pb.go +++ b/bigquery/migration/apiv2alpha/migrationpb/migration_entities.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/bigquery/migration/v2alpha/migration_entities.proto package migrationpb @@ -351,7 +351,6 @@ type MigrationTask struct { // The details of the task. // // Types that are assignable to TaskDetails: - // // *MigrationTask_AssessmentTaskDetails // *MigrationTask_TranslationTaskDetails TaskDetails isMigrationTask_TaskDetails `protobuf_oneof:"task_details"` @@ -654,7 +653,6 @@ type MigrationTaskOrchestrationResult struct { // Details specific to the task type. // // Types that are assignable to Details: - // // *MigrationTaskOrchestrationResult_AssessmentDetails Details isMigrationTaskOrchestrationResult_Details `protobuf_oneof:"details"` } diff --git a/bigquery/migration/apiv2alpha/migrationpb/migration_error_details.pb.go b/bigquery/migration/apiv2alpha/migrationpb/migration_error_details.pb.go index 12709347427a..1a4521d465d9 100644 --- a/bigquery/migration/apiv2alpha/migrationpb/migration_error_details.pb.go +++ b/bigquery/migration/apiv2alpha/migrationpb/migration_error_details.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/bigquery/migration/v2alpha/migration_error_details.proto package migrationpb diff --git a/bigquery/migration/apiv2alpha/migrationpb/migration_metrics.pb.go b/bigquery/migration/apiv2alpha/migrationpb/migration_metrics.pb.go index e4f6248fba9d..588a7e51ce78 100644 --- a/bigquery/migration/apiv2alpha/migrationpb/migration_metrics.pb.go +++ b/bigquery/migration/apiv2alpha/migrationpb/migration_metrics.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/bigquery/migration/v2alpha/migration_metrics.proto package migrationpb @@ -112,14 +112,14 @@ func (x *TimeSeries) GetValueType() metric.MetricDescriptor_ValueType { if x != nil { return x.ValueType } - return metric.MetricDescriptor_VALUE_TYPE_UNSPECIFIED + return metric.MetricDescriptor_ValueType(0) } func (x *TimeSeries) GetMetricKind() metric.MetricDescriptor_MetricKind { if x != nil { return x.MetricKind } - return metric.MetricDescriptor_METRIC_KIND_UNSPECIFIED + return metric.MetricDescriptor_MetricKind(0) } func (x *TimeSeries) GetPoints() []*Point { @@ -266,7 +266,6 @@ type TypedValue struct { // The typed value field. // // Types that are assignable to Value: - // // *TypedValue_BoolValue // *TypedValue_Int64Value // *TypedValue_DoubleValue diff --git a/bigquery/migration/apiv2alpha/migrationpb/migration_service.pb.go b/bigquery/migration/apiv2alpha/migrationpb/migration_service.pb.go index 027e46714b06..b035f76e1949 100644 --- a/bigquery/migration/apiv2alpha/migrationpb/migration_service.pb.go +++ b/bigquery/migration/apiv2alpha/migrationpb/migration_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/bigquery/migration/v2alpha/migration_service.proto package migrationpb diff --git a/bigquery/migration/apiv2alpha/migrationpb/translation_service.pb.go b/bigquery/migration/apiv2alpha/migrationpb/translation_service.pb.go index 5e2e8b7f864d..a39694d5a6b3 100644 --- a/bigquery/migration/apiv2alpha/migrationpb/translation_service.pb.go +++ b/bigquery/migration/apiv2alpha/migrationpb/translation_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/bigquery/migration/v2alpha/translation_service.proto package migrationpb diff --git a/bigquery/migration/apiv2alpha/migrationpb/translation_task.pb.go b/bigquery/migration/apiv2alpha/migrationpb/translation_task.pb.go index 09eb5481f8c3..4e20013da3ff 100644 --- a/bigquery/migration/apiv2alpha/migrationpb/translation_task.pb.go +++ b/bigquery/migration/apiv2alpha/migrationpb/translation_task.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/bigquery/migration/v2alpha/translation_task.proto package migrationpb @@ -355,7 +355,6 @@ type TranslationTaskDetails struct { // The language specific settings for the translation task. // // Types that are assignable to LanguageOptions: - // // *TranslationTaskDetails_TeradataOptions // *TranslationTaskDetails_BteqOptions LanguageOptions isTranslationTaskDetails_LanguageOptions `protobuf_oneof:"language_options"` diff --git a/bigquery/migration/apiv2alpha/sql_translation_client.go b/bigquery/migration/apiv2alpha/sql_translation_client.go index 6b9a589991fa..8249a423e80d 100644 --- a/bigquery/migration/apiv2alpha/sql_translation_client.go +++ b/bigquery/migration/apiv2alpha/sql_translation_client.go @@ -17,18 +17,24 @@ package migration import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" migrationpb "cloud.google.com/go/bigquery/migration/apiv2alpha/migrationpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" ) var newSqlTranslationClientHook clientHook @@ -56,6 +62,12 @@ func defaultSqlTranslationCallOptions() *SqlTranslationCallOptions { } } +func defaultSqlTranslationRESTCallOptions() *SqlTranslationCallOptions { + return &SqlTranslationCallOptions{ + TranslateQuery: []gax.CallOption{}, + } +} + // internalSqlTranslationClient is an interface that defines the methods available from BigQuery Migration API. type internalSqlTranslationClient interface { Close() error @@ -185,6 +197,74 @@ func (c *sqlTranslationGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type sqlTranslationRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing SqlTranslationClient + CallOptions **SqlTranslationCallOptions +} + +// NewSqlTranslationRESTClient creates a new sql translation service rest client. +// +// Provides other SQL dialects to GoogleSQL translation operations. +func NewSqlTranslationRESTClient(ctx context.Context, opts ...option.ClientOption) (*SqlTranslationClient, error) { + clientOpts := append(defaultSqlTranslationRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultSqlTranslationRESTCallOptions() + c := &sqlTranslationRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &SqlTranslationClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultSqlTranslationRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://bigquerymigration.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://bigquerymigration.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://bigquerymigration.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *sqlTranslationRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *sqlTranslationRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *sqlTranslationRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *sqlTranslationGRPCClient) TranslateQuery(ctx context.Context, req *migrationpb.TranslateQueryRequest, opts ...gax.CallOption) (*migrationpb.TranslateQueryResponse, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -201,3 +281,62 @@ func (c *sqlTranslationGRPCClient) TranslateQuery(ctx context.Context, req *migr } return resp, nil } + +// TranslateQuery translates input queries from source dialects to GoogleSQL. +func (c *sqlTranslationRESTClient) TranslateQuery(ctx context.Context, req *migrationpb.TranslateQueryRequest, opts ...gax.CallOption) (*migrationpb.TranslateQueryResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2alpha/%v:translateQuery", req.GetParent()) + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).TranslateQuery[0:len((*c.CallOptions).TranslateQuery):len((*c.CallOptions).TranslateQuery)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &migrationpb.TranslateQueryResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} diff --git a/bigquery/migration/apiv2alpha/sql_translation_client_example_test.go b/bigquery/migration/apiv2alpha/sql_translation_client_example_test.go index 37be00ab3407..a73da25855e6 100644 --- a/bigquery/migration/apiv2alpha/sql_translation_client_example_test.go +++ b/bigquery/migration/apiv2alpha/sql_translation_client_example_test.go @@ -40,6 +40,23 @@ func ExampleNewSqlTranslationClient() { _ = c } +func ExampleNewSqlTranslationRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := migration.NewSqlTranslationRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleSqlTranslationClient_TranslateQuery() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/bigquery/reservation/apiv1/doc.go b/bigquery/reservation/apiv1/doc.go index 00e6bac9649d..a8fa6e662744 100644 --- a/bigquery/reservation/apiv1/doc.go +++ b/bigquery/reservation/apiv1/doc.go @@ -80,6 +80,8 @@ package reservation // import "cloud.google.com/go/bigquery/reservation/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -169,3 +171,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/bigquery/reservation/apiv1/gapic_metadata.json b/bigquery/reservation/apiv1/gapic_metadata.json index af74246e8a44..83d8ecb6871c 100644 --- a/bigquery/reservation/apiv1/gapic_metadata.json +++ b/bigquery/reservation/apiv1/gapic_metadata.json @@ -116,6 +116,116 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "CreateAssignment": { + "methods": [ + "CreateAssignment" + ] + }, + "CreateCapacityCommitment": { + "methods": [ + "CreateCapacityCommitment" + ] + }, + "CreateReservation": { + "methods": [ + "CreateReservation" + ] + }, + "DeleteAssignment": { + "methods": [ + "DeleteAssignment" + ] + }, + "DeleteCapacityCommitment": { + "methods": [ + "DeleteCapacityCommitment" + ] + }, + "DeleteReservation": { + "methods": [ + "DeleteReservation" + ] + }, + "GetBiReservation": { + "methods": [ + "GetBiReservation" + ] + }, + "GetCapacityCommitment": { + "methods": [ + "GetCapacityCommitment" + ] + }, + "GetReservation": { + "methods": [ + "GetReservation" + ] + }, + "ListAssignments": { + "methods": [ + "ListAssignments" + ] + }, + "ListCapacityCommitments": { + "methods": [ + "ListCapacityCommitments" + ] + }, + "ListReservations": { + "methods": [ + "ListReservations" + ] + }, + "MergeCapacityCommitments": { + "methods": [ + "MergeCapacityCommitments" + ] + }, + "MoveAssignment": { + "methods": [ + "MoveAssignment" + ] + }, + "SearchAllAssignments": { + "methods": [ + "SearchAllAssignments" + ] + }, + "SearchAssignments": { + "methods": [ + "SearchAssignments" + ] + }, + "SplitCapacityCommitment": { + "methods": [ + "SplitCapacityCommitment" + ] + }, + "UpdateAssignment": { + "methods": [ + "UpdateAssignment" + ] + }, + "UpdateBiReservation": { + "methods": [ + "UpdateBiReservation" + ] + }, + "UpdateCapacityCommitment": { + "methods": [ + "UpdateCapacityCommitment" + ] + }, + "UpdateReservation": { + "methods": [ + "UpdateReservation" + ] + } + } } } } diff --git a/bigquery/reservation/apiv1/reservation_client.go b/bigquery/reservation/apiv1/reservation_client.go index 794baaaa75fa..4dbfc0e65278 100644 --- a/bigquery/reservation/apiv1/reservation_client.go +++ b/bigquery/reservation/apiv1/reservation_client.go @@ -17,21 +17,27 @@ package reservation import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" reservationpb "cloud.google.com/go/bigquery/reservation/apiv1/reservationpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -210,6 +216,132 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + CreateReservation: []gax.CallOption{}, + ListReservations: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + GetReservation: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + DeleteReservation: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + UpdateReservation: []gax.CallOption{}, + CreateCapacityCommitment: []gax.CallOption{}, + ListCapacityCommitments: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + GetCapacityCommitment: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + DeleteCapacityCommitment: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + UpdateCapacityCommitment: []gax.CallOption{}, + SplitCapacityCommitment: []gax.CallOption{}, + MergeCapacityCommitments: []gax.CallOption{}, + CreateAssignment: []gax.CallOption{}, + ListAssignments: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + DeleteAssignment: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + SearchAssignments: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + SearchAllAssignments: []gax.CallOption{}, + MoveAssignment: []gax.CallOption{}, + UpdateAssignment: []gax.CallOption{}, + GetBiReservation: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + UpdateBiReservation: []gax.CallOption{}, + } +} + // internalClient is an interface that defines the methods available from BigQuery Reservation API. type internalClient interface { Close() error @@ -647,6 +779,88 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new reservation service rest client. +// +// This API allows users to manage their flat-rate BigQuery reservations. +// +// A reservation provides computational resource guarantees, in the form of +// slots (at https://cloud.google.com/bigquery/docs/slots), to users. A slot is a +// unit of computational power in BigQuery, and serves as the basic unit of +// parallelism. In a scan of a multi-partitioned table, a single slot operates +// on a single partition of the table. A reservation resource exists as a child +// resource of the admin project and location, e.g.: +// projects/myproject/locations/US/reservations/reservationName. +// +// A capacity commitment is a way to purchase compute capacity for BigQuery jobs +// (in the form of slots) with some committed period of usage. A capacity +// commitment resource exists as a child resource of the admin project and +// location, e.g.: +// projects/myproject/locations/US/capacityCommitments/id. +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://bigqueryreservation.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://bigqueryreservation.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://bigqueryreservation.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) CreateReservation(ctx context.Context, req *reservationpb.CreateReservationRequest, opts ...gax.CallOption) (*reservationpb.Reservation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 300000*time.Millisecond) @@ -1207,6 +1421,1596 @@ func (c *gRPCClient) UpdateBiReservation(ctx context.Context, req *reservationpb return resp, nil } +// CreateReservation creates a new reservation resource. +func (c *restClient) CreateReservation(ctx context.Context, req *reservationpb.CreateReservationRequest, opts ...gax.CallOption) (*reservationpb.Reservation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetReservation() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/reservations", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetReservationId() != "" { + params.Add("reservationId", fmt.Sprintf("%v", req.GetReservationId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateReservation[0:len((*c.CallOptions).CreateReservation):len((*c.CallOptions).CreateReservation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &reservationpb.Reservation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListReservations lists all the reservations for the project in the specified location. +func (c *restClient) ListReservations(ctx context.Context, req *reservationpb.ListReservationsRequest, opts ...gax.CallOption) *ReservationIterator { + it := &ReservationIterator{} + req = proto.Clone(req).(*reservationpb.ListReservationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*reservationpb.Reservation, string, error) { + resp := &reservationpb.ListReservationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/reservations", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetReservations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetReservation returns information about the reservation. +func (c *restClient) GetReservation(ctx context.Context, req *reservationpb.GetReservationRequest, opts ...gax.CallOption) (*reservationpb.Reservation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetReservation[0:len((*c.CallOptions).GetReservation):len((*c.CallOptions).GetReservation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &reservationpb.Reservation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteReservation deletes a reservation. +// Returns google.rpc.Code.FAILED_PRECONDITION when reservation has +// assignments. +func (c *restClient) DeleteReservation(ctx context.Context, req *reservationpb.DeleteReservationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// UpdateReservation updates an existing reservation resource. +func (c *restClient) UpdateReservation(ctx context.Context, req *reservationpb.UpdateReservationRequest, opts ...gax.CallOption) (*reservationpb.Reservation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetReservation() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetReservation().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "reservation.name", url.QueryEscape(req.GetReservation().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateReservation[0:len((*c.CallOptions).UpdateReservation):len((*c.CallOptions).UpdateReservation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &reservationpb.Reservation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateCapacityCommitment creates a new capacity commitment resource. +func (c *restClient) CreateCapacityCommitment(ctx context.Context, req *reservationpb.CreateCapacityCommitmentRequest, opts ...gax.CallOption) (*reservationpb.CapacityCommitment, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetCapacityCommitment() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/capacityCommitments", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetCapacityCommitmentId() != "" { + params.Add("capacityCommitmentId", fmt.Sprintf("%v", req.GetCapacityCommitmentId())) + } + if req.GetEnforceSingleAdminProjectPerOrg() { + params.Add("enforceSingleAdminProjectPerOrg", fmt.Sprintf("%v", req.GetEnforceSingleAdminProjectPerOrg())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateCapacityCommitment[0:len((*c.CallOptions).CreateCapacityCommitment):len((*c.CallOptions).CreateCapacityCommitment)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &reservationpb.CapacityCommitment{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListCapacityCommitments lists all the capacity commitments for the admin project. +func (c *restClient) ListCapacityCommitments(ctx context.Context, req *reservationpb.ListCapacityCommitmentsRequest, opts ...gax.CallOption) *CapacityCommitmentIterator { + it := &CapacityCommitmentIterator{} + req = proto.Clone(req).(*reservationpb.ListCapacityCommitmentsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*reservationpb.CapacityCommitment, string, error) { + resp := &reservationpb.ListCapacityCommitmentsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/capacityCommitments", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetCapacityCommitments(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetCapacityCommitment returns information about the capacity commitment. +func (c *restClient) GetCapacityCommitment(ctx context.Context, req *reservationpb.GetCapacityCommitmentRequest, opts ...gax.CallOption) (*reservationpb.CapacityCommitment, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetCapacityCommitment[0:len((*c.CallOptions).GetCapacityCommitment):len((*c.CallOptions).GetCapacityCommitment)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &reservationpb.CapacityCommitment{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteCapacityCommitment deletes a capacity commitment. Attempting to delete capacity commitment +// before its commitment_end_time will fail with the error code +// google.rpc.Code.FAILED_PRECONDITION. +func (c *restClient) DeleteCapacityCommitment(ctx context.Context, req *reservationpb.DeleteCapacityCommitmentRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetForce() { + params.Add("force", fmt.Sprintf("%v", req.GetForce())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// UpdateCapacityCommitment updates an existing capacity commitment. +// +// Only plan and renewal_plan fields can be updated. +// +// Plan can only be changed to a plan of a longer commitment period. +// Attempting to change to a plan with shorter commitment period will fail +// with the error code google.rpc.Code.FAILED_PRECONDITION. +func (c *restClient) UpdateCapacityCommitment(ctx context.Context, req *reservationpb.UpdateCapacityCommitmentRequest, opts ...gax.CallOption) (*reservationpb.CapacityCommitment, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetCapacityCommitment() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetCapacityCommitment().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "capacity_commitment.name", url.QueryEscape(req.GetCapacityCommitment().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateCapacityCommitment[0:len((*c.CallOptions).UpdateCapacityCommitment):len((*c.CallOptions).UpdateCapacityCommitment)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &reservationpb.CapacityCommitment{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SplitCapacityCommitment splits capacity commitment to two commitments of the same plan and +// commitment_end_time. +// +// A common use case is to enable downgrading commitments. +// +// For example, in order to downgrade from 10000 slots to 8000, you might +// split a 10000 capacity commitment into commitments of 2000 and 8000. Then, +// you delete the first one after the commitment end time passes. +func (c *restClient) SplitCapacityCommitment(ctx context.Context, req *reservationpb.SplitCapacityCommitmentRequest, opts ...gax.CallOption) (*reservationpb.SplitCapacityCommitmentResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:split", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SplitCapacityCommitment[0:len((*c.CallOptions).SplitCapacityCommitment):len((*c.CallOptions).SplitCapacityCommitment)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &reservationpb.SplitCapacityCommitmentResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// MergeCapacityCommitments merges capacity commitments of the same plan into a single commitment. +// +// The resulting capacity commitment has the greater commitment_end_time +// out of the to-be-merged capacity commitments. +// +// Attempting to merge capacity commitments of different plan will fail +// with the error code google.rpc.Code.FAILED_PRECONDITION. +func (c *restClient) MergeCapacityCommitments(ctx context.Context, req *reservationpb.MergeCapacityCommitmentsRequest, opts ...gax.CallOption) (*reservationpb.CapacityCommitment, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/capacityCommitments:merge", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).MergeCapacityCommitments[0:len((*c.CallOptions).MergeCapacityCommitments):len((*c.CallOptions).MergeCapacityCommitments)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &reservationpb.CapacityCommitment{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateAssignment creates an assignment object which allows the given project to submit jobs +// of a certain type using slots from the specified reservation. +// +// Currently a +// resource (project, folder, organization) can only have one assignment per +// each (job_type, location) combination, and that reservation will be used +// for all jobs of the matching type. +// +// Different assignments can be created on different levels of the +// projects, folders or organization hierarchy. During query execution, +// the assignment is looked up at the project, folder and organization levels +// in that order. The first assignment found is applied to the query. +// +// When creating assignments, it does not matter if other assignments exist at +// higher levels. +// +// Example: +// +// The organization organizationA contains two projects, project1 +// and project2. +// +// Assignments for all three entities (organizationA, project1, and +// project2) could all be created and mapped to the same or different +// reservations. +// +// “None” assignments represent an absence of the assignment. Projects +// assigned to None use on-demand pricing. To create a “None” assignment, use +// “none” as a reservation_id in the parent. Example parent: +// projects/myproject/locations/US/reservations/none. +// +// Returns google.rpc.Code.PERMISSION_DENIED if user does not have +// ‘bigquery.admin’ permissions on the project using the reservation +// and the project that owns this reservation. +// +// Returns google.rpc.Code.INVALID_ARGUMENT when location of the assignment +// does not match location of the reservation. +func (c *restClient) CreateAssignment(ctx context.Context, req *reservationpb.CreateAssignmentRequest, opts ...gax.CallOption) (*reservationpb.Assignment, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetAssignment() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/assignments", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetAssignmentId() != "" { + params.Add("assignmentId", fmt.Sprintf("%v", req.GetAssignmentId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateAssignment[0:len((*c.CallOptions).CreateAssignment):len((*c.CallOptions).CreateAssignment)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &reservationpb.Assignment{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListAssignments lists assignments. +// +// Only explicitly created assignments will be returned. +// +// Example: +// +// Organization organizationA contains two projects, project1 and +// project2. +// +// Reservation res1 exists and was created previously. +// +// CreateAssignment was used previously to define the following +// associations between entities and reservations: +// and +// +// In this example, ListAssignments will just return the above two assignments +// for reservation res1, and no expansion/merge will happen. +// +// The wildcard “-” can be used for +// reservations in the request. In that case all assignments belongs to the +// specified project and location will be listed. +// +// Note "-" cannot be used for projects nor locations. +func (c *restClient) ListAssignments(ctx context.Context, req *reservationpb.ListAssignmentsRequest, opts ...gax.CallOption) *AssignmentIterator { + it := &AssignmentIterator{} + req = proto.Clone(req).(*reservationpb.ListAssignmentsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*reservationpb.Assignment, string, error) { + resp := &reservationpb.ListAssignmentsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/assignments", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetAssignments(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// DeleteAssignment deletes a assignment. No expansion will happen. +// +// Example: +// +// Organization organizationA contains two projects, project1 and +// project2. +// +// Reservation res1 exists and was created previously. +// +// CreateAssignment was used previously to define the following +// associations between entities and reservations: +// and +// +// In this example, deletion of the assignment won’t +// affect the other assignment . After said deletion, +// queries from project1 will still use res1 while queries from +// project2 will switch to use on-demand mode. +func (c *restClient) DeleteAssignment(ctx context.Context, req *reservationpb.DeleteAssignmentRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// SearchAssignments deprecated: Looks up assignments for a specified resource for a particular +// region. If the request is about a project: +// +// Assignments created on the project will be returned if they exist. +// +// Otherwise assignments created on the closest ancestor will be +// returned. +// +// Assignments for different JobTypes will all be returned. +// +// The same logic applies if the request is about a folder. +// +// If the request is about an organization, then assignments created on the +// organization will be returned (organization doesn’t have ancestors). +// +// Comparing to ListAssignments, there are some behavior +// differences: +// +// permission on the assignee will be verified in this API. +// +// Hierarchy lookup (project->folder->organization) happens in this API. +// +// Parent here is projects/*/locations/*, instead of +// projects/*/locations/*reservations/*. +// +// Note "-" cannot be used for projects +// nor locations. +// +// Deprecated: SearchAssignments may be removed in a future version. +func (c *restClient) SearchAssignments(ctx context.Context, req *reservationpb.SearchAssignmentsRequest, opts ...gax.CallOption) *AssignmentIterator { + it := &AssignmentIterator{} + req = proto.Clone(req).(*reservationpb.SearchAssignmentsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*reservationpb.Assignment, string, error) { + resp := &reservationpb.SearchAssignmentsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:searchAssignments", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + if req.GetQuery() != "" { + params.Add("query", fmt.Sprintf("%v", req.GetQuery())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetAssignments(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// SearchAllAssignments looks up assignments for a specified resource for a particular region. +// If the request is about a project: +// +// Assignments created on the project will be returned if they exist. +// +// Otherwise assignments created on the closest ancestor will be +// returned. +// +// Assignments for different JobTypes will all be returned. +// +// The same logic applies if the request is about a folder. +// +// If the request is about an organization, then assignments created on the +// organization will be returned (organization doesn’t have ancestors). +// +// Comparing to ListAssignments, there are some behavior +// differences: +// +// permission on the assignee will be verified in this API. +// +// Hierarchy lookup (project->folder->organization) happens in this API. +// +// Parent here is projects/*/locations/*, instead of +// projects/*/locations/*reservations/*. +func (c *restClient) SearchAllAssignments(ctx context.Context, req *reservationpb.SearchAllAssignmentsRequest, opts ...gax.CallOption) *AssignmentIterator { + it := &AssignmentIterator{} + req = proto.Clone(req).(*reservationpb.SearchAllAssignmentsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*reservationpb.Assignment, string, error) { + resp := &reservationpb.SearchAllAssignmentsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:searchAllAssignments", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + if req.GetQuery() != "" { + params.Add("query", fmt.Sprintf("%v", req.GetQuery())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetAssignments(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// MoveAssignment moves an assignment under a new reservation. +// +// This differs from removing an existing assignment and recreating a new one +// by providing a transactional change that ensures an assignee always has an +// associated reservation. +func (c *restClient) MoveAssignment(ctx context.Context, req *reservationpb.MoveAssignmentRequest, opts ...gax.CallOption) (*reservationpb.Assignment, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:move", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).MoveAssignment[0:len((*c.CallOptions).MoveAssignment):len((*c.CallOptions).MoveAssignment)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &reservationpb.Assignment{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateAssignment updates an existing assignment. +// +// Only the priority field can be updated. +func (c *restClient) UpdateAssignment(ctx context.Context, req *reservationpb.UpdateAssignmentRequest, opts ...gax.CallOption) (*reservationpb.Assignment, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetAssignment() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetAssignment().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "assignment.name", url.QueryEscape(req.GetAssignment().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateAssignment[0:len((*c.CallOptions).UpdateAssignment):len((*c.CallOptions).UpdateAssignment)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &reservationpb.Assignment{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetBiReservation retrieves a BI reservation. +func (c *restClient) GetBiReservation(ctx context.Context, req *reservationpb.GetBiReservationRequest, opts ...gax.CallOption) (*reservationpb.BiReservation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetBiReservation[0:len((*c.CallOptions).GetBiReservation):len((*c.CallOptions).GetBiReservation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &reservationpb.BiReservation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateBiReservation updates a BI reservation. +// +// Only fields specified in the field_mask are updated. +// +// A singleton BI reservation always exists with default size 0. +// In order to reserve BI capacity it needs to be updated to an amount +// greater than 0. In order to release BI capacity reservation size +// must be set to 0. +func (c *restClient) UpdateBiReservation(ctx context.Context, req *reservationpb.UpdateBiReservationRequest, opts ...gax.CallOption) (*reservationpb.BiReservation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetBiReservation() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetBiReservation().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "bi_reservation.name", url.QueryEscape(req.GetBiReservation().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateBiReservation[0:len((*c.CallOptions).UpdateBiReservation):len((*c.CallOptions).UpdateBiReservation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &reservationpb.BiReservation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + // AssignmentIterator manages a stream of *reservationpb.Assignment. type AssignmentIterator struct { items []*reservationpb.Assignment diff --git a/bigquery/reservation/apiv1/reservation_client_example_test.go b/bigquery/reservation/apiv1/reservation_client_example_test.go index 0243c87e90e8..cbdd0736be9e 100644 --- a/bigquery/reservation/apiv1/reservation_client_example_test.go +++ b/bigquery/reservation/apiv1/reservation_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := reservation.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_CreateReservation() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/bigquery/reservation/apiv1/reservationpb/reservation.pb.go b/bigquery/reservation/apiv1/reservationpb/reservation.pb.go index 031ee1bf6722..0a36c861b4ea 100644 --- a/bigquery/reservation/apiv1/reservationpb/reservation.pb.go +++ b/bigquery/reservation/apiv1/reservationpb/reservation.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/bigquery/reservation/v1/reservation.proto package reservationpb @@ -643,8 +643,7 @@ type ListReservationsRequest struct { unknownFields protoimpl.UnknownFields // Required. The parent resource name containing project and location, e.g.: - // - // `projects/myproject/locations/US` + // `projects/myproject/locations/US` Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // The maximum number of items to return per page. PageSize int32 `protobuf:"varint,2,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"` @@ -771,8 +770,7 @@ type GetReservationRequest struct { unknownFields protoimpl.UnknownFields // Required. Resource name of the reservation to retrieve. E.g., - // - // `projects/myproject/locations/US/reservations/team1-prod` + // `projects/myproject/locations/US/reservations/team1-prod` Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` } @@ -822,8 +820,7 @@ type DeleteReservationRequest struct { unknownFields protoimpl.UnknownFields // Required. Resource name of the reservation to retrieve. E.g., - // - // `projects/myproject/locations/US/reservations/team1-prod` + // `projects/myproject/locations/US/reservations/team1-prod` Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` } @@ -931,8 +928,7 @@ type CreateCapacityCommitmentRequest struct { unknownFields protoimpl.UnknownFields // Required. Resource name of the parent reservation. E.g., - // - // `projects/myproject/locations/US` + // `projects/myproject/locations/US` Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // Content of the capacity commitment to create. CapacityCommitment *CapacityCommitment `protobuf:"bytes,2,opt,name=capacity_commitment,json=capacityCommitment,proto3" json:"capacity_commitment,omitempty"` @@ -1014,8 +1010,7 @@ type ListCapacityCommitmentsRequest struct { unknownFields protoimpl.UnknownFields // Required. Resource name of the parent reservation. E.g., - // - // `projects/myproject/locations/US` + // `projects/myproject/locations/US` Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // The maximum number of items to return. PageSize int32 `protobuf:"varint,2,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"` @@ -1142,8 +1137,7 @@ type GetCapacityCommitmentRequest struct { unknownFields protoimpl.UnknownFields // Required. Resource name of the capacity commitment to retrieve. E.g., - // - // `projects/myproject/locations/US/capacityCommitments/123` + // `projects/myproject/locations/US/capacityCommitments/123` Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` } @@ -1193,8 +1187,7 @@ type DeleteCapacityCommitmentRequest struct { unknownFields protoimpl.UnknownFields // Required. Resource name of the capacity commitment to delete. E.g., - // - // `projects/myproject/locations/US/capacityCommitments/123` + // `projects/myproject/locations/US/capacityCommitments/123` Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Can be used to force delete commitments even if assignments exist. Deleting // commitments with assignments may cause queries to fail if they no longer @@ -1313,8 +1306,7 @@ type SplitCapacityCommitmentRequest struct { unknownFields protoimpl.UnknownFields // Required. The resource name e.g.,: - // - // `projects/myproject/locations/US/capacityCommitments/123` + // `projects/myproject/locations/US/capacityCommitments/123` Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Number of slots in the capacity commitment after the split. SlotCount int64 `protobuf:"varint,2,opt,name=slot_count,json=slotCount,proto3" json:"slot_count,omitempty"` @@ -1431,8 +1423,7 @@ type MergeCapacityCommitmentsRequest struct { unknownFields protoimpl.UnknownFields // Parent resource that identifies admin project and location e.g., - // - // `projects/myproject/locations/us` + // `projects/myproject/locations/us` Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // Ids of capacity commitments to merge. // These capacity commitments must exist under admin project and location @@ -1783,8 +1774,7 @@ type DeleteAssignmentRequest struct { unknownFields protoimpl.UnknownFields // Required. Name of the resource, e.g. - // - // `projects/myproject/locations/US/reservations/team1-prod/assignments/123` + // `projects/myproject/locations/US/reservations/team1-prod/assignments/123` Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` } @@ -1838,8 +1828,7 @@ type SearchAssignmentsRequest struct { // Required. The resource name of the admin project(containing project and location), // e.g.: - // - // `projects/myproject/locations/US`. + // `projects/myproject/locations/US`. Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // Please specify resource name as assignee in the query. // @@ -1926,8 +1915,7 @@ type SearchAllAssignmentsRequest struct { // Required. The resource name with location (project name could be the wildcard '-'), // e.g.: - // - // `projects/-/locations/US`. + // `projects/-/locations/US`. Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // Please specify resource name as assignee in the query. // @@ -2140,8 +2128,7 @@ type MoveAssignmentRequest struct { // `projects/myproject/locations/US/reservations/team1-prod/assignments/123` Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // The new reservation ID, e.g.: - // - // `projects/myotherproject/locations/US/reservations/team2-prod` + // `projects/myotherproject/locations/US/reservations/team2-prod` DestinationId string `protobuf:"bytes,3,opt,name=destination_id,json=destinationId,proto3" json:"destination_id,omitempty"` } @@ -3923,11 +3910,11 @@ type ReservationServiceClient interface { // // Example: // - // - The organization `organizationA` contains two projects, `project1` - // and `project2`. - // - Assignments for all three entities (`organizationA`, `project1`, and - // `project2`) could all be created and mapped to the same or different - // reservations. + // * The organization `organizationA` contains two projects, `project1` + // and `project2`. + // * Assignments for all three entities (`organizationA`, `project1`, and + // `project2`) could all be created and mapped to the same or different + // reservations. // // "None" assignments represent an absence of the assignment. Projects // assigned to None use on-demand pricing. To create a "None" assignment, use @@ -3947,12 +3934,12 @@ type ReservationServiceClient interface { // // Example: // - // - Organization `organizationA` contains two projects, `project1` and - // `project2`. - // - Reservation `res1` exists and was created previously. - // - CreateAssignment was used previously to define the following - // associations between entities and reservations: `` - // and `` + // * Organization `organizationA` contains two projects, `project1` and + // `project2`. + // * Reservation `res1` exists and was created previously. + // * CreateAssignment was used previously to define the following + // associations between entities and reservations: `` + // and `` // // In this example, ListAssignments will just return the above two assignments // for reservation `res1`, and no expansion/merge will happen. @@ -3967,12 +3954,12 @@ type ReservationServiceClient interface { // // Example: // - // - Organization `organizationA` contains two projects, `project1` and - // `project2`. - // - Reservation `res1` exists and was created previously. - // - CreateAssignment was used previously to define the following - // associations between entities and reservations: `` - // and `` + // * Organization `organizationA` contains two projects, `project1` and + // `project2`. + // * Reservation `res1` exists and was created previously. + // * CreateAssignment was used previously to define the following + // associations between entities and reservations: `` + // and `` // // In this example, deletion of the `` assignment won't // affect the other assignment ``. After said deletion, @@ -3983,10 +3970,10 @@ type ReservationServiceClient interface { // Deprecated: Looks up assignments for a specified resource for a particular // region. If the request is about a project: // - // 1. Assignments created on the project will be returned if they exist. - // 2. Otherwise assignments created on the closest ancestor will be - // returned. - // 3. Assignments for different JobTypes will all be returned. + // 1. Assignments created on the project will be returned if they exist. + // 2. Otherwise assignments created on the closest ancestor will be + // returned. + // 3. Assignments for different JobTypes will all be returned. // // The same logic applies if the request is about a folder. // @@ -3996,10 +3983,10 @@ type ReservationServiceClient interface { // Comparing to ListAssignments, there are some behavior // differences: // - // 1. permission on the assignee will be verified in this API. - // 2. Hierarchy lookup (project->folder->organization) happens in this API. - // 3. Parent here is `projects/*/locations/*`, instead of - // `projects/*/locations/*reservations/*`. + // 1. permission on the assignee will be verified in this API. + // 2. Hierarchy lookup (project->folder->organization) happens in this API. + // 3. Parent here is `projects/*/locations/*`, instead of + // `projects/*/locations/*reservations/*`. // // **Note** "-" cannot be used for projects // nor locations. @@ -4007,10 +3994,10 @@ type ReservationServiceClient interface { // Looks up assignments for a specified resource for a particular region. // If the request is about a project: // - // 1. Assignments created on the project will be returned if they exist. - // 2. Otherwise assignments created on the closest ancestor will be - // returned. - // 3. Assignments for different JobTypes will all be returned. + // 1. Assignments created on the project will be returned if they exist. + // 2. Otherwise assignments created on the closest ancestor will be + // returned. + // 3. Assignments for different JobTypes will all be returned. // // The same logic applies if the request is about a folder. // @@ -4020,10 +4007,10 @@ type ReservationServiceClient interface { // Comparing to ListAssignments, there are some behavior // differences: // - // 1. permission on the assignee will be verified in this API. - // 2. Hierarchy lookup (project->folder->organization) happens in this API. - // 3. Parent here is `projects/*/locations/*`, instead of - // `projects/*/locations/*reservations/*`. + // 1. permission on the assignee will be verified in this API. + // 2. Hierarchy lookup (project->folder->organization) happens in this API. + // 3. Parent here is `projects/*/locations/*`, instead of + // `projects/*/locations/*reservations/*`. SearchAllAssignments(ctx context.Context, in *SearchAllAssignmentsRequest, opts ...grpc.CallOption) (*SearchAllAssignmentsResponse, error) // Moves an assignment under a new reservation. // @@ -4313,11 +4300,11 @@ type ReservationServiceServer interface { // // Example: // - // - The organization `organizationA` contains two projects, `project1` - // and `project2`. - // - Assignments for all three entities (`organizationA`, `project1`, and - // `project2`) could all be created and mapped to the same or different - // reservations. + // * The organization `organizationA` contains two projects, `project1` + // and `project2`. + // * Assignments for all three entities (`organizationA`, `project1`, and + // `project2`) could all be created and mapped to the same or different + // reservations. // // "None" assignments represent an absence of the assignment. Projects // assigned to None use on-demand pricing. To create a "None" assignment, use @@ -4337,12 +4324,12 @@ type ReservationServiceServer interface { // // Example: // - // - Organization `organizationA` contains two projects, `project1` and - // `project2`. - // - Reservation `res1` exists and was created previously. - // - CreateAssignment was used previously to define the following - // associations between entities and reservations: `` - // and `` + // * Organization `organizationA` contains two projects, `project1` and + // `project2`. + // * Reservation `res1` exists and was created previously. + // * CreateAssignment was used previously to define the following + // associations between entities and reservations: `` + // and `` // // In this example, ListAssignments will just return the above two assignments // for reservation `res1`, and no expansion/merge will happen. @@ -4357,12 +4344,12 @@ type ReservationServiceServer interface { // // Example: // - // - Organization `organizationA` contains two projects, `project1` and - // `project2`. - // - Reservation `res1` exists and was created previously. - // - CreateAssignment was used previously to define the following - // associations between entities and reservations: `` - // and `` + // * Organization `organizationA` contains two projects, `project1` and + // `project2`. + // * Reservation `res1` exists and was created previously. + // * CreateAssignment was used previously to define the following + // associations between entities and reservations: `` + // and `` // // In this example, deletion of the `` assignment won't // affect the other assignment ``. After said deletion, @@ -4373,10 +4360,10 @@ type ReservationServiceServer interface { // Deprecated: Looks up assignments for a specified resource for a particular // region. If the request is about a project: // - // 1. Assignments created on the project will be returned if they exist. - // 2. Otherwise assignments created on the closest ancestor will be - // returned. - // 3. Assignments for different JobTypes will all be returned. + // 1. Assignments created on the project will be returned if they exist. + // 2. Otherwise assignments created on the closest ancestor will be + // returned. + // 3. Assignments for different JobTypes will all be returned. // // The same logic applies if the request is about a folder. // @@ -4386,10 +4373,10 @@ type ReservationServiceServer interface { // Comparing to ListAssignments, there are some behavior // differences: // - // 1. permission on the assignee will be verified in this API. - // 2. Hierarchy lookup (project->folder->organization) happens in this API. - // 3. Parent here is `projects/*/locations/*`, instead of - // `projects/*/locations/*reservations/*`. + // 1. permission on the assignee will be verified in this API. + // 2. Hierarchy lookup (project->folder->organization) happens in this API. + // 3. Parent here is `projects/*/locations/*`, instead of + // `projects/*/locations/*reservations/*`. // // **Note** "-" cannot be used for projects // nor locations. @@ -4397,10 +4384,10 @@ type ReservationServiceServer interface { // Looks up assignments for a specified resource for a particular region. // If the request is about a project: // - // 1. Assignments created on the project will be returned if they exist. - // 2. Otherwise assignments created on the closest ancestor will be - // returned. - // 3. Assignments for different JobTypes will all be returned. + // 1. Assignments created on the project will be returned if they exist. + // 2. Otherwise assignments created on the closest ancestor will be + // returned. + // 3. Assignments for different JobTypes will all be returned. // // The same logic applies if the request is about a folder. // @@ -4410,10 +4397,10 @@ type ReservationServiceServer interface { // Comparing to ListAssignments, there are some behavior // differences: // - // 1. permission on the assignee will be verified in this API. - // 2. Hierarchy lookup (project->folder->organization) happens in this API. - // 3. Parent here is `projects/*/locations/*`, instead of - // `projects/*/locations/*reservations/*`. + // 1. permission on the assignee will be verified in this API. + // 2. Hierarchy lookup (project->folder->organization) happens in this API. + // 3. Parent here is `projects/*/locations/*`, instead of + // `projects/*/locations/*reservations/*`. SearchAllAssignments(context.Context, *SearchAllAssignmentsRequest) (*SearchAllAssignmentsResponse, error) // Moves an assignment under a new reservation. // diff --git a/bigquery/storage/apiv1/big_query_read_client.go b/bigquery/storage/apiv1/big_query_read_client.go index b791337696a3..704c32397049 100644 --- a/bigquery/storage/apiv1/big_query_read_client.go +++ b/bigquery/storage/apiv1/big_query_read_client.go @@ -17,20 +17,26 @@ package storage import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" storagepb "cloud.google.com/go/bigquery/storage/apiv1/storagepb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" ) var newBigQueryReadClientHook clientHook @@ -94,6 +100,43 @@ func defaultBigQueryReadCallOptions() *BigQueryReadCallOptions { } } +func defaultBigQueryReadRESTCallOptions() *BigQueryReadCallOptions { + return &BigQueryReadCallOptions{ + CreateReadSession: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + ReadRows: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + SplitReadStream: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + } +} + // internalBigQueryReadClient is an interface that defines the methods available from BigQuery Storage API. type internalBigQueryReadClient interface { Close() error @@ -274,6 +317,76 @@ func (c *bigQueryReadGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type bigQueryReadRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing BigQueryReadClient + CallOptions **BigQueryReadCallOptions +} + +// NewBigQueryReadRESTClient creates a new big query read rest client. +// +// BigQuery Read API. +// +// The Read API can be used to read data from BigQuery. +func NewBigQueryReadRESTClient(ctx context.Context, opts ...option.ClientOption) (*BigQueryReadClient, error) { + clientOpts := append(defaultBigQueryReadRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultBigQueryReadRESTCallOptions() + c := &bigQueryReadRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &BigQueryReadClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultBigQueryReadRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://bigquerystorage.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://bigquerystorage.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://bigquerystorage.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *bigQueryReadRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *bigQueryReadRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *bigQueryReadRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *bigQueryReadGRPCClient) CreateReadSession(ctx context.Context, req *storagepb.CreateReadSessionRequest, opts ...gax.CallOption) (*storagepb.ReadSession, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) @@ -333,3 +446,264 @@ func (c *bigQueryReadGRPCClient) SplitReadStream(ctx context.Context, req *stora } return resp, nil } + +// CreateReadSession creates a new read session. A read session divides the contents of a +// BigQuery table into one or more streams, which can then be used to read +// data from the table. The read session also specifies properties of the +// data to be read, such as a list of columns or a push-down filter describing +// the rows to be returned. +// +// A particular row can be read by at most one stream. When the caller has +// reached the end of each stream in the session, then all the data in the +// table has been read. +// +// Data is assigned to each stream such that roughly the same number of +// rows can be read from each stream. Because the server-side unit for +// assigning data is collections of rows, the API does not guarantee that +// each stream will return the same number or rows. Additionally, the +// limits are enforced based on the number of pre-filtered rows, so some +// filters can lead to lopsided assignments. +// +// Read sessions automatically expire 6 hours after they are created and do +// not require manual clean-up by the caller. +func (c *bigQueryReadRESTClient) CreateReadSession(ctx context.Context, req *storagepb.CreateReadSessionRequest, opts ...gax.CallOption) (*storagepb.ReadSession, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetReadSession().GetTable()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "read_session.table", url.QueryEscape(req.GetReadSession().GetTable()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateReadSession[0:len((*c.CallOptions).CreateReadSession):len((*c.CallOptions).CreateReadSession)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &storagepb.ReadSession{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ReadRows reads rows from the stream in the format prescribed by the ReadSession. +// Each response contains one or more table rows, up to a maximum of 100 MiB +// per response; read requests which attempt to read individual rows larger +// than 100 MiB will fail. +// +// Each request also returns a set of stream statistics reflecting the current +// state of the stream. +func (c *bigQueryReadRESTClient) ReadRows(ctx context.Context, req *storagepb.ReadRowsRequest, opts ...gax.CallOption) (storagepb.BigQueryRead_ReadRowsClient, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetReadStream()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetOffset() != 0 { + params.Add("offset", fmt.Sprintf("%v", req.GetOffset())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "read_stream", url.QueryEscape(req.GetReadStream()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + var streamClient *readRowsRESTClient + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + streamClient = &readRowsRESTClient{ + ctx: ctx, + md: metadata.MD(httpRsp.Header), + stream: gax.NewProtoJSONStreamReader(httpRsp.Body, (&storagepb.ReadRowsResponse{}).ProtoReflect().Type()), + } + return nil + }, opts...) + + return streamClient, e +} + +// readRowsRESTClient is the stream client used to consume the server stream created by +// the REST implementation of ReadRows. +type readRowsRESTClient struct { + ctx context.Context + md metadata.MD + stream *gax.ProtoJSONStream +} + +func (c *readRowsRESTClient) Recv() (*storagepb.ReadRowsResponse, error) { + if err := c.ctx.Err(); err != nil { + defer c.stream.Close() + return nil, err + } + msg, err := c.stream.Recv() + if err != nil { + defer c.stream.Close() + return nil, err + } + res := msg.(*storagepb.ReadRowsResponse) + return res, nil +} + +func (c *readRowsRESTClient) Header() (metadata.MD, error) { + return c.md, nil +} + +func (c *readRowsRESTClient) Trailer() metadata.MD { + return c.md +} + +func (c *readRowsRESTClient) CloseSend() error { + // This is a no-op to fulfill the interface. + return fmt.Errorf("this method is not implemented for a server-stream") +} + +func (c *readRowsRESTClient) Context() context.Context { + return c.ctx +} + +func (c *readRowsRESTClient) SendMsg(m interface{}) error { + // This is a no-op to fulfill the interface. + return fmt.Errorf("this method is not implemented for a server-stream") +} + +func (c *readRowsRESTClient) RecvMsg(m interface{}) error { + // This is a no-op to fulfill the interface. + return fmt.Errorf("this method is not implemented, use Recv") +} + +// SplitReadStream splits a given ReadStream into two ReadStream objects. These +// ReadStream objects are referred to as the primary and the residual +// streams of the split. The original ReadStream can still be read from in +// the same manner as before. Both of the returned ReadStream objects can +// also be read from, and the rows returned by both child streams will be +// the same as the rows read from the original stream. +// +// Moreover, the two child streams will be allocated back-to-back in the +// original ReadStream. Concretely, it is guaranteed that for streams +// original, primary, and residual, that original[0-j] = primary[0-j] and +// original[j-n] = residual[0-m] once the streams have been read to +// completion. +func (c *bigQueryReadRESTClient) SplitReadStream(ctx context.Context, req *storagepb.SplitReadStreamRequest, opts ...gax.CallOption) (*storagepb.SplitReadStreamResponse, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFraction() != 0 { + params.Add("fraction", fmt.Sprintf("%v", req.GetFraction())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SplitReadStream[0:len((*c.CallOptions).SplitReadStream):len((*c.CallOptions).SplitReadStream)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &storagepb.SplitReadStreamResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} diff --git a/bigquery/storage/apiv1/big_query_read_client_example_test.go b/bigquery/storage/apiv1/big_query_read_client_example_test.go index a80b106d54c4..1846aa3b116e 100644 --- a/bigquery/storage/apiv1/big_query_read_client_example_test.go +++ b/bigquery/storage/apiv1/big_query_read_client_example_test.go @@ -40,6 +40,23 @@ func ExampleNewBigQueryReadClient() { _ = c } +func ExampleNewBigQueryReadRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := storage.NewBigQueryReadRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleBigQueryReadClient_CreateReadSession() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/bigquery/storage/apiv1/big_query_write_client.go b/bigquery/storage/apiv1/big_query_write_client.go index d4a79051cca9..cd318abca03b 100644 --- a/bigquery/storage/apiv1/big_query_write_client.go +++ b/bigquery/storage/apiv1/big_query_write_client.go @@ -17,20 +17,26 @@ package storage import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" storagepb "cloud.google.com/go/bigquery/storage/apiv1/storagepb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" ) var newBigQueryWriteClientHook clientHook @@ -134,6 +140,77 @@ func defaultBigQueryWriteCallOptions() *BigQueryWriteCallOptions { } } +func defaultBigQueryWriteRESTCallOptions() *BigQueryWriteCallOptions { + return &BigQueryWriteCallOptions{ + CreateWriteStream: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 10000 * time.Millisecond, + Max: 120000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable, + http.StatusTooManyRequests) + }), + }, + AppendRows: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetWriteStream: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + FinalizeWriteStream: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + BatchCommitWriteStreams: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + FlushRows: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + } +} + // internalBigQueryWriteClient is an interface that defines the methods available from BigQuery Storage API. type internalBigQueryWriteClient interface { Close() error @@ -228,6 +305,8 @@ func (c *BigQueryWriteClient) CreateWriteStream(ctx context.Context, req *storag // For PENDING streams, data is not made visible until the stream itself is // finalized (via the FinalizeWriteStream rpc), and the stream is explicitly // committed via the BatchCommitWriteStreams rpc. +// +// This method is not supported for the REST transport. func (c *BigQueryWriteClient) AppendRows(ctx context.Context, opts ...gax.CallOption) (storagepb.BigQueryWrite_AppendRowsClient, error) { return c.internalClient.AppendRows(ctx, opts...) } @@ -351,6 +430,79 @@ func (c *bigQueryWriteGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type bigQueryWriteRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing BigQueryWriteClient + CallOptions **BigQueryWriteCallOptions +} + +// NewBigQueryWriteRESTClient creates a new big query write rest client. +// +// BigQuery Write API. +// +// The Write API can be used to write data to BigQuery. +// +// For supplementary information about the Write API, see: +// https://cloud.google.com/bigquery/docs/write-api (at https://cloud.google.com/bigquery/docs/write-api) +func NewBigQueryWriteRESTClient(ctx context.Context, opts ...option.ClientOption) (*BigQueryWriteClient, error) { + clientOpts := append(defaultBigQueryWriteRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultBigQueryWriteRESTCallOptions() + c := &bigQueryWriteRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &BigQueryWriteClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultBigQueryWriteRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://bigquerystorage.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://bigquerystorage.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://bigquerystorage.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *bigQueryWriteRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *bigQueryWriteRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *bigQueryWriteRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *bigQueryWriteGRPCClient) CreateWriteStream(ctx context.Context, req *storagepb.CreateWriteStreamRequest, opts ...gax.CallOption) (*storagepb.WriteStream, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 1200000*time.Millisecond) @@ -475,3 +627,378 @@ func (c *bigQueryWriteGRPCClient) FlushRows(ctx context.Context, req *storagepb. } return resp, nil } + +// CreateWriteStream creates a write stream to the given table. +// Additionally, every table has a special stream named ‘_default’ +// to which data can be written. This stream doesn’t need to be created using +// CreateWriteStream. It is a stream that can be used simultaneously by any +// number of clients. Data written to this stream is considered committed as +// soon as an acknowledgement is received. +func (c *bigQueryWriteRESTClient) CreateWriteStream(ctx context.Context, req *storagepb.CreateWriteStreamRequest, opts ...gax.CallOption) (*storagepb.WriteStream, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetWriteStream() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateWriteStream[0:len((*c.CallOptions).CreateWriteStream):len((*c.CallOptions).CreateWriteStream)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &storagepb.WriteStream{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// AppendRows appends data to the given stream. +// +// If offset is specified, the offset is checked against the end of +// stream. The server returns OUT_OF_RANGE in AppendRowsResponse if an +// attempt is made to append to an offset beyond the current end of the stream +// or ALREADY_EXISTS if user provides an offset that has already been +// written to. User can retry with adjusted offset within the same RPC +// connection. If offset is not specified, append happens at the end of the +// stream. +// +// The response contains an optional offset at which the append +// happened. No offset information will be returned for appends to a +// default stream. +// +// Responses are received in the same order in which requests are sent. +// There will be one response for each successful inserted request. Responses +// may optionally embed error information if the originating AppendRequest was +// not successfully processed. +// +// The specifics of when successfully appended data is made visible to the +// table are governed by the type of stream: +// +// For COMMITTED streams (which includes the default stream), data is +// visible immediately upon successful append. +// +// For BUFFERED streams, data is made visible via a subsequent FlushRows +// rpc which advances a cursor to a newer offset in the stream. +// +// For PENDING streams, data is not made visible until the stream itself is +// finalized (via the FinalizeWriteStream rpc), and the stream is explicitly +// committed via the BatchCommitWriteStreams rpc. +// +// This method is not supported for the REST transport. +func (c *bigQueryWriteRESTClient) AppendRows(ctx context.Context, opts ...gax.CallOption) (storagepb.BigQueryWrite_AppendRowsClient, error) { + return nil, fmt.Errorf("AppendRows not yet supported for REST clients") +} + +// GetWriteStream gets information about a write stream. +func (c *bigQueryWriteRESTClient) GetWriteStream(ctx context.Context, req *storagepb.GetWriteStreamRequest, opts ...gax.CallOption) (*storagepb.WriteStream, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetWriteStream[0:len((*c.CallOptions).GetWriteStream):len((*c.CallOptions).GetWriteStream)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &storagepb.WriteStream{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// FinalizeWriteStream finalize a write stream so that no new data can be appended to the +// stream. Finalize is not supported on the ‘_default’ stream. +func (c *bigQueryWriteRESTClient) FinalizeWriteStream(ctx context.Context, req *storagepb.FinalizeWriteStreamRequest, opts ...gax.CallOption) (*storagepb.FinalizeWriteStreamResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).FinalizeWriteStream[0:len((*c.CallOptions).FinalizeWriteStream):len((*c.CallOptions).FinalizeWriteStream)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &storagepb.FinalizeWriteStreamResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// BatchCommitWriteStreams atomically commits a group of PENDING streams that belong to the same +// parent table. +// +// Streams must be finalized before commit and cannot be committed multiple +// times. Once a stream is committed, data in the stream becomes available +// for read operations. +func (c *bigQueryWriteRESTClient) BatchCommitWriteStreams(ctx context.Context, req *storagepb.BatchCommitWriteStreamsRequest, opts ...gax.CallOption) (*storagepb.BatchCommitWriteStreamsResponse, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if items := req.GetWriteStreams(); len(items) > 0 { + for _, item := range items { + params.Add("writeStreams", fmt.Sprintf("%v", item)) + } + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).BatchCommitWriteStreams[0:len((*c.CallOptions).BatchCommitWriteStreams):len((*c.CallOptions).BatchCommitWriteStreams)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &storagepb.BatchCommitWriteStreamsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// FlushRows flushes rows to a BUFFERED stream. +// +// If users are appending rows to BUFFERED stream, flush operation is +// required in order for the rows to become available for reading. A +// Flush operation flushes up to any previously flushed offset in a BUFFERED +// stream, to the offset specified in the request. +// +// Flush is not supported on the _default stream, since it is not BUFFERED. +func (c *bigQueryWriteRESTClient) FlushRows(ctx context.Context, req *storagepb.FlushRowsRequest, opts ...gax.CallOption) (*storagepb.FlushRowsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetWriteStream()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "write_stream", url.QueryEscape(req.GetWriteStream()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).FlushRows[0:len((*c.CallOptions).FlushRows):len((*c.CallOptions).FlushRows)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &storagepb.FlushRowsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} diff --git a/bigquery/storage/apiv1/big_query_write_client_example_test.go b/bigquery/storage/apiv1/big_query_write_client_example_test.go index 2c3047e7702a..bbe1841379db 100644 --- a/bigquery/storage/apiv1/big_query_write_client_example_test.go +++ b/bigquery/storage/apiv1/big_query_write_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewBigQueryWriteClient() { _ = c } +func ExampleNewBigQueryWriteRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := storage.NewBigQueryWriteRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleBigQueryWriteClient_CreateWriteStream() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/bigquery/storage/apiv1/doc.go b/bigquery/storage/apiv1/doc.go index aecbe4f468d6..e2e2aa38e33b 100644 --- a/bigquery/storage/apiv1/doc.go +++ b/bigquery/storage/apiv1/doc.go @@ -78,6 +78,8 @@ package storage // import "cloud.google.com/go/bigquery/storage/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -168,3 +170,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/bigquery/storage/apiv1/gapic_metadata.json b/bigquery/storage/apiv1/gapic_metadata.json index 1b8e7b14b695..027c3ae1f1d5 100644 --- a/bigquery/storage/apiv1/gapic_metadata.json +++ b/bigquery/storage/apiv1/gapic_metadata.json @@ -26,6 +26,26 @@ ] } } + }, + "rest": { + "libraryClient": "BigQueryReadClient", + "rpcs": { + "CreateReadSession": { + "methods": [ + "CreateReadSession" + ] + }, + "ReadRows": { + "methods": [ + "ReadRows" + ] + }, + "SplitReadStream": { + "methods": [ + "SplitReadStream" + ] + } + } } } }, @@ -65,6 +85,41 @@ ] } } + }, + "rest": { + "libraryClient": "BigQueryWriteClient", + "rpcs": { + "AppendRows": { + "methods": [ + "AppendRows" + ] + }, + "BatchCommitWriteStreams": { + "methods": [ + "BatchCommitWriteStreams" + ] + }, + "CreateWriteStream": { + "methods": [ + "CreateWriteStream" + ] + }, + "FinalizeWriteStream": { + "methods": [ + "FinalizeWriteStream" + ] + }, + "FlushRows": { + "methods": [ + "FlushRows" + ] + }, + "GetWriteStream": { + "methods": [ + "GetWriteStream" + ] + } + } } } } diff --git a/bigquery/storage/apiv1/storagepb/annotations.pb.go b/bigquery/storage/apiv1/storagepb/annotations.pb.go index 9247ca73d96d..4994e7aef0e3 100644 --- a/bigquery/storage/apiv1/storagepb/annotations.pb.go +++ b/bigquery/storage/apiv1/storagepb/annotations.pb.go @@ -1,7 +1,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/bigquery/storage/v1/annotations.proto package storagepb diff --git a/bigquery/storage/apiv1/storagepb/arrow.pb.go b/bigquery/storage/apiv1/storagepb/arrow.pb.go index 4afd9408089e..988d3ef12a84 100644 --- a/bigquery/storage/apiv1/storagepb/arrow.pb.go +++ b/bigquery/storage/apiv1/storagepb/arrow.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/bigquery/storage/v1/arrow.proto package storagepb diff --git a/bigquery/storage/apiv1/storagepb/avro.pb.go b/bigquery/storage/apiv1/storagepb/avro.pb.go index 5bb0cc1d83e7..2c4005ce6a38 100644 --- a/bigquery/storage/apiv1/storagepb/avro.pb.go +++ b/bigquery/storage/apiv1/storagepb/avro.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/bigquery/storage/v1/avro.proto package storagepb diff --git a/bigquery/storage/apiv1/storagepb/protobuf.pb.go b/bigquery/storage/apiv1/storagepb/protobuf.pb.go index ceeaf212dc84..59cce70d0ff2 100644 --- a/bigquery/storage/apiv1/storagepb/protobuf.pb.go +++ b/bigquery/storage/apiv1/storagepb/protobuf.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/bigquery/storage/v1/protobuf.proto package storagepb diff --git a/bigquery/storage/apiv1/storagepb/storage.pb.go b/bigquery/storage/apiv1/storagepb/storage.pb.go index b3d3cde9ae88..968452be5872 100644 --- a/bigquery/storage/apiv1/storagepb/storage.pb.go +++ b/bigquery/storage/apiv1/storagepb/storage.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/bigquery/storage/v1/storage.proto package storagepb @@ -497,7 +497,6 @@ type ReadRowsResponse struct { // Row data is returned in format specified during session creation. // // Types that are assignable to Rows: - // // *ReadRowsResponse_AvroRows // *ReadRowsResponse_ArrowRecordBatch Rows isReadRowsResponse_Rows `protobuf_oneof:"rows"` @@ -515,7 +514,6 @@ type ReadRowsResponse struct { // RPC. // // Types that are assignable to Schema: - // // *ReadRowsResponse_AvroSchema // *ReadRowsResponse_ArrowSchema Schema isReadRowsResponse_Schema `protobuf_oneof:"schema"` @@ -873,7 +871,6 @@ type AppendRowsRequest struct { // initial request. // // Types that are assignable to Rows: - // // *AppendRowsRequest_ProtoRows Rows isAppendRowsRequest_Rows `protobuf_oneof:"rows"` // Id set by client to annotate its identity. Only initial request setting is @@ -992,7 +989,6 @@ type AppendRowsResponse struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Response: - // // *AppendRowsResponse_AppendResult_ // *AppendRowsResponse_Error Response isAppendRowsResponse_Response `protobuf_oneof:"response"` diff --git a/bigquery/storage/apiv1/storagepb/stream.pb.go b/bigquery/storage/apiv1/storagepb/stream.pb.go index 0310e190f990..eb4ea631542c 100644 --- a/bigquery/storage/apiv1/storagepb/stream.pb.go +++ b/bigquery/storage/apiv1/storagepb/stream.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/bigquery/storage/v1/stream.proto package storagepb @@ -278,7 +278,6 @@ type ReadSession struct { // the selected fields. // // Types that are assignable to Schema: - // // *ReadSession_AvroSchema // *ReadSession_ArrowSchema Schema isReadSession_Schema `protobuf_oneof:"schema"` @@ -674,40 +673,38 @@ type ReadSession_TableReadOptions struct { // // As an example, consider a table with the following schema: // - // { - // "name": "struct_field", - // "type": "RECORD", - // "mode": "NULLABLE", - // "fields": [ - // { - // "name": "string_field1", - // "type": "STRING", - // + // { + // "name": "struct_field", + // "type": "RECORD", + // "mode": "NULLABLE", + // "fields": [ + // { + // "name": "string_field1", + // "type": "STRING", // . "mode": "NULLABLE" - // - // }, - // { - // "name": "string_field2", - // "type": "STRING", - // "mode": "NULLABLE" - // } - // ] - // } + // }, + // { + // "name": "string_field2", + // "type": "STRING", + // "mode": "NULLABLE" + // } + // ] + // } // // Specifying "struct_field" in the selected fields list will result in a // read session schema with the following logical structure: // - // struct_field { - // string_field1 - // string_field2 - // } + // struct_field { + // string_field1 + // string_field2 + // } // // Specifying "struct_field.string_field1" in the selected fields list will // result in a read session schema with the following logical structure: // - // struct_field { - // string_field1 - // } + // struct_field { + // string_field1 + // } // // The order of the fields in the read session schema is derived from the // table schema and does not correspond to the order in which the fields are @@ -717,16 +714,14 @@ type ReadSession_TableReadOptions struct { // Aggregates are not supported. // // Examples: "int_field > 5" - // - // "date_field = CAST('2014-9-27' as DATE)" - // "nullable_field is not NULL" - // "st_equals(geo_field, st_geofromtext("POINT(2, 2)"))" - // "numeric_field BETWEEN 1.0 AND 5.0" + // "date_field = CAST('2014-9-27' as DATE)" + // "nullable_field is not NULL" + // "st_equals(geo_field, st_geofromtext("POINT(2, 2)"))" + // "numeric_field BETWEEN 1.0 AND 5.0" // // Restricted to a maximum length for 1 MB. RowRestriction string `protobuf:"bytes,2,opt,name=row_restriction,json=rowRestriction,proto3" json:"row_restriction,omitempty"` // Types that are assignable to OutputFormatSerializationOptions: - // // *ReadSession_TableReadOptions_ArrowSerializationOptions // *ReadSession_TableReadOptions_AvroSerializationOptions OutputFormatSerializationOptions isReadSession_TableReadOptions_OutputFormatSerializationOptions `protobuf_oneof:"output_format_serialization_options"` diff --git a/bigquery/storage/apiv1/storagepb/table.pb.go b/bigquery/storage/apiv1/storagepb/table.pb.go index 3db7756936fd..42ca9f542037 100644 --- a/bigquery/storage/apiv1/storagepb/table.pb.go +++ b/bigquery/storage/apiv1/storagepb/table.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/bigquery/storage/v1/table.proto package storagepb @@ -287,18 +287,18 @@ type TableFieldSchema struct { // // Values of this NUMERIC or BIGNUMERIC field must be in this range when: // - // - Precision (P) and scale (S) are specified: - // [-10^(P-S) + 10^(-S), 10^(P-S) - 10^(-S)] - // - Precision (P) is specified but not scale (and thus scale is - // interpreted to be equal to zero): - // [-10^P + 1, 10^P - 1]. + // * Precision (P) and scale (S) are specified: + // [-10^(P-S) + 10^(-S), 10^(P-S) - 10^(-S)] + // * Precision (P) is specified but not scale (and thus scale is + // interpreted to be equal to zero): + // [-10^P + 1, 10^P - 1]. // // Acceptable values for precision and scale if both are specified: // - // - If type = "NUMERIC": - // 1 <= precision - scale <= 29 and 0 <= scale <= 9. - // - If type = "BIGNUMERIC": - // 1 <= precision - scale <= 38 and 0 <= scale <= 38. + // * If type = "NUMERIC": + // 1 <= precision - scale <= 29 and 0 <= scale <= 9. + // * If type = "BIGNUMERIC": + // 1 <= precision - scale <= 38 and 0 <= scale <= 38. // // Acceptable values for precision if only precision is specified but not // scale (and thus scale is interpreted to be equal to zero): diff --git a/bigquery/storage/apiv1beta1/storagepb/arrow.pb.go b/bigquery/storage/apiv1beta1/storagepb/arrow.pb.go index d232f761ca76..2d2be3fea836 100644 --- a/bigquery/storage/apiv1beta1/storagepb/arrow.pb.go +++ b/bigquery/storage/apiv1beta1/storagepb/arrow.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/bigquery/storage/v1beta1/arrow.proto package storagepb diff --git a/bigquery/storage/apiv1beta1/storagepb/avro.pb.go b/bigquery/storage/apiv1beta1/storagepb/avro.pb.go index 5d7feef4406c..abda4ceec255 100644 --- a/bigquery/storage/apiv1beta1/storagepb/avro.pb.go +++ b/bigquery/storage/apiv1beta1/storagepb/avro.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/bigquery/storage/v1beta1/avro.proto package storagepb diff --git a/bigquery/storage/apiv1beta1/storagepb/read_options.pb.go b/bigquery/storage/apiv1beta1/storagepb/read_options.pb.go index a7679fb0bbbb..668339a82ac6 100644 --- a/bigquery/storage/apiv1beta1/storagepb/read_options.pb.go +++ b/bigquery/storage/apiv1beta1/storagepb/read_options.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/bigquery/storage/v1beta1/read_options.proto package storagepb @@ -50,11 +50,10 @@ type TableReadOptions struct { // a query. Aggregates are not supported. // // Examples: "int_field > 5" - // - // "date_field = CAST('2014-9-27' as DATE)" - // "nullable_field is not NULL" - // "st_equals(geo_field, st_geofromtext("POINT(2, 2)"))" - // "numeric_field BETWEEN 1.0 AND 5.0" + // "date_field = CAST('2014-9-27' as DATE)" + // "nullable_field is not NULL" + // "st_equals(geo_field, st_geofromtext("POINT(2, 2)"))" + // "numeric_field BETWEEN 1.0 AND 5.0" RowRestriction string `protobuf:"bytes,2,opt,name=row_restriction,json=rowRestriction,proto3" json:"row_restriction,omitempty"` } diff --git a/bigquery/storage/apiv1beta1/storagepb/storage.pb.go b/bigquery/storage/apiv1beta1/storagepb/storage.pb.go index 95554c307eb6..26ba67b24aa0 100644 --- a/bigquery/storage/apiv1beta1/storagepb/storage.pb.go +++ b/bigquery/storage/apiv1beta1/storagepb/storage.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/bigquery/storage/v1beta1/storage.proto package storagepb @@ -281,7 +281,6 @@ type ReadSession struct { // the selected fields. // // Types that are assignable to Schema: - // // *ReadSession_AvroSchema // *ReadSession_ArrowSchema Schema isReadSession_Schema `protobuf_oneof:"schema"` @@ -788,7 +787,6 @@ type ReadRowsResponse struct { // Row data is returned in format specified during session creation. // // Types that are assignable to Rows: - // // *ReadRowsResponse_AvroRows // *ReadRowsResponse_ArrowRecordBatch Rows isReadRowsResponse_Rows `protobuf_oneof:"rows"` diff --git a/bigquery/storage/apiv1beta1/storagepb/table_reference.pb.go b/bigquery/storage/apiv1beta1/storagepb/table_reference.pb.go index 441af0dfdfd3..454231eaa97c 100644 --- a/bigquery/storage/apiv1beta1/storagepb/table_reference.pb.go +++ b/bigquery/storage/apiv1beta1/storagepb/table_reference.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/bigquery/storage/v1beta1/table_reference.proto package storagepb diff --git a/bigquery/storage/apiv1beta2/big_query_write_client.go b/bigquery/storage/apiv1beta2/big_query_write_client.go index 52602e1febe9..4c32c5773226 100644 --- a/bigquery/storage/apiv1beta2/big_query_write_client.go +++ b/bigquery/storage/apiv1beta2/big_query_write_client.go @@ -292,6 +292,8 @@ func (c *BigQueryWriteClient) CreateWriteStream(ctx context.Context, req *storag // // If the stream is of PENDING type, data will only be available for read // operations after the stream is committed. +// +// This method is not supported for the REST transport. func (c *BigQueryWriteClient) AppendRows(ctx context.Context, opts ...gax.CallOption) (storagepb.BigQueryWrite_AppendRowsClient, error) { return c.internalClient.AppendRows(ctx, opts...) } @@ -688,6 +690,8 @@ func (c *bigQueryWriteRESTClient) CreateWriteStream(ctx context.Context, req *st // // If the stream is of PENDING type, data will only be available for read // operations after the stream is committed. +// +// This method is not supported for the REST transport. func (c *bigQueryWriteRESTClient) AppendRows(ctx context.Context, opts ...gax.CallOption) (storagepb.BigQueryWrite_AppendRowsClient, error) { return nil, fmt.Errorf("AppendRows not yet supported for REST clients") } @@ -824,8 +828,10 @@ func (c *bigQueryWriteRESTClient) BatchCommitWriteStreams(ctx context.Context, r baseUrl.Path += fmt.Sprintf("/v1beta2/%v", req.GetParent()) params := url.Values{} - if req.GetWriteStreams() != nil { - params.Add("writeStreams", fmt.Sprintf("%v", req.GetWriteStreams())) + if items := req.GetWriteStreams(); len(items) > 0 { + for _, item := range items { + params.Add("writeStreams", fmt.Sprintf("%v", item)) + } } baseUrl.RawQuery = params.Encode() diff --git a/bigquery/storage/apiv1beta2/storagepb/arrow.pb.go b/bigquery/storage/apiv1beta2/storagepb/arrow.pb.go index 665cc9dc0224..bdb113cefd80 100644 --- a/bigquery/storage/apiv1beta2/storagepb/arrow.pb.go +++ b/bigquery/storage/apiv1beta2/storagepb/arrow.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/bigquery/storage/v1beta2/arrow.proto package storagepb diff --git a/bigquery/storage/apiv1beta2/storagepb/avro.pb.go b/bigquery/storage/apiv1beta2/storagepb/avro.pb.go index f3e42cdecb1a..f98b278387f9 100644 --- a/bigquery/storage/apiv1beta2/storagepb/avro.pb.go +++ b/bigquery/storage/apiv1beta2/storagepb/avro.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/bigquery/storage/v1beta2/avro.proto package storagepb diff --git a/bigquery/storage/apiv1beta2/storagepb/protobuf.pb.go b/bigquery/storage/apiv1beta2/storagepb/protobuf.pb.go index 240ec996d8c9..d5c996e697ce 100644 --- a/bigquery/storage/apiv1beta2/storagepb/protobuf.pb.go +++ b/bigquery/storage/apiv1beta2/storagepb/protobuf.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/bigquery/storage/v1beta2/protobuf.proto package storagepb diff --git a/bigquery/storage/apiv1beta2/storagepb/storage.pb.go b/bigquery/storage/apiv1beta2/storagepb/storage.pb.go index 0caf3d2ed5f0..4dde23ccb847 100644 --- a/bigquery/storage/apiv1beta2/storagepb/storage.pb.go +++ b/bigquery/storage/apiv1beta2/storagepb/storage.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/bigquery/storage/v1beta2/storage.proto package storagepb @@ -359,7 +359,6 @@ type ReadRowsResponse struct { // Row data is returned in format specified during session creation. // // Types that are assignable to Rows: - // // *ReadRowsResponse_AvroRows // *ReadRowsResponse_ArrowRecordBatch Rows isReadRowsResponse_Rows `protobuf_oneof:"rows"` @@ -377,7 +376,6 @@ type ReadRowsResponse struct { // RPC. // // Types that are assignable to Schema: - // // *ReadRowsResponse_AvroSchema // *ReadRowsResponse_ArrowSchema Schema isReadRowsResponse_Schema `protobuf_oneof:"schema"` @@ -720,7 +718,6 @@ type AppendRowsRequest struct { // initial request. // // Types that are assignable to Rows: - // // *AppendRowsRequest_ProtoRows Rows isAppendRowsRequest_Rows `protobuf_oneof:"rows"` // Id set by client to annotate its identity. Only initial request setting is @@ -813,7 +810,6 @@ type AppendRowsResponse struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Response: - // // *AppendRowsResponse_AppendResult_ // *AppendRowsResponse_Error Response isAppendRowsResponse_Response `protobuf_oneof:"response"` diff --git a/bigquery/storage/apiv1beta2/storagepb/stream.pb.go b/bigquery/storage/apiv1beta2/storagepb/stream.pb.go index 6d539f3c429c..f814dbff2d5a 100644 --- a/bigquery/storage/apiv1beta2/storagepb/stream.pb.go +++ b/bigquery/storage/apiv1beta2/storagepb/stream.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/bigquery/storage/v1beta2/stream.proto package storagepb @@ -169,7 +169,6 @@ type ReadSession struct { // the selected fields. // // Types that are assignable to Schema: - // // *ReadSession_AvroSchema // *ReadSession_ArrowSchema Schema isReadSession_Schema `protobuf_oneof:"schema"` @@ -518,11 +517,10 @@ type ReadSession_TableReadOptions struct { // Aggregates are not supported. // // Examples: "int_field > 5" - // - // "date_field = CAST('2014-9-27' as DATE)" - // "nullable_field is not NULL" - // "st_equals(geo_field, st_geofromtext("POINT(2, 2)"))" - // "numeric_field BETWEEN 1.0 AND 5.0" + // "date_field = CAST('2014-9-27' as DATE)" + // "nullable_field is not NULL" + // "st_equals(geo_field, st_geofromtext("POINT(2, 2)"))" + // "numeric_field BETWEEN 1.0 AND 5.0" // // Restricted to a maximum length for 1 MB. RowRestriction string `protobuf:"bytes,2,opt,name=row_restriction,json=rowRestriction,proto3" json:"row_restriction,omitempty"` diff --git a/bigquery/storage/apiv1beta2/storagepb/table.pb.go b/bigquery/storage/apiv1beta2/storagepb/table.pb.go index bfc320100624..d38c94056b3b 100644 --- a/bigquery/storage/apiv1beta2/storagepb/table.pb.go +++ b/bigquery/storage/apiv1beta2/storagepb/table.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/bigquery/storage/v1beta2/table.proto package storagepb diff --git a/billing/apiv1/billingpb/cloud_billing.pb.go b/billing/apiv1/billingpb/cloud_billing.pb.go index c8e735d2f3c0..b7c7a58e0906 100644 --- a/billing/apiv1/billingpb/cloud_billing.pb.go +++ b/billing/apiv1/billingpb/cloud_billing.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/billing/v1/cloud_billing.proto package billingpb diff --git a/billing/apiv1/billingpb/cloud_catalog.pb.go b/billing/apiv1/billingpb/cloud_catalog.pb.go index 7456897c3761..20c40767376f 100644 --- a/billing/apiv1/billingpb/cloud_catalog.pb.go +++ b/billing/apiv1/billingpb/cloud_catalog.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/billing/v1/cloud_catalog.proto package billingpb diff --git a/billing/apiv1/cloud_billing_client.go b/billing/apiv1/cloud_billing_client.go index ef1877ad7677..5982f99c2886 100644 --- a/billing/apiv1/cloud_billing_client.go +++ b/billing/apiv1/cloud_billing_client.go @@ -17,22 +17,28 @@ package billing import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" billingpb "cloud.google.com/go/billing/apiv1/billingpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" iampb "google.golang.org/genproto/googleapis/iam/v1" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -178,6 +184,111 @@ func defaultCloudBillingCallOptions() *CloudBillingCallOptions { } } +func defaultCloudBillingRESTCallOptions() *CloudBillingCallOptions { + return &CloudBillingCallOptions{ + GetBillingAccount: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + ListBillingAccounts: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + UpdateBillingAccount: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + CreateBillingAccount: []gax.CallOption{}, + ListProjectBillingInfo: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + GetProjectBillingInfo: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + UpdateProjectBillingInfo: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + GetIamPolicy: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + SetIamPolicy: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + TestIamPermissions: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + } +} + // internalCloudBillingClient is an interface that defines the methods available from Cloud Billing API. type internalCloudBillingClient interface { Close() error @@ -431,6 +542,75 @@ func (c *cloudBillingGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type cloudBillingRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing CloudBillingClient + CallOptions **CloudBillingCallOptions +} + +// NewCloudBillingRESTClient creates a new cloud billing rest client. +// +// Retrieves the Google Cloud Console billing accounts and associates them with +// projects. +func NewCloudBillingRESTClient(ctx context.Context, opts ...option.ClientOption) (*CloudBillingClient, error) { + clientOpts := append(defaultCloudBillingRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultCloudBillingRESTCallOptions() + c := &cloudBillingRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &CloudBillingClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultCloudBillingRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://cloudbilling.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://cloudbilling.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://cloudbilling.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *cloudBillingRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *cloudBillingRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *cloudBillingRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *cloudBillingGRPCClient) GetBillingAccount(ctx context.Context, req *billingpb.GetBillingAccountRequest, opts ...gax.CallOption) (*billingpb.BillingAccount, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) @@ -693,6 +873,758 @@ func (c *cloudBillingGRPCClient) TestIamPermissions(ctx context.Context, req *ia return resp, nil } +// GetBillingAccount gets information about a billing account. The current authenticated user +// must be a viewer of the billing +// account (at https://cloud.google.com/billing/docs/how-to/billing-access). +func (c *cloudBillingRESTClient) GetBillingAccount(ctx context.Context, req *billingpb.GetBillingAccountRequest, opts ...gax.CallOption) (*billingpb.BillingAccount, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetBillingAccount[0:len((*c.CallOptions).GetBillingAccount):len((*c.CallOptions).GetBillingAccount)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &billingpb.BillingAccount{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListBillingAccounts lists the billing accounts that the current authenticated user has +// permission to +// view (at https://cloud.google.com/billing/docs/how-to/billing-access). +func (c *cloudBillingRESTClient) ListBillingAccounts(ctx context.Context, req *billingpb.ListBillingAccountsRequest, opts ...gax.CallOption) *BillingAccountIterator { + it := &BillingAccountIterator{} + req = proto.Clone(req).(*billingpb.ListBillingAccountsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*billingpb.BillingAccount, string, error) { + resp := &billingpb.ListBillingAccountsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/billingAccounts") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetBillingAccounts(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// UpdateBillingAccount updates a billing account’s fields. +// Currently the only field that can be edited is display_name. +// The current authenticated user must have the billing.accounts.update +// IAM permission, which is typically given to the +// administrator (at https://cloud.google.com/billing/docs/how-to/billing-access) +// of the billing account. +func (c *cloudBillingRESTClient) UpdateBillingAccount(ctx context.Context, req *billingpb.UpdateBillingAccountRequest, opts ...gax.CallOption) (*billingpb.BillingAccount, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetAccount() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateBillingAccount[0:len((*c.CallOptions).UpdateBillingAccount):len((*c.CallOptions).UpdateBillingAccount)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &billingpb.BillingAccount{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateBillingAccount this method creates billing +// subaccounts (at https://cloud.google.com/billing/docs/concepts#subaccounts). +// +// Google Cloud resellers should use the +// Channel Services APIs, +// accounts.customers.create (at https://cloud.google.com/channel/docs/reference/rest/v1/accounts.customers/create) +// and +// accounts.customers.entitlements.create (at https://cloud.google.com/channel/docs/reference/rest/v1/accounts.customers.entitlements/create). +// +// When creating a subaccount, the current authenticated user must have the +// billing.accounts.update IAM permission on the parent account, which is +// typically given to billing account +// administrators (at https://cloud.google.com/billing/docs/how-to/billing-access). +// This method will return an error if the parent account has not been +// provisioned as a reseller account. +func (c *cloudBillingRESTClient) CreateBillingAccount(ctx context.Context, req *billingpb.CreateBillingAccountRequest, opts ...gax.CallOption) (*billingpb.BillingAccount, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetBillingAccount() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/billingAccounts") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateBillingAccount[0:len((*c.CallOptions).CreateBillingAccount):len((*c.CallOptions).CreateBillingAccount)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &billingpb.BillingAccount{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListProjectBillingInfo lists the projects associated with a billing account. The current +// authenticated user must have the billing.resourceAssociations.list IAM +// permission, which is often given to billing account +// viewers (at https://cloud.google.com/billing/docs/how-to/billing-access). +func (c *cloudBillingRESTClient) ListProjectBillingInfo(ctx context.Context, req *billingpb.ListProjectBillingInfoRequest, opts ...gax.CallOption) *ProjectBillingInfoIterator { + it := &ProjectBillingInfoIterator{} + req = proto.Clone(req).(*billingpb.ListProjectBillingInfoRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*billingpb.ProjectBillingInfo, string, error) { + resp := &billingpb.ListProjectBillingInfoResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/projects", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetProjectBillingInfo(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetProjectBillingInfo gets the billing information for a project. The current authenticated user +// must have the resourcemanager.projects.get permission for the project, +// which can be granted by assigning the Project +// Viewer (at https://cloud.google.com/iam/docs/understanding-roles#predefined_roles) +// role. +func (c *cloudBillingRESTClient) GetProjectBillingInfo(ctx context.Context, req *billingpb.GetProjectBillingInfoRequest, opts ...gax.CallOption) (*billingpb.ProjectBillingInfo, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/billingInfo", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetProjectBillingInfo[0:len((*c.CallOptions).GetProjectBillingInfo):len((*c.CallOptions).GetProjectBillingInfo)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &billingpb.ProjectBillingInfo{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateProjectBillingInfo sets or updates the billing account associated with a project. You specify +// the new billing account by setting the billing_account_name in the +// ProjectBillingInfo resource to the resource name of a billing account. +// Associating a project with an open billing account enables billing on the +// project and allows charges for resource usage. If the project already had a +// billing account, this method changes the billing account used for resource +// usage charges. +// +// Note: Incurred charges that have not yet been reported in the transaction +// history of the Google Cloud Console might be billed to the new billing +// account, even if the charge occurred before the new billing account was +// assigned to the project. +// +// The current authenticated user must have ownership privileges for both the +// project (at https://cloud.google.com/docs/permissions-overview#h.bgs0oxofvnoo) and the billing +// account (at https://cloud.google.com/billing/docs/how-to/billing-access). +// +// You can disable billing on the project by setting the +// billing_account_name field to empty. This action disassociates the +// current billing account from the project. Any billable activity of your +// in-use services will stop, and your application could stop functioning as +// expected. Any unbilled charges to date will be billed to the previously +// associated account. The current authenticated user must be either an owner +// of the project or an owner of the billing account for the project. +// +// Note that associating a project with a closed billing account will have +// much the same effect as disabling billing on the project: any paid +// resources used by the project will be shut down. Thus, unless you wish to +// disable billing, you should always call this method with the name of an +// open billing account. +func (c *cloudBillingRESTClient) UpdateProjectBillingInfo(ctx context.Context, req *billingpb.UpdateProjectBillingInfoRequest, opts ...gax.CallOption) (*billingpb.ProjectBillingInfo, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetProjectBillingInfo() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/billingInfo", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateProjectBillingInfo[0:len((*c.CallOptions).UpdateProjectBillingInfo):len((*c.CallOptions).UpdateProjectBillingInfo)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &billingpb.ProjectBillingInfo{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PUT", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetIamPolicy gets the access control policy for a billing account. +// The caller must have the billing.accounts.getIamPolicy permission on the +// account, which is often given to billing account +// viewers (at https://cloud.google.com/billing/docs/how-to/billing-access). +func (c *cloudBillingRESTClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:getIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetOptions().GetRequestedPolicyVersion() != 0 { + params.Add("options.requestedPolicyVersion", fmt.Sprintf("%v", req.GetOptions().GetRequestedPolicyVersion())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SetIamPolicy sets the access control policy for a billing account. Replaces any existing +// policy. +// The caller must have the billing.accounts.setIamPolicy permission on the +// account, which is often given to billing account +// administrators (at https://cloud.google.com/billing/docs/how-to/billing-access). +func (c *cloudBillingRESTClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:setIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// TestIamPermissions tests the access control policy for a billing account. This method takes +// the resource and a set of permissions as input and returns the subset of +// the input permissions that the caller is allowed for that resource. +func (c *cloudBillingRESTClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:testIamPermissions", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.TestIamPermissionsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + // BillingAccountIterator manages a stream of *billingpb.BillingAccount. type BillingAccountIterator struct { items []*billingpb.BillingAccount diff --git a/billing/apiv1/cloud_billing_client_example_test.go b/billing/apiv1/cloud_billing_client_example_test.go index d7b77994d9b0..2e9299ff62d6 100644 --- a/billing/apiv1/cloud_billing_client_example_test.go +++ b/billing/apiv1/cloud_billing_client_example_test.go @@ -42,6 +42,23 @@ func ExampleNewCloudBillingClient() { _ = c } +func ExampleNewCloudBillingRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := billing.NewCloudBillingRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleCloudBillingClient_GetBillingAccount() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/billing/apiv1/cloud_catalog_client.go b/billing/apiv1/cloud_catalog_client.go index b07b1bdef5a3..38dff1bb3ba0 100644 --- a/billing/apiv1/cloud_catalog_client.go +++ b/billing/apiv1/cloud_catalog_client.go @@ -19,17 +19,22 @@ package billing import ( "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" billingpb "cloud.google.com/go/billing/apiv1/billingpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -60,6 +65,13 @@ func defaultCloudCatalogCallOptions() *CloudCatalogCallOptions { } } +func defaultCloudCatalogRESTCallOptions() *CloudCatalogCallOptions { + return &CloudCatalogCallOptions{ + ListServices: []gax.CallOption{}, + ListSkus: []gax.CallOption{}, + } +} + // internalCloudCatalogClient is an interface that defines the methods available from Cloud Billing API. type internalCloudCatalogClient interface { Close() error @@ -199,6 +211,76 @@ func (c *cloudCatalogGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type cloudCatalogRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing CloudCatalogClient + CallOptions **CloudCatalogCallOptions +} + +// NewCloudCatalogRESTClient creates a new cloud catalog rest client. +// +// A catalog of Google Cloud Platform services and SKUs. +// Provides pricing information and metadata on Google Cloud Platform services +// and SKUs. +func NewCloudCatalogRESTClient(ctx context.Context, opts ...option.ClientOption) (*CloudCatalogClient, error) { + clientOpts := append(defaultCloudCatalogRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultCloudCatalogRESTCallOptions() + c := &cloudCatalogRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &CloudCatalogClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultCloudCatalogRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://cloudbilling.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://cloudbilling.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://cloudbilling.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *cloudCatalogRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *cloudCatalogRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *cloudCatalogRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *cloudCatalogGRPCClient) ListServices(ctx context.Context, req *billingpb.ListServicesRequest, opts ...gax.CallOption) *ServiceIterator { ctx = insertMetadata(ctx, c.xGoogMetadata) opts = append((*c.CallOptions).ListServices[0:len((*c.CallOptions).ListServices):len((*c.CallOptions).ListServices)], opts...) @@ -287,6 +369,199 @@ func (c *cloudCatalogGRPCClient) ListSkus(ctx context.Context, req *billingpb.Li return it } +// ListServices lists all public cloud services. +func (c *cloudCatalogRESTClient) ListServices(ctx context.Context, req *billingpb.ListServicesRequest, opts ...gax.CallOption) *ServiceIterator { + it := &ServiceIterator{} + req = proto.Clone(req).(*billingpb.ListServicesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*billingpb.Service, string, error) { + resp := &billingpb.ListServicesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/services") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetServices(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// ListSkus lists all publicly available SKUs for a given cloud service. +func (c *cloudCatalogRESTClient) ListSkus(ctx context.Context, req *billingpb.ListSkusRequest, opts ...gax.CallOption) *SkuIterator { + it := &SkuIterator{} + req = proto.Clone(req).(*billingpb.ListSkusRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*billingpb.Sku, string, error) { + resp := &billingpb.ListSkusResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/skus", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetCurrencyCode() != "" { + params.Add("currencyCode", fmt.Sprintf("%v", req.GetCurrencyCode())) + } + if req.GetEndTime() != nil { + endTime, err := protojson.Marshal(req.GetEndTime()) + if err != nil { + return nil, "", err + } + params.Add("endTime", string(endTime)) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + if req.GetStartTime() != nil { + startTime, err := protojson.Marshal(req.GetStartTime()) + if err != nil { + return nil, "", err + } + params.Add("startTime", string(startTime)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetSkus(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + // ServiceIterator manages a stream of *billingpb.Service. type ServiceIterator struct { items []*billingpb.Service diff --git a/billing/apiv1/cloud_catalog_client_example_test.go b/billing/apiv1/cloud_catalog_client_example_test.go index bd13a3bff5b0..672308bda94f 100644 --- a/billing/apiv1/cloud_catalog_client_example_test.go +++ b/billing/apiv1/cloud_catalog_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewCloudCatalogClient() { _ = c } +func ExampleNewCloudCatalogRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := billing.NewCloudCatalogRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleCloudCatalogClient_ListServices() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/billing/apiv1/doc.go b/billing/apiv1/doc.go index dfd51bc572b2..f8c01f2f5cd2 100644 --- a/billing/apiv1/doc.go +++ b/billing/apiv1/doc.go @@ -81,6 +81,8 @@ package billing // import "cloud.google.com/go/billing/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -171,3 +173,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/billing/apiv1/gapic_metadata.json b/billing/apiv1/gapic_metadata.json index b5571d8762f5..df58ffa4b3ae 100644 --- a/billing/apiv1/gapic_metadata.json +++ b/billing/apiv1/gapic_metadata.json @@ -61,6 +61,61 @@ ] } } + }, + "rest": { + "libraryClient": "CloudBillingClient", + "rpcs": { + "CreateBillingAccount": { + "methods": [ + "CreateBillingAccount" + ] + }, + "GetBillingAccount": { + "methods": [ + "GetBillingAccount" + ] + }, + "GetIamPolicy": { + "methods": [ + "GetIamPolicy" + ] + }, + "GetProjectBillingInfo": { + "methods": [ + "GetProjectBillingInfo" + ] + }, + "ListBillingAccounts": { + "methods": [ + "ListBillingAccounts" + ] + }, + "ListProjectBillingInfo": { + "methods": [ + "ListProjectBillingInfo" + ] + }, + "SetIamPolicy": { + "methods": [ + "SetIamPolicy" + ] + }, + "TestIamPermissions": { + "methods": [ + "TestIamPermissions" + ] + }, + "UpdateBillingAccount": { + "methods": [ + "UpdateBillingAccount" + ] + }, + "UpdateProjectBillingInfo": { + "methods": [ + "UpdateProjectBillingInfo" + ] + } + } } } }, @@ -80,6 +135,21 @@ ] } } + }, + "rest": { + "libraryClient": "CloudCatalogClient", + "rpcs": { + "ListServices": { + "methods": [ + "ListServices" + ] + }, + "ListSkus": { + "methods": [ + "ListSkus" + ] + } + } } } } diff --git a/billing/budgets/apiv1/budget_client.go b/billing/budgets/apiv1/budget_client.go index 35f48c5f8dfb..77f4ea526c6c 100644 --- a/billing/budgets/apiv1/budget_client.go +++ b/billing/budgets/apiv1/budget_client.go @@ -17,21 +17,27 @@ package budgets import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" budgetspb "cloud.google.com/go/billing/budgets/apiv1/budgetspb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -112,6 +118,56 @@ func defaultBudgetCallOptions() *BudgetCallOptions { } } +func defaultBudgetRESTCallOptions() *BudgetCallOptions { + return &BudgetCallOptions{ + CreateBudget: []gax.CallOption{}, + UpdateBudget: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + GetBudget: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + ListBudgets: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + DeleteBudget: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + } +} + // internalBudgetClient is an interface that defines the methods available from Cloud Billing Budget API. type internalBudgetClient interface { Close() error @@ -283,6 +339,75 @@ func (c *budgetGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type budgetRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing BudgetClient + CallOptions **BudgetCallOptions +} + +// NewBudgetRESTClient creates a new budget service rest client. +// +// BudgetService stores Cloud Billing budgets, which define a +// budget plan and rules to execute as we track spend against that plan. +func NewBudgetRESTClient(ctx context.Context, opts ...option.ClientOption) (*BudgetClient, error) { + clientOpts := append(defaultBudgetRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultBudgetRESTCallOptions() + c := &budgetRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &BudgetClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultBudgetRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://billingbudgets.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://billingbudgets.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://billingbudgets.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *budgetRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *budgetRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *budgetRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *budgetGRPCClient) CreateBudget(ctx context.Context, req *budgetspb.CreateBudgetRequest, opts ...gax.CallOption) (*budgetspb.Budget, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) @@ -412,6 +537,345 @@ func (c *budgetGRPCClient) DeleteBudget(ctx context.Context, req *budgetspb.Dele return err } +// CreateBudget creates a new budget. See +// Quotas and limits (at https://cloud.google.com/billing/quotas) +// for more information on the limits of the number of budgets you can create. +func (c *budgetRESTClient) CreateBudget(ctx context.Context, req *budgetspb.CreateBudgetRequest, opts ...gax.CallOption) (*budgetspb.Budget, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetBudget() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/budgets", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateBudget[0:len((*c.CallOptions).CreateBudget):len((*c.CallOptions).CreateBudget)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &budgetspb.Budget{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateBudget updates a budget and returns the updated budget. +// +// WARNING: There are some fields exposed on the Google Cloud Console that +// aren’t available on this API. Budget fields that are not exposed in +// this API will not be changed by this method. +func (c *budgetRESTClient) UpdateBudget(ctx context.Context, req *budgetspb.UpdateBudgetRequest, opts ...gax.CallOption) (*budgetspb.Budget, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetBudget() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetBudget().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "budget.name", url.QueryEscape(req.GetBudget().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateBudget[0:len((*c.CallOptions).UpdateBudget):len((*c.CallOptions).UpdateBudget)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &budgetspb.Budget{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetBudget returns a budget. +// +// WARNING: There are some fields exposed on the Google Cloud Console that +// aren’t available on this API. When reading from the API, you will not +// see these fields in the return value, though they may have been set +// in the Cloud Console. +func (c *budgetRESTClient) GetBudget(ctx context.Context, req *budgetspb.GetBudgetRequest, opts ...gax.CallOption) (*budgetspb.Budget, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetBudget[0:len((*c.CallOptions).GetBudget):len((*c.CallOptions).GetBudget)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &budgetspb.Budget{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListBudgets returns a list of budgets for a billing account. +// +// WARNING: There are some fields exposed on the Google Cloud Console that +// aren’t available on this API. When reading from the API, you will not +// see these fields in the return value, though they may have been set +// in the Cloud Console. +func (c *budgetRESTClient) ListBudgets(ctx context.Context, req *budgetspb.ListBudgetsRequest, opts ...gax.CallOption) *BudgetIterator { + it := &BudgetIterator{} + req = proto.Clone(req).(*budgetspb.ListBudgetsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*budgetspb.Budget, string, error) { + resp := &budgetspb.ListBudgetsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/budgets", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetBudgets(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// DeleteBudget deletes a budget. Returns successfully if already deleted. +func (c *budgetRESTClient) DeleteBudget(ctx context.Context, req *budgetspb.DeleteBudgetRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + // BudgetIterator manages a stream of *budgetspb.Budget. type BudgetIterator struct { items []*budgetspb.Budget diff --git a/billing/budgets/apiv1/budget_client_example_test.go b/billing/budgets/apiv1/budget_client_example_test.go index d2c21759be07..ebbfc26df177 100644 --- a/billing/budgets/apiv1/budget_client_example_test.go +++ b/billing/budgets/apiv1/budget_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewBudgetClient() { _ = c } +func ExampleNewBudgetRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := budgets.NewBudgetRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleBudgetClient_CreateBudget() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/billing/budgets/apiv1/budgetspb/budget_model.pb.go b/billing/budgets/apiv1/budgetspb/budget_model.pb.go index fcb9319cf8dd..2f77c0240ab9 100644 --- a/billing/budgets/apiv1/budgetspb/budget_model.pb.go +++ b/billing/budgets/apiv1/budgetspb/budget_model.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/billing/budgets/v1/budget_model.proto package budgetspb @@ -348,7 +348,6 @@ type BudgetAmount struct { // Specification for what amount to use as the budget. // // Types that are assignable to BudgetAmount: - // // *BudgetAmount_SpecifiedAmount // *BudgetAmount_LastPeriodAmount BudgetAmount isBudgetAmount_BudgetAmount `protobuf_oneof:"budget_amount"` @@ -698,7 +697,6 @@ type Filter struct { // If not set, the `usage_period` defaults to CalendarPeriod.MONTH. // // Types that are assignable to UsagePeriod: - // // *Filter_CalendarPeriod // *Filter_CustomPeriod UsagePeriod isFilter_UsagePeriod `protobuf_oneof:"usage_period"` diff --git a/billing/budgets/apiv1/budgetspb/budget_service.pb.go b/billing/budgets/apiv1/budgetspb/budget_service.pb.go index 9b084fb9d905..c9f9fc2f18fe 100644 --- a/billing/budgets/apiv1/budgetspb/budget_service.pb.go +++ b/billing/budgets/apiv1/budgetspb/budget_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/billing/budgets/v1/budget_service.proto package budgetspb diff --git a/billing/budgets/apiv1/doc.go b/billing/budgets/apiv1/doc.go index df95d5a71823..8673c6eaf337 100644 --- a/billing/budgets/apiv1/doc.go +++ b/billing/budgets/apiv1/doc.go @@ -82,6 +82,8 @@ package budgets // import "cloud.google.com/go/billing/budgets/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -171,3 +173,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/billing/budgets/apiv1/gapic_metadata.json b/billing/budgets/apiv1/gapic_metadata.json index 71de553dd86c..023c2448621f 100644 --- a/billing/budgets/apiv1/gapic_metadata.json +++ b/billing/budgets/apiv1/gapic_metadata.json @@ -36,6 +36,36 @@ ] } } + }, + "rest": { + "libraryClient": "BudgetClient", + "rpcs": { + "CreateBudget": { + "methods": [ + "CreateBudget" + ] + }, + "DeleteBudget": { + "methods": [ + "DeleteBudget" + ] + }, + "GetBudget": { + "methods": [ + "GetBudget" + ] + }, + "ListBudgets": { + "methods": [ + "ListBudgets" + ] + }, + "UpdateBudget": { + "methods": [ + "UpdateBudget" + ] + } + } } } } diff --git a/billing/budgets/apiv1beta1/budget_client.go b/billing/budgets/apiv1beta1/budget_client.go index 2eecbae1e97a..4f4a0ae486ce 100644 --- a/billing/budgets/apiv1beta1/budget_client.go +++ b/billing/budgets/apiv1beta1/budget_client.go @@ -553,6 +553,11 @@ func (c *budgetRESTClient) CreateBudget(ctx context.Context, req *budgetspb.Crea } baseUrl.Path += fmt.Sprintf("/v1beta1/%v/budgets", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -616,6 +621,11 @@ func (c *budgetRESTClient) UpdateBudget(ctx context.Context, req *budgetspb.Upda } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetBudget().GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "budget.name", url.QueryEscape(req.GetBudget().GetName()))) @@ -674,6 +684,11 @@ func (c *budgetRESTClient) GetBudget(ctx context.Context, req *budgetspb.GetBudg } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -746,6 +761,7 @@ func (c *budgetRESTClient) ListBudgets(ctx context.Context, req *budgetspb.ListB baseUrl.Path += fmt.Sprintf("/v1beta1/%v/budgets", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -819,6 +835,11 @@ func (c *budgetRESTClient) DeleteBudget(ctx context.Context, req *budgetspb.Dele } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) diff --git a/billing/budgets/apiv1beta1/budgetspb/budget_model.pb.go b/billing/budgets/apiv1beta1/budgetspb/budget_model.pb.go index 752c8f60525c..d6b7370a0887 100644 --- a/billing/budgets/apiv1beta1/budgetspb/budget_model.pb.go +++ b/billing/budgets/apiv1beta1/budgetspb/budget_model.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/billing/budgets/v1beta1/budget_model.proto package budgetspb @@ -352,7 +352,6 @@ type BudgetAmount struct { // Specification for what amount to use as the budget. // // Types that are assignable to BudgetAmount: - // // *BudgetAmount_SpecifiedAmount // *BudgetAmount_LastPeriodAmount BudgetAmount isBudgetAmount_BudgetAmount `protobuf_oneof:"budget_amount"` @@ -706,15 +705,14 @@ type Filter struct { // An object containing a single `"key": value` pair. Example: `{ "name": // "wrench" }`. // - // _Currently, multiple entries or multiple values per entry are not - // allowed._ + // _Currently, multiple entries or multiple values per entry are not + // allowed._ Labels map[string]*structpb.ListValue `protobuf:"bytes,6,rep,name=labels,proto3" json:"labels,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` // Multiple options to choose the budget's time period, specifying that only // usage that occurs during this time period should be included in the budget. // If not set, the usage_period defaults to CalendarPeriod.MONTH. // // Types that are assignable to UsagePeriod: - // // *Filter_CalendarPeriod // *Filter_CustomPeriod UsagePeriod isFilter_UsagePeriod `protobuf_oneof:"usage_period"` diff --git a/billing/budgets/apiv1beta1/budgetspb/budget_service.pb.go b/billing/budgets/apiv1beta1/budgetspb/budget_service.pb.go index a6e44f9e8953..0a56c5867c7a 100644 --- a/billing/budgets/apiv1beta1/budgetspb/budget_service.pb.go +++ b/billing/budgets/apiv1beta1/budgetspb/budget_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/billing/budgets/v1beta1/budget_service.proto package budgetspb diff --git a/binaryauthorization/apiv1/binaryauthorizationpb/resources.pb.go b/binaryauthorization/apiv1/binaryauthorizationpb/resources.pb.go index b7ef878a135f..6cbc0d47adcc 100644 --- a/binaryauthorization/apiv1/binaryauthorizationpb/resources.pb.go +++ b/binaryauthorization/apiv1/binaryauthorizationpb/resources.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/binaryauthorization/v1/resources.proto package binaryauthorizationpb @@ -605,7 +605,6 @@ type Attestor struct { // The field may be displayed in chooser dialogs. Description string `protobuf:"bytes,6,opt,name=description,proto3" json:"description,omitempty"` // Types that are assignable to AttestorType: - // // *Attestor_UserOwnedGrafeasNote AttestorType isAttestor_AttestorType `protobuf_oneof:"attestor_type"` // Output only. Time when the attestor was last updated. @@ -865,7 +864,6 @@ type AttestorPublicKey struct { // for details. Id string `protobuf:"bytes,2,opt,name=id,proto3" json:"id,omitempty"` // Types that are assignable to PublicKey: - // // *AttestorPublicKey_AsciiArmoredPgpPublicKey // *AttestorPublicKey_PkixPublicKey PublicKey isAttestorPublicKey_PublicKey `protobuf_oneof:"public_key"` diff --git a/binaryauthorization/apiv1/binaryauthorizationpb/service.pb.go b/binaryauthorization/apiv1/binaryauthorizationpb/service.pb.go index cac49fe60eca..9efd33a36844 100644 --- a/binaryauthorization/apiv1/binaryauthorizationpb/service.pb.go +++ b/binaryauthorization/apiv1/binaryauthorizationpb/service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/binaryauthorization/v1/service.proto package binaryauthorizationpb diff --git a/binaryauthorization/apiv1/binauthz_management_client.go b/binaryauthorization/apiv1/binauthz_management_client.go index f795ca25cd5a..d16ceaeedf70 100644 --- a/binaryauthorization/apiv1/binauthz_management_client.go +++ b/binaryauthorization/apiv1/binauthz_management_client.go @@ -17,21 +17,27 @@ package binaryauthorization import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" binaryauthorizationpb "cloud.google.com/go/binaryauthorization/apiv1/binaryauthorizationpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -138,6 +144,78 @@ func defaultBinauthzManagementCallOptions() *BinauthzManagementCallOptions { } } +func defaultBinauthzManagementRESTCallOptions() *BinauthzManagementCallOptions { + return &BinauthzManagementCallOptions{ + GetPolicy: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + UpdatePolicy: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + CreateAttestor: []gax.CallOption{}, + GetAttestor: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + UpdateAttestor: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + ListAttestors: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + DeleteAttestor: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + } +} + // internalBinauthzManagementClient is an interface that defines the methods available from Binary Authorization API. type internalBinauthzManagementClient interface { Close() error @@ -334,6 +412,81 @@ func (c *binauthzManagementGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type binauthzManagementRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing BinauthzManagementClient + CallOptions **BinauthzManagementCallOptions +} + +// NewBinauthzManagementRESTClient creates a new binauthz management service v1 rest client. +// +// Google Cloud Management Service for Binary Authorization admission policies +// and attestation authorities. +// +// This API implements a REST model with the following objects: +// +// Policy +// +// Attestor +func NewBinauthzManagementRESTClient(ctx context.Context, opts ...option.ClientOption) (*BinauthzManagementClient, error) { + clientOpts := append(defaultBinauthzManagementRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultBinauthzManagementRESTCallOptions() + c := &binauthzManagementRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &BinauthzManagementClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultBinauthzManagementRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://binaryauthorization.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://binaryauthorization.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://binaryauthorization.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *binauthzManagementRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *binauthzManagementRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *binauthzManagementRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *binauthzManagementGRPCClient) GetPolicy(ctx context.Context, req *binaryauthorizationpb.GetPolicyRequest, opts ...gax.CallOption) (*binaryauthorizationpb.Policy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) @@ -507,6 +660,463 @@ func (c *binauthzManagementGRPCClient) DeleteAttestor(ctx context.Context, req * return err } +// GetPolicy a policy specifies the attestors that must attest to +// a container image, before the project is allowed to deploy that +// image. There is at most one policy per project. All image admission +// requests are permitted if a project has no policy. +// +// Gets the policy for this project. Returns a default +// policy if the project does not have one. +func (c *binauthzManagementRESTClient) GetPolicy(ctx context.Context, req *binaryauthorizationpb.GetPolicyRequest, opts ...gax.CallOption) (*binaryauthorizationpb.Policy, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetPolicy[0:len((*c.CallOptions).GetPolicy):len((*c.CallOptions).GetPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &binaryauthorizationpb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdatePolicy creates or updates a project’s policy, and returns a copy of the +// new policy. A policy is always updated as a whole, to avoid race +// conditions with concurrent policy enforcement (or management!) +// requests. Returns NOT_FOUND if the project does not exist, INVALID_ARGUMENT +// if the request is malformed. +func (c *binauthzManagementRESTClient) UpdatePolicy(ctx context.Context, req *binaryauthorizationpb.UpdatePolicyRequest, opts ...gax.CallOption) (*binaryauthorizationpb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetPolicy() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetPolicy().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "policy.name", url.QueryEscape(req.GetPolicy().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdatePolicy[0:len((*c.CallOptions).UpdatePolicy):len((*c.CallOptions).UpdatePolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &binaryauthorizationpb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PUT", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateAttestor creates an attestor, and returns a copy of the new +// attestor. Returns NOT_FOUND if the project does not exist, +// INVALID_ARGUMENT if the request is malformed, ALREADY_EXISTS if the +// attestor already exists. +func (c *binauthzManagementRESTClient) CreateAttestor(ctx context.Context, req *binaryauthorizationpb.CreateAttestorRequest, opts ...gax.CallOption) (*binaryauthorizationpb.Attestor, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetAttestor() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/attestors", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("attestorId", fmt.Sprintf("%v", req.GetAttestorId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateAttestor[0:len((*c.CallOptions).CreateAttestor):len((*c.CallOptions).CreateAttestor)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &binaryauthorizationpb.Attestor{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetAttestor gets an attestor. +// Returns NOT_FOUND if the attestor does not exist. +func (c *binauthzManagementRESTClient) GetAttestor(ctx context.Context, req *binaryauthorizationpb.GetAttestorRequest, opts ...gax.CallOption) (*binaryauthorizationpb.Attestor, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetAttestor[0:len((*c.CallOptions).GetAttestor):len((*c.CallOptions).GetAttestor)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &binaryauthorizationpb.Attestor{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateAttestor updates an attestor. +// Returns NOT_FOUND if the attestor does not exist. +func (c *binauthzManagementRESTClient) UpdateAttestor(ctx context.Context, req *binaryauthorizationpb.UpdateAttestorRequest, opts ...gax.CallOption) (*binaryauthorizationpb.Attestor, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetAttestor() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetAttestor().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "attestor.name", url.QueryEscape(req.GetAttestor().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateAttestor[0:len((*c.CallOptions).UpdateAttestor):len((*c.CallOptions).UpdateAttestor)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &binaryauthorizationpb.Attestor{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PUT", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListAttestors lists attestors. +// Returns INVALID_ARGUMENT if the project does not exist. +func (c *binauthzManagementRESTClient) ListAttestors(ctx context.Context, req *binaryauthorizationpb.ListAttestorsRequest, opts ...gax.CallOption) *AttestorIterator { + it := &AttestorIterator{} + req = proto.Clone(req).(*binaryauthorizationpb.ListAttestorsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*binaryauthorizationpb.Attestor, string, error) { + resp := &binaryauthorizationpb.ListAttestorsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/attestors", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetAttestors(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// DeleteAttestor deletes an attestor. Returns NOT_FOUND if the +// attestor does not exist. +func (c *binauthzManagementRESTClient) DeleteAttestor(ctx context.Context, req *binaryauthorizationpb.DeleteAttestorRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + // AttestorIterator manages a stream of *binaryauthorizationpb.Attestor. type AttestorIterator struct { items []*binaryauthorizationpb.Attestor diff --git a/binaryauthorization/apiv1/binauthz_management_client_example_test.go b/binaryauthorization/apiv1/binauthz_management_client_example_test.go index 08cbd196cb53..70944dbe4efb 100644 --- a/binaryauthorization/apiv1/binauthz_management_client_example_test.go +++ b/binaryauthorization/apiv1/binauthz_management_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewBinauthzManagementClient() { _ = c } +func ExampleNewBinauthzManagementRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := binaryauthorization.NewBinauthzManagementRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleBinauthzManagementClient_GetPolicy() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/binaryauthorization/apiv1/doc.go b/binaryauthorization/apiv1/doc.go index 8a796a011967..b53f2a32cd28 100644 --- a/binaryauthorization/apiv1/doc.go +++ b/binaryauthorization/apiv1/doc.go @@ -82,6 +82,8 @@ package binaryauthorization // import "cloud.google.com/go/binaryauthorization/a import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -170,3 +172,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/binaryauthorization/apiv1/gapic_metadata.json b/binaryauthorization/apiv1/gapic_metadata.json index 19e9e01b00a2..5a9538b68089 100644 --- a/binaryauthorization/apiv1/gapic_metadata.json +++ b/binaryauthorization/apiv1/gapic_metadata.json @@ -46,6 +46,46 @@ ] } } + }, + "rest": { + "libraryClient": "BinauthzManagementClient", + "rpcs": { + "CreateAttestor": { + "methods": [ + "CreateAttestor" + ] + }, + "DeleteAttestor": { + "methods": [ + "DeleteAttestor" + ] + }, + "GetAttestor": { + "methods": [ + "GetAttestor" + ] + }, + "GetPolicy": { + "methods": [ + "GetPolicy" + ] + }, + "ListAttestors": { + "methods": [ + "ListAttestors" + ] + }, + "UpdateAttestor": { + "methods": [ + "UpdateAttestor" + ] + }, + "UpdatePolicy": { + "methods": [ + "UpdatePolicy" + ] + } + } } } }, @@ -60,6 +100,16 @@ ] } } + }, + "rest": { + "libraryClient": "SystemPolicyClient", + "rpcs": { + "GetSystemPolicy": { + "methods": [ + "GetSystemPolicy" + ] + } + } } } }, @@ -74,6 +124,16 @@ ] } } + }, + "rest": { + "libraryClient": "ValidationHelperClient", + "rpcs": { + "ValidateAttestationOccurrence": { + "methods": [ + "ValidateAttestationOccurrence" + ] + } + } } } } diff --git a/binaryauthorization/apiv1/system_policy_client.go b/binaryauthorization/apiv1/system_policy_client.go index 391d886eba4a..c6f64c5a6bb2 100644 --- a/binaryauthorization/apiv1/system_policy_client.go +++ b/binaryauthorization/apiv1/system_policy_client.go @@ -19,16 +19,21 @@ package binaryauthorization import ( "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" binaryauthorizationpb "cloud.google.com/go/binaryauthorization/apiv1/binaryauthorizationpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" ) var newSystemPolicyClientHook clientHook @@ -56,6 +61,12 @@ func defaultSystemPolicyCallOptions() *SystemPolicyCallOptions { } } +func defaultSystemPolicyRESTCallOptions() *SystemPolicyCallOptions { + return &SystemPolicyCallOptions{ + GetSystemPolicy: []gax.CallOption{}, + } +} + // internalSystemPolicyClient is an interface that defines the methods available from Binary Authorization API. type internalSystemPolicyClient interface { Close() error @@ -185,6 +196,74 @@ func (c *systemPolicyGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type systemPolicyRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing SystemPolicyClient + CallOptions **SystemPolicyCallOptions +} + +// NewSystemPolicyRESTClient creates a new system policy v1 rest client. +// +// API for working with the system policy. +func NewSystemPolicyRESTClient(ctx context.Context, opts ...option.ClientOption) (*SystemPolicyClient, error) { + clientOpts := append(defaultSystemPolicyRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultSystemPolicyRESTCallOptions() + c := &systemPolicyRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &SystemPolicyClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultSystemPolicyRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://binaryauthorization.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://binaryauthorization.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://binaryauthorization.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *systemPolicyRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *systemPolicyRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *systemPolicyRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *systemPolicyGRPCClient) GetSystemPolicy(ctx context.Context, req *binaryauthorizationpb.GetSystemPolicyRequest, opts ...gax.CallOption) (*binaryauthorizationpb.Policy, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -201,3 +280,61 @@ func (c *systemPolicyGRPCClient) GetSystemPolicy(ctx context.Context, req *binar } return resp, nil } + +// GetSystemPolicy gets the current system policy in the specified location. +func (c *systemPolicyRESTClient) GetSystemPolicy(ctx context.Context, req *binaryauthorizationpb.GetSystemPolicyRequest, opts ...gax.CallOption) (*binaryauthorizationpb.Policy, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetSystemPolicy[0:len((*c.CallOptions).GetSystemPolicy):len((*c.CallOptions).GetSystemPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &binaryauthorizationpb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} diff --git a/binaryauthorization/apiv1/system_policy_client_example_test.go b/binaryauthorization/apiv1/system_policy_client_example_test.go index a10ec588c103..7a6c98c88d70 100644 --- a/binaryauthorization/apiv1/system_policy_client_example_test.go +++ b/binaryauthorization/apiv1/system_policy_client_example_test.go @@ -40,6 +40,23 @@ func ExampleNewSystemPolicyClient() { _ = c } +func ExampleNewSystemPolicyRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := binaryauthorization.NewSystemPolicyRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleSystemPolicyClient_GetSystemPolicy() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/binaryauthorization/apiv1/validation_helper_client.go b/binaryauthorization/apiv1/validation_helper_client.go index 3bd7f3838345..9eccf201b353 100644 --- a/binaryauthorization/apiv1/validation_helper_client.go +++ b/binaryauthorization/apiv1/validation_helper_client.go @@ -17,18 +17,24 @@ package binaryauthorization import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" binaryauthorizationpb "cloud.google.com/go/binaryauthorization/apiv1/binaryauthorizationpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" ) var newValidationHelperClientHook clientHook @@ -56,6 +62,12 @@ func defaultValidationHelperCallOptions() *ValidationHelperCallOptions { } } +func defaultValidationHelperRESTCallOptions() *ValidationHelperCallOptions { + return &ValidationHelperCallOptions{ + ValidateAttestationOccurrence: []gax.CallOption{}, + } +} + // internalValidationHelperClient is an interface that defines the methods available from Binary Authorization API. type internalValidationHelperClient interface { Close() error @@ -186,6 +198,74 @@ func (c *validationHelperGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type validationHelperRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing ValidationHelperClient + CallOptions **ValidationHelperCallOptions +} + +// NewValidationHelperRESTClient creates a new validation helper v1 rest client. +// +// BinAuthz Attestor verification +func NewValidationHelperRESTClient(ctx context.Context, opts ...option.ClientOption) (*ValidationHelperClient, error) { + clientOpts := append(defaultValidationHelperRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultValidationHelperRESTCallOptions() + c := &validationHelperRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &ValidationHelperClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultValidationHelperRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://binaryauthorization.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://binaryauthorization.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://binaryauthorization.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *validationHelperRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *validationHelperRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *validationHelperRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *validationHelperGRPCClient) ValidateAttestationOccurrence(ctx context.Context, req *binaryauthorizationpb.ValidateAttestationOccurrenceRequest, opts ...gax.CallOption) (*binaryauthorizationpb.ValidateAttestationOccurrenceResponse, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "attestor", url.QueryEscape(req.GetAttestor()))) @@ -202,3 +282,68 @@ func (c *validationHelperGRPCClient) ValidateAttestationOccurrence(ctx context.C } return resp, nil } + +// ValidateAttestationOccurrence returns whether the given Attestation for the given image URI +// was signed by the given Attestor +func (c *validationHelperRESTClient) ValidateAttestationOccurrence(ctx context.Context, req *binaryauthorizationpb.ValidateAttestationOccurrenceRequest, opts ...gax.CallOption) (*binaryauthorizationpb.ValidateAttestationOccurrenceResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:validateAttestationOccurrence", req.GetAttestor()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "attestor", url.QueryEscape(req.GetAttestor()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).ValidateAttestationOccurrence[0:len((*c.CallOptions).ValidateAttestationOccurrence):len((*c.CallOptions).ValidateAttestationOccurrence)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &binaryauthorizationpb.ValidateAttestationOccurrenceResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} diff --git a/binaryauthorization/apiv1/validation_helper_client_example_test.go b/binaryauthorization/apiv1/validation_helper_client_example_test.go index 86c33aaecb56..39ebd3a95793 100644 --- a/binaryauthorization/apiv1/validation_helper_client_example_test.go +++ b/binaryauthorization/apiv1/validation_helper_client_example_test.go @@ -40,6 +40,23 @@ func ExampleNewValidationHelperClient() { _ = c } +func ExampleNewValidationHelperRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := binaryauthorization.NewValidationHelperRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleValidationHelperClient_ValidateAttestationOccurrence() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/binaryauthorization/apiv1beta1/binaryauthorizationpb/continuous_validation_logging.pb.go b/binaryauthorization/apiv1beta1/binaryauthorizationpb/continuous_validation_logging.pb.go index 37a06794c39d..d225b51868d1 100644 --- a/binaryauthorization/apiv1beta1/binaryauthorizationpb/continuous_validation_logging.pb.go +++ b/binaryauthorization/apiv1beta1/binaryauthorizationpb/continuous_validation_logging.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/binaryauthorization/v1beta1/continuous_validation_logging.proto package binaryauthorizationpb @@ -147,7 +147,6 @@ type ContinuousValidationEvent struct { // Type of CV event. // // Types that are assignable to EventType: - // // *ContinuousValidationEvent_PodEvent // *ContinuousValidationEvent_UnsupportedPolicyEvent_ EventType isContinuousValidationEvent_EventType `protobuf_oneof:"event_type"` diff --git a/binaryauthorization/apiv1beta1/binaryauthorizationpb/resources.pb.go b/binaryauthorization/apiv1beta1/binaryauthorizationpb/resources.pb.go index 7e9e9f3905b9..7f89f0efb127 100644 --- a/binaryauthorization/apiv1beta1/binaryauthorizationpb/resources.pb.go +++ b/binaryauthorization/apiv1beta1/binaryauthorizationpb/resources.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/binaryauthorization/v1beta1/resources.proto package binaryauthorizationpb @@ -337,8 +337,7 @@ type Policy struct { // https://cloud.google.com/container-engine/reference/rest/v1/projects.zones.clusters. ClusterAdmissionRules map[string]*AdmissionRule `protobuf:"bytes,3,rep,name=cluster_admission_rules,json=clusterAdmissionRules,proto3" json:"cluster_admission_rules,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` // Optional. Per-kubernetes-namespace admission rules. K8s namespace spec format: - // - // `[a-z.-]+`, e.g. `some-namespace` + // `[a-z.-]+`, e.g. `some-namespace` KubernetesNamespaceAdmissionRules map[string]*AdmissionRule `protobuf:"bytes,10,rep,name=kubernetes_namespace_admission_rules,json=kubernetesNamespaceAdmissionRules,proto3" json:"kubernetes_namespace_admission_rules,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` // Optional. Per-kubernetes-service-account admission rules. Service account // spec format: `namespace:serviceaccount`. e.g. `test-ns:default` @@ -615,7 +614,6 @@ type Attestor struct { // attestor fields may be updated. // // Types that are assignable to AttestorType: - // // *Attestor_UserOwnedDrydockNote AttestorType isAttestor_AttestorType `protobuf_oneof:"attestor_type"` // Output only. Time when the attestor was last updated. @@ -877,7 +875,6 @@ type AttestorPublicKey struct { // updated. // // Types that are assignable to PublicKey: - // // *AttestorPublicKey_AsciiArmoredPgpPublicKey // *AttestorPublicKey_PkixPublicKey PublicKey isAttestorPublicKey_PublicKey `protobuf_oneof:"public_key"` diff --git a/binaryauthorization/apiv1beta1/binaryauthorizationpb/service.pb.go b/binaryauthorization/apiv1beta1/binaryauthorizationpb/service.pb.go index 4e10ff251cda..8543b8e85998 100644 --- a/binaryauthorization/apiv1beta1/binaryauthorizationpb/service.pb.go +++ b/binaryauthorization/apiv1beta1/binaryauthorizationpb/service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/binaryauthorization/v1beta1/service.proto package binaryauthorizationpb diff --git a/binaryauthorization/apiv1beta1/binauthz_management_service_v1_beta1_client.go b/binaryauthorization/apiv1beta1/binauthz_management_service_v1_beta1_client.go index 4fd6bf49b535..1d41e437764c 100644 --- a/binaryauthorization/apiv1beta1/binauthz_management_service_v1_beta1_client.go +++ b/binaryauthorization/apiv1beta1/binauthz_management_service_v1_beta1_client.go @@ -674,6 +674,11 @@ func (c *binauthzManagementServiceV1Beta1RESTClient) GetPolicy(ctx context.Conte } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -738,6 +743,11 @@ func (c *binauthzManagementServiceV1Beta1RESTClient) UpdatePolicy(ctx context.Co } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetPolicy().GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "policy.name", url.QueryEscape(req.GetPolicy().GetName()))) @@ -802,6 +812,7 @@ func (c *binauthzManagementServiceV1Beta1RESTClient) CreateAttestor(ctx context. baseUrl.Path += fmt.Sprintf("/v1beta1/%v/attestors", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("attestorId", fmt.Sprintf("%v", req.GetAttestorId())) baseUrl.RawQuery = params.Encode() @@ -860,6 +871,11 @@ func (c *binauthzManagementServiceV1Beta1RESTClient) GetAttestor(ctx context.Con } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -921,6 +937,11 @@ func (c *binauthzManagementServiceV1Beta1RESTClient) UpdateAttestor(ctx context. } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetAttestor().GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "attestor.name", url.QueryEscape(req.GetAttestor().GetName()))) @@ -989,6 +1010,7 @@ func (c *binauthzManagementServiceV1Beta1RESTClient) ListAttestors(ctx context.C baseUrl.Path += fmt.Sprintf("/v1beta1/%v/attestors", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -1063,6 +1085,11 @@ func (c *binauthzManagementServiceV1Beta1RESTClient) DeleteAttestor(ctx context. } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) diff --git a/binaryauthorization/apiv1beta1/system_policy_v1_beta1_client.go b/binaryauthorization/apiv1beta1/system_policy_v1_beta1_client.go index bdecd07ac9fc..efa12b40f028 100644 --- a/binaryauthorization/apiv1beta1/system_policy_v1_beta1_client.go +++ b/binaryauthorization/apiv1beta1/system_policy_v1_beta1_client.go @@ -289,6 +289,11 @@ func (c *systemPolicyV1Beta1RESTClient) GetSystemPolicy(ctx context.Context, req } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) diff --git a/certificatemanager/apiv1/certificate_manager_client.go b/certificatemanager/apiv1/certificate_manager_client.go index 3cd2edf77c2e..3a03c76226a0 100644 --- a/certificatemanager/apiv1/certificate_manager_client.go +++ b/certificatemanager/apiv1/certificate_manager_client.go @@ -17,9 +17,12 @@ package certificatemanager import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,15 +30,18 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -422,6 +428,311 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + ListCertificates: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetCertificate: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateCertificate: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UpdateCertificate: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeleteCertificate: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListCertificateMaps: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetCertificateMap: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateCertificateMap: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UpdateCertificateMap: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeleteCertificateMap: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListCertificateMapEntries: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetCertificateMapEntry: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateCertificateMapEntry: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UpdateCertificateMapEntry: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeleteCertificateMapEntry: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListDnsAuthorizations: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetDnsAuthorization: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateDnsAuthorization: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UpdateDnsAuthorization: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeleteDnsAuthorization: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListCertificateIssuanceConfigs: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetCertificateIssuanceConfig: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateCertificateIssuanceConfig: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeleteCertificateIssuanceConfig: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetLocation: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListLocations: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CancelOperation: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeleteOperation: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetOperation: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 200 * time.Millisecond, + Max: 3000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListOperations: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + } +} + // internalClient is an interface that defines the methods available from Certificate Manager API. type internalClient interface { Close() error @@ -910,46 +1221,158 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } -func (c *gRPCClient) ListCertificates(ctx context.Context, req *certificatemanagerpb.ListCertificatesRequest, opts ...gax.CallOption) *CertificateIterator { - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).ListCertificates[0:len((*c.CallOptions).ListCertificates):len((*c.CallOptions).ListCertificates)], opts...) - it := &CertificateIterator{} - req = proto.Clone(req).(*certificatemanagerpb.ListCertificatesRequest) - it.InternalFetch = func(pageSize int, pageToken string) ([]*certificatemanagerpb.Certificate, string, error) { - resp := &certificatemanagerpb.ListCertificatesResponse{} - if pageToken != "" { - req.PageToken = pageToken - } - if pageSize > math.MaxInt32 { - req.PageSize = math.MaxInt32 - } else if pageSize != 0 { - req.PageSize = int32(pageSize) - } - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.client.ListCertificates(ctx, req, settings.GRPC...) - return err - }, opts...) - if err != nil { - return nil, "", err - } + // The http client. + httpClient *http.Client - it.Response = resp - return resp.GetCertificates(), resp.GetNextPageToken(), 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 - } + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient - it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf) - it.pageInfo.MaxSize = int(req.GetPageSize()) + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new certificate manager rest client. +// +// # API Overview +// +// Certificates Manager API allows customers to see and manage all their TLS +// certificates. +// +// Certificates Manager API service provides methods to manage certificates, +// group them into collections, and create serving configuration that can be +// easily applied to other Cloud resources e.g. Target Proxies. +// +// # Data Model +// +// The Certificates Manager service exposes the following resources: +// +// Certificate which describes a single TLS certificate. +// +// CertificateMap which describes a collection of certificates that can be +// attached to a target resource. +// +// CertificateMapEntry which describes a single configuration entry that +// consists of a SNI and a group of certificates. It’s a subresource of +// CertificateMap. +// +// Certificate, CertificateMap and CertificateMapEntry IDs +// have to match “^[a-z0-9-]{1,63}$” regexp, which means that +// +// only lower case letters, digits, and hyphen are allowed +// +// length of the resource ID has to be in [1,63] range. +// +// Provides methods to manage Cloud Certificate Manager entities. +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://certificatemanager.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://certificatemanager.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://certificatemanager.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} +func (c *gRPCClient) ListCertificates(ctx context.Context, req *certificatemanagerpb.ListCertificatesRequest, opts ...gax.CallOption) *CertificateIterator { + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).ListCertificates[0:len((*c.CallOptions).ListCertificates):len((*c.CallOptions).ListCertificates)], opts...) + it := &CertificateIterator{} + req = proto.Clone(req).(*certificatemanagerpb.ListCertificatesRequest) + it.InternalFetch = func(pageSize int, pageToken string) ([]*certificatemanagerpb.Certificate, string, error) { + resp := &certificatemanagerpb.ListCertificatesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.client.ListCertificates(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, "", err + } + + it.Response = resp + return resp.GetCertificates(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) it.pageInfo.Token = req.GetPageToken() return it @@ -1573,43 +1996,1973 @@ func (c *gRPCClient) DeleteCertificateIssuanceConfig(ctx context.Context, req *c resp, err = c.client.DeleteCertificateIssuanceConfig(ctx, req, settings.GRPC...) return err }, opts...) - if err != nil { - return nil, err + if err != nil { + return nil, err + } + return &DeleteCertificateIssuanceConfigOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + }, nil +} + +func (c *gRPCClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + var resp *locationpb.Location + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.locationsClient.GetLocation(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *gRPCClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).ListLocations[0:len((*c.CallOptions).ListLocations):len((*c.CallOptions).ListLocations)], opts...) + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.locationsClient.ListLocations(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, "", err + } + + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +func (c *gRPCClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + 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 +} + +func (c *gRPCClient) DeleteOperation(ctx context.Context, req *longrunningpb.DeleteOperationRequest, opts ...gax.CallOption) error { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + 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 +} + +func (c *gRPCClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 5000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + 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 +} + +func (c *gRPCClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).ListOperations[0:len((*c.CallOptions).ListOperations):len((*c.CallOptions).ListOperations)], opts...) + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + 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 + } + + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// ListCertificates lists Certificates in a given project and location. +func (c *restClient) ListCertificates(ctx context.Context, req *certificatemanagerpb.ListCertificatesRequest, opts ...gax.CallOption) *CertificateIterator { + it := &CertificateIterator{} + req = proto.Clone(req).(*certificatemanagerpb.ListCertificatesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*certificatemanagerpb.Certificate, string, error) { + resp := &certificatemanagerpb.ListCertificatesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/certificates", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetCertificates(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetCertificate gets details of a single Certificate. +func (c *restClient) GetCertificate(ctx context.Context, req *certificatemanagerpb.GetCertificateRequest, opts ...gax.CallOption) (*certificatemanagerpb.Certificate, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetCertificate[0:len((*c.CallOptions).GetCertificate):len((*c.CallOptions).GetCertificate)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &certificatemanagerpb.Certificate{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateCertificate creates a new Certificate in a given project and location. +func (c *restClient) CreateCertificate(ctx context.Context, req *certificatemanagerpb.CreateCertificateRequest, opts ...gax.CallOption) (*CreateCertificateOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetCertificate() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/certificates", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("certificateId", fmt.Sprintf("%v", req.GetCertificateId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateCertificateOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateCertificate updates a Certificate. +func (c *restClient) UpdateCertificate(ctx context.Context, req *certificatemanagerpb.UpdateCertificateRequest, opts ...gax.CallOption) (*UpdateCertificateOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetCertificate() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetCertificate().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "certificate.name", url.QueryEscape(req.GetCertificate().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateCertificateOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteCertificate deletes a single Certificate. +func (c *restClient) DeleteCertificate(ctx context.Context, req *certificatemanagerpb.DeleteCertificateRequest, opts ...gax.CallOption) (*DeleteCertificateOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteCertificateOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListCertificateMaps lists CertificateMaps in a given project and location. +func (c *restClient) ListCertificateMaps(ctx context.Context, req *certificatemanagerpb.ListCertificateMapsRequest, opts ...gax.CallOption) *CertificateMapIterator { + it := &CertificateMapIterator{} + req = proto.Clone(req).(*certificatemanagerpb.ListCertificateMapsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*certificatemanagerpb.CertificateMap, string, error) { + resp := &certificatemanagerpb.ListCertificateMapsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/certificateMaps", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetCertificateMaps(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetCertificateMap gets details of a single CertificateMap. +func (c *restClient) GetCertificateMap(ctx context.Context, req *certificatemanagerpb.GetCertificateMapRequest, opts ...gax.CallOption) (*certificatemanagerpb.CertificateMap, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetCertificateMap[0:len((*c.CallOptions).GetCertificateMap):len((*c.CallOptions).GetCertificateMap)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &certificatemanagerpb.CertificateMap{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateCertificateMap creates a new CertificateMap in a given project and location. +func (c *restClient) CreateCertificateMap(ctx context.Context, req *certificatemanagerpb.CreateCertificateMapRequest, opts ...gax.CallOption) (*CreateCertificateMapOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetCertificateMap() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/certificateMaps", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("certificateMapId", fmt.Sprintf("%v", req.GetCertificateMapId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateCertificateMapOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateCertificateMap updates a CertificateMap. +func (c *restClient) UpdateCertificateMap(ctx context.Context, req *certificatemanagerpb.UpdateCertificateMapRequest, opts ...gax.CallOption) (*UpdateCertificateMapOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetCertificateMap() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetCertificateMap().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "certificate_map.name", url.QueryEscape(req.GetCertificateMap().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateCertificateMapOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteCertificateMap deletes a single CertificateMap. A Certificate Map can’t be deleted +// if it contains Certificate Map Entries. Remove all the entries from +// the map before calling this method. +func (c *restClient) DeleteCertificateMap(ctx context.Context, req *certificatemanagerpb.DeleteCertificateMapRequest, opts ...gax.CallOption) (*DeleteCertificateMapOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteCertificateMapOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListCertificateMapEntries lists CertificateMapEntries in a given project and location. +func (c *restClient) ListCertificateMapEntries(ctx context.Context, req *certificatemanagerpb.ListCertificateMapEntriesRequest, opts ...gax.CallOption) *CertificateMapEntryIterator { + it := &CertificateMapEntryIterator{} + req = proto.Clone(req).(*certificatemanagerpb.ListCertificateMapEntriesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*certificatemanagerpb.CertificateMapEntry, string, error) { + resp := &certificatemanagerpb.ListCertificateMapEntriesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/certificateMapEntries", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetCertificateMapEntries(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetCertificateMapEntry gets details of a single CertificateMapEntry. +func (c *restClient) GetCertificateMapEntry(ctx context.Context, req *certificatemanagerpb.GetCertificateMapEntryRequest, opts ...gax.CallOption) (*certificatemanagerpb.CertificateMapEntry, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetCertificateMapEntry[0:len((*c.CallOptions).GetCertificateMapEntry):len((*c.CallOptions).GetCertificateMapEntry)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &certificatemanagerpb.CertificateMapEntry{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateCertificateMapEntry creates a new CertificateMapEntry in a given project and location. +func (c *restClient) CreateCertificateMapEntry(ctx context.Context, req *certificatemanagerpb.CreateCertificateMapEntryRequest, opts ...gax.CallOption) (*CreateCertificateMapEntryOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetCertificateMapEntry() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/certificateMapEntries", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("certificateMapEntryId", fmt.Sprintf("%v", req.GetCertificateMapEntryId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateCertificateMapEntryOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateCertificateMapEntry updates a CertificateMapEntry. +func (c *restClient) UpdateCertificateMapEntry(ctx context.Context, req *certificatemanagerpb.UpdateCertificateMapEntryRequest, opts ...gax.CallOption) (*UpdateCertificateMapEntryOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetCertificateMapEntry() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetCertificateMapEntry().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "certificate_map_entry.name", url.QueryEscape(req.GetCertificateMapEntry().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateCertificateMapEntryOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteCertificateMapEntry deletes a single CertificateMapEntry. +func (c *restClient) DeleteCertificateMapEntry(ctx context.Context, req *certificatemanagerpb.DeleteCertificateMapEntryRequest, opts ...gax.CallOption) (*DeleteCertificateMapEntryOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteCertificateMapEntryOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListDnsAuthorizations lists DnsAuthorizations in a given project and location. +func (c *restClient) ListDnsAuthorizations(ctx context.Context, req *certificatemanagerpb.ListDnsAuthorizationsRequest, opts ...gax.CallOption) *DnsAuthorizationIterator { + it := &DnsAuthorizationIterator{} + req = proto.Clone(req).(*certificatemanagerpb.ListDnsAuthorizationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*certificatemanagerpb.DnsAuthorization, string, error) { + resp := &certificatemanagerpb.ListDnsAuthorizationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/dnsAuthorizations", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetDnsAuthorizations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetDnsAuthorization gets details of a single DnsAuthorization. +func (c *restClient) GetDnsAuthorization(ctx context.Context, req *certificatemanagerpb.GetDnsAuthorizationRequest, opts ...gax.CallOption) (*certificatemanagerpb.DnsAuthorization, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetDnsAuthorization[0:len((*c.CallOptions).GetDnsAuthorization):len((*c.CallOptions).GetDnsAuthorization)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &certificatemanagerpb.DnsAuthorization{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateDnsAuthorization creates a new DnsAuthorization in a given project and location. +func (c *restClient) CreateDnsAuthorization(ctx context.Context, req *certificatemanagerpb.CreateDnsAuthorizationRequest, opts ...gax.CallOption) (*CreateDnsAuthorizationOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetDnsAuthorization() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/dnsAuthorizations", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("dnsAuthorizationId", fmt.Sprintf("%v", req.GetDnsAuthorizationId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateDnsAuthorizationOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateDnsAuthorization updates a DnsAuthorization. +func (c *restClient) UpdateDnsAuthorization(ctx context.Context, req *certificatemanagerpb.UpdateDnsAuthorizationRequest, opts ...gax.CallOption) (*UpdateDnsAuthorizationOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetDnsAuthorization() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetDnsAuthorization().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "dns_authorization.name", url.QueryEscape(req.GetDnsAuthorization().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateDnsAuthorizationOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteDnsAuthorization deletes a single DnsAuthorization. +func (c *restClient) DeleteDnsAuthorization(ctx context.Context, req *certificatemanagerpb.DeleteDnsAuthorizationRequest, opts ...gax.CallOption) (*DeleteDnsAuthorizationOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteDnsAuthorizationOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListCertificateIssuanceConfigs lists CertificateIssuanceConfigs in a given project and location. +func (c *restClient) ListCertificateIssuanceConfigs(ctx context.Context, req *certificatemanagerpb.ListCertificateIssuanceConfigsRequest, opts ...gax.CallOption) *CertificateIssuanceConfigIterator { + it := &CertificateIssuanceConfigIterator{} + req = proto.Clone(req).(*certificatemanagerpb.ListCertificateIssuanceConfigsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*certificatemanagerpb.CertificateIssuanceConfig, string, error) { + resp := &certificatemanagerpb.ListCertificateIssuanceConfigsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/certificateIssuanceConfigs", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetCertificateIssuanceConfigs(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetCertificateIssuanceConfig gets details of a single CertificateIssuanceConfig. +func (c *restClient) GetCertificateIssuanceConfig(ctx context.Context, req *certificatemanagerpb.GetCertificateIssuanceConfigRequest, opts ...gax.CallOption) (*certificatemanagerpb.CertificateIssuanceConfig, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetCertificateIssuanceConfig[0:len((*c.CallOptions).GetCertificateIssuanceConfig):len((*c.CallOptions).GetCertificateIssuanceConfig)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &certificatemanagerpb.CertificateIssuanceConfig{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateCertificateIssuanceConfig creates a new CertificateIssuanceConfig in a given project and location. +func (c *restClient) CreateCertificateIssuanceConfig(ctx context.Context, req *certificatemanagerpb.CreateCertificateIssuanceConfigRequest, opts ...gax.CallOption) (*CreateCertificateIssuanceConfigOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetCertificateIssuanceConfig() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/certificateIssuanceConfigs", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("certificateIssuanceConfigId", fmt.Sprintf("%v", req.GetCertificateIssuanceConfigId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateCertificateIssuanceConfigOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteCertificateIssuanceConfig deletes a single CertificateIssuanceConfig. +func (c *restClient) DeleteCertificateIssuanceConfig(ctx context.Context, req *certificatemanagerpb.DeleteCertificateIssuanceConfigRequest, opts ...gax.CallOption) (*DeleteCertificateIssuanceConfigOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) return &DeleteCertificateIssuanceConfigOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, }, nil } -func (c *gRPCClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx +// GetLocation gets information about a location. +func (c *restClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) - var resp *locationpb.Location - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.locationsClient.GetLocation(ctx, req, settings.GRPC...) - return err + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil }, opts...) - if err != nil { - return nil, err + if e != nil { + return nil, e } return resp, nil } -func (c *gRPCClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) - - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).ListLocations[0:len((*c.CallOptions).ListLocations):len((*c.CallOptions).ListLocations)], opts...) +// ListLocations lists information about the supported locations for this service. +func (c *restClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { it := &LocationIterator{} req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { resp := &locationpb.ListLocationsResponse{} if pageToken != "" { @@ -1620,18 +3973,66 @@ func (c *gRPCClient) ListLocations(ctx context.Context, req *locationpb.ListLoca } else if pageSize != 0 { req.PageSize = int32(pageSize) } - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.locationsClient.ListLocations(ctx, req, settings.GRPC...) - return err - }, opts...) + baseUrl, err := url.Parse(c.endpoint) if err != nil { return nil, "", err } + baseUrl.Path += fmt.Sprintf("/v1/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } it.Response = resp return resp.GetLocations(), resp.GetNextPageToken(), nil } + fetch := func(pageSize int, pageToken string) (string, error) { items, nextPageToken, err := it.InternalFetch(pageSize, pageToken) if err != nil { @@ -1648,71 +4049,155 @@ func (c *gRPCClient) ListLocations(ctx context.Context, req *locationpb.ListLoca return it } -func (c *gRPCClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *restClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return err } - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - 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...) + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) }, opts...) - return err } -func (c *gRPCClient) DeleteOperation(ctx context.Context, req *longrunningpb.DeleteOperationRequest, opts ...gax.CallOption) error { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx +// DeleteOperation is a utility method from google.longrunning.Operations. +func (c *restClient) DeleteOperation(ctx context.Context, req *longrunningpb.DeleteOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - 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 + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) }, opts...) - return err } -func (c *gRPCClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 5000*time.Millisecond) - defer cancel() - ctx = cctx +// GetOperation is a utility method from google.longrunning.Operations. +func (c *restClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) 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 + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil }, opts...) - if err != nil { - return nil, err + if e != nil { + return nil, e } return resp, nil } -func (c *gRPCClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) - - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).ListOperations[0:len((*c.CallOptions).ListOperations):len((*c.CallOptions).ListOperations)], opts...) +// ListOperations is a utility method from google.longrunning.Operations. +func (c *restClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { it := &OperationIterator{} req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { resp := &longrunningpb.ListOperationsResponse{} if pageToken != "" { @@ -1723,18 +4208,66 @@ func (c *gRPCClient) ListOperations(ctx context.Context, req *longrunningpb.List } else if pageSize != 0 { 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...) + baseUrl, err := url.Parse(c.endpoint) if err != nil { return nil, "", err } + baseUrl.Path += fmt.Sprintf("/v1/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } it.Response = resp return resp.GetOperations(), resp.GetNextPageToken(), nil } + fetch := func(pageSize int, pageToken string) (string, error) { items, nextPageToken, err := it.InternalFetch(pageSize, pageToken) if err != nil { @@ -1753,7 +4286,8 @@ func (c *gRPCClient) ListOperations(ctx context.Context, req *longrunningpb.List // CreateCertificateOperation manages a long-running operation from CreateCertificate. type CreateCertificateOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateCertificateOperation returns a new CreateCertificateOperation from a given name. @@ -1764,10 +4298,21 @@ func (c *gRPCClient) CreateCertificateOperation(name string) *CreateCertificateO } } +// CreateCertificateOperation returns a new CreateCertificateOperation from a given name. +// The name must be that of a previously created CreateCertificateOperation, possibly from a different process. +func (c *restClient) CreateCertificateOperation(name string) *CreateCertificateOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateCertificateOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateCertificateOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*certificatemanagerpb.Certificate, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp certificatemanagerpb.Certificate if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1785,6 +4330,7 @@ func (op *CreateCertificateOperation) Wait(ctx context.Context, opts ...gax.Call // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateCertificateOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*certificatemanagerpb.Certificate, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp certificatemanagerpb.Certificate if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1822,7 +4368,8 @@ func (op *CreateCertificateOperation) Name() string { // CreateCertificateIssuanceConfigOperation manages a long-running operation from CreateCertificateIssuanceConfig. type CreateCertificateIssuanceConfigOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateCertificateIssuanceConfigOperation returns a new CreateCertificateIssuanceConfigOperation from a given name. @@ -1833,10 +4380,21 @@ func (c *gRPCClient) CreateCertificateIssuanceConfigOperation(name string) *Crea } } +// CreateCertificateIssuanceConfigOperation returns a new CreateCertificateIssuanceConfigOperation from a given name. +// The name must be that of a previously created CreateCertificateIssuanceConfigOperation, possibly from a different process. +func (c *restClient) CreateCertificateIssuanceConfigOperation(name string) *CreateCertificateIssuanceConfigOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateCertificateIssuanceConfigOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateCertificateIssuanceConfigOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*certificatemanagerpb.CertificateIssuanceConfig, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp certificatemanagerpb.CertificateIssuanceConfig if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1854,6 +4412,7 @@ func (op *CreateCertificateIssuanceConfigOperation) Wait(ctx context.Context, op // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateCertificateIssuanceConfigOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*certificatemanagerpb.CertificateIssuanceConfig, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp certificatemanagerpb.CertificateIssuanceConfig if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1891,7 +4450,8 @@ func (op *CreateCertificateIssuanceConfigOperation) Name() string { // CreateCertificateMapOperation manages a long-running operation from CreateCertificateMap. type CreateCertificateMapOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateCertificateMapOperation returns a new CreateCertificateMapOperation from a given name. @@ -1902,10 +4462,21 @@ func (c *gRPCClient) CreateCertificateMapOperation(name string) *CreateCertifica } } +// CreateCertificateMapOperation returns a new CreateCertificateMapOperation from a given name. +// The name must be that of a previously created CreateCertificateMapOperation, possibly from a different process. +func (c *restClient) CreateCertificateMapOperation(name string) *CreateCertificateMapOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateCertificateMapOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateCertificateMapOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*certificatemanagerpb.CertificateMap, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp certificatemanagerpb.CertificateMap if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1923,6 +4494,7 @@ func (op *CreateCertificateMapOperation) Wait(ctx context.Context, opts ...gax.C // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateCertificateMapOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*certificatemanagerpb.CertificateMap, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp certificatemanagerpb.CertificateMap if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1960,7 +4532,8 @@ func (op *CreateCertificateMapOperation) Name() string { // CreateCertificateMapEntryOperation manages a long-running operation from CreateCertificateMapEntry. type CreateCertificateMapEntryOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateCertificateMapEntryOperation returns a new CreateCertificateMapEntryOperation from a given name. @@ -1971,10 +4544,21 @@ func (c *gRPCClient) CreateCertificateMapEntryOperation(name string) *CreateCert } } +// CreateCertificateMapEntryOperation returns a new CreateCertificateMapEntryOperation from a given name. +// The name must be that of a previously created CreateCertificateMapEntryOperation, possibly from a different process. +func (c *restClient) CreateCertificateMapEntryOperation(name string) *CreateCertificateMapEntryOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateCertificateMapEntryOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateCertificateMapEntryOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*certificatemanagerpb.CertificateMapEntry, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp certificatemanagerpb.CertificateMapEntry if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1992,6 +4576,7 @@ func (op *CreateCertificateMapEntryOperation) Wait(ctx context.Context, opts ... // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateCertificateMapEntryOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*certificatemanagerpb.CertificateMapEntry, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp certificatemanagerpb.CertificateMapEntry if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2029,7 +4614,8 @@ func (op *CreateCertificateMapEntryOperation) Name() string { // CreateDnsAuthorizationOperation manages a long-running operation from CreateDnsAuthorization. type CreateDnsAuthorizationOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateDnsAuthorizationOperation returns a new CreateDnsAuthorizationOperation from a given name. @@ -2040,10 +4626,21 @@ func (c *gRPCClient) CreateDnsAuthorizationOperation(name string) *CreateDnsAuth } } +// CreateDnsAuthorizationOperation returns a new CreateDnsAuthorizationOperation from a given name. +// The name must be that of a previously created CreateDnsAuthorizationOperation, possibly from a different process. +func (c *restClient) CreateDnsAuthorizationOperation(name string) *CreateDnsAuthorizationOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateDnsAuthorizationOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateDnsAuthorizationOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*certificatemanagerpb.DnsAuthorization, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp certificatemanagerpb.DnsAuthorization if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2061,6 +4658,7 @@ func (op *CreateDnsAuthorizationOperation) Wait(ctx context.Context, opts ...gax // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateDnsAuthorizationOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*certificatemanagerpb.DnsAuthorization, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp certificatemanagerpb.DnsAuthorization if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2098,7 +4696,8 @@ func (op *CreateDnsAuthorizationOperation) Name() string { // DeleteCertificateOperation manages a long-running operation from DeleteCertificate. type DeleteCertificateOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteCertificateOperation returns a new DeleteCertificateOperation from a given name. @@ -2109,10 +4708,21 @@ func (c *gRPCClient) DeleteCertificateOperation(name string) *DeleteCertificateO } } +// DeleteCertificateOperation returns a new DeleteCertificateOperation from a given name. +// The name must be that of a previously created DeleteCertificateOperation, possibly from a different process. +func (c *restClient) DeleteCertificateOperation(name string) *DeleteCertificateOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteCertificateOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteCertificateOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -2126,6 +4736,7 @@ func (op *DeleteCertificateOperation) Wait(ctx context.Context, opts ...gax.Call // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteCertificateOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -2156,7 +4767,8 @@ func (op *DeleteCertificateOperation) Name() string { // DeleteCertificateIssuanceConfigOperation manages a long-running operation from DeleteCertificateIssuanceConfig. type DeleteCertificateIssuanceConfigOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteCertificateIssuanceConfigOperation returns a new DeleteCertificateIssuanceConfigOperation from a given name. @@ -2167,10 +4779,21 @@ func (c *gRPCClient) DeleteCertificateIssuanceConfigOperation(name string) *Dele } } +// DeleteCertificateIssuanceConfigOperation returns a new DeleteCertificateIssuanceConfigOperation from a given name. +// The name must be that of a previously created DeleteCertificateIssuanceConfigOperation, possibly from a different process. +func (c *restClient) DeleteCertificateIssuanceConfigOperation(name string) *DeleteCertificateIssuanceConfigOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteCertificateIssuanceConfigOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteCertificateIssuanceConfigOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -2184,6 +4807,7 @@ func (op *DeleteCertificateIssuanceConfigOperation) Wait(ctx context.Context, op // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteCertificateIssuanceConfigOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -2214,7 +4838,8 @@ func (op *DeleteCertificateIssuanceConfigOperation) Name() string { // DeleteCertificateMapOperation manages a long-running operation from DeleteCertificateMap. type DeleteCertificateMapOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteCertificateMapOperation returns a new DeleteCertificateMapOperation from a given name. @@ -2225,10 +4850,21 @@ func (c *gRPCClient) DeleteCertificateMapOperation(name string) *DeleteCertifica } } +// DeleteCertificateMapOperation returns a new DeleteCertificateMapOperation from a given name. +// The name must be that of a previously created DeleteCertificateMapOperation, possibly from a different process. +func (c *restClient) DeleteCertificateMapOperation(name string) *DeleteCertificateMapOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteCertificateMapOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteCertificateMapOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -2242,6 +4878,7 @@ func (op *DeleteCertificateMapOperation) Wait(ctx context.Context, opts ...gax.C // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteCertificateMapOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -2272,7 +4909,8 @@ func (op *DeleteCertificateMapOperation) Name() string { // DeleteCertificateMapEntryOperation manages a long-running operation from DeleteCertificateMapEntry. type DeleteCertificateMapEntryOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteCertificateMapEntryOperation returns a new DeleteCertificateMapEntryOperation from a given name. @@ -2283,10 +4921,21 @@ func (c *gRPCClient) DeleteCertificateMapEntryOperation(name string) *DeleteCert } } +// DeleteCertificateMapEntryOperation returns a new DeleteCertificateMapEntryOperation from a given name. +// The name must be that of a previously created DeleteCertificateMapEntryOperation, possibly from a different process. +func (c *restClient) DeleteCertificateMapEntryOperation(name string) *DeleteCertificateMapEntryOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteCertificateMapEntryOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteCertificateMapEntryOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -2300,6 +4949,7 @@ func (op *DeleteCertificateMapEntryOperation) Wait(ctx context.Context, opts ... // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteCertificateMapEntryOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -2330,7 +4980,8 @@ func (op *DeleteCertificateMapEntryOperation) Name() string { // DeleteDnsAuthorizationOperation manages a long-running operation from DeleteDnsAuthorization. type DeleteDnsAuthorizationOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteDnsAuthorizationOperation returns a new DeleteDnsAuthorizationOperation from a given name. @@ -2341,10 +4992,21 @@ func (c *gRPCClient) DeleteDnsAuthorizationOperation(name string) *DeleteDnsAuth } } +// DeleteDnsAuthorizationOperation returns a new DeleteDnsAuthorizationOperation from a given name. +// The name must be that of a previously created DeleteDnsAuthorizationOperation, possibly from a different process. +func (c *restClient) DeleteDnsAuthorizationOperation(name string) *DeleteDnsAuthorizationOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteDnsAuthorizationOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteDnsAuthorizationOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -2358,6 +5020,7 @@ func (op *DeleteDnsAuthorizationOperation) Wait(ctx context.Context, opts ...gax // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteDnsAuthorizationOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -2388,7 +5051,8 @@ func (op *DeleteDnsAuthorizationOperation) Name() string { // UpdateCertificateOperation manages a long-running operation from UpdateCertificate. type UpdateCertificateOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateCertificateOperation returns a new UpdateCertificateOperation from a given name. @@ -2399,10 +5063,21 @@ func (c *gRPCClient) UpdateCertificateOperation(name string) *UpdateCertificateO } } +// UpdateCertificateOperation returns a new UpdateCertificateOperation from a given name. +// The name must be that of a previously created UpdateCertificateOperation, possibly from a different process. +func (c *restClient) UpdateCertificateOperation(name string) *UpdateCertificateOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateCertificateOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateCertificateOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*certificatemanagerpb.Certificate, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp certificatemanagerpb.Certificate if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2420,6 +5095,7 @@ func (op *UpdateCertificateOperation) Wait(ctx context.Context, opts ...gax.Call // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateCertificateOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*certificatemanagerpb.Certificate, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp certificatemanagerpb.Certificate if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2457,7 +5133,8 @@ func (op *UpdateCertificateOperation) Name() string { // UpdateCertificateMapOperation manages a long-running operation from UpdateCertificateMap. type UpdateCertificateMapOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateCertificateMapOperation returns a new UpdateCertificateMapOperation from a given name. @@ -2468,10 +5145,21 @@ func (c *gRPCClient) UpdateCertificateMapOperation(name string) *UpdateCertifica } } +// UpdateCertificateMapOperation returns a new UpdateCertificateMapOperation from a given name. +// The name must be that of a previously created UpdateCertificateMapOperation, possibly from a different process. +func (c *restClient) UpdateCertificateMapOperation(name string) *UpdateCertificateMapOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateCertificateMapOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateCertificateMapOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*certificatemanagerpb.CertificateMap, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp certificatemanagerpb.CertificateMap if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2489,6 +5177,7 @@ func (op *UpdateCertificateMapOperation) Wait(ctx context.Context, opts ...gax.C // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateCertificateMapOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*certificatemanagerpb.CertificateMap, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp certificatemanagerpb.CertificateMap if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2526,7 +5215,8 @@ func (op *UpdateCertificateMapOperation) Name() string { // UpdateCertificateMapEntryOperation manages a long-running operation from UpdateCertificateMapEntry. type UpdateCertificateMapEntryOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateCertificateMapEntryOperation returns a new UpdateCertificateMapEntryOperation from a given name. @@ -2537,10 +5227,21 @@ func (c *gRPCClient) UpdateCertificateMapEntryOperation(name string) *UpdateCert } } +// UpdateCertificateMapEntryOperation returns a new UpdateCertificateMapEntryOperation from a given name. +// The name must be that of a previously created UpdateCertificateMapEntryOperation, possibly from a different process. +func (c *restClient) UpdateCertificateMapEntryOperation(name string) *UpdateCertificateMapEntryOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateCertificateMapEntryOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateCertificateMapEntryOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*certificatemanagerpb.CertificateMapEntry, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp certificatemanagerpb.CertificateMapEntry if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2558,6 +5259,7 @@ func (op *UpdateCertificateMapEntryOperation) Wait(ctx context.Context, opts ... // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateCertificateMapEntryOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*certificatemanagerpb.CertificateMapEntry, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp certificatemanagerpb.CertificateMapEntry if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2595,7 +5297,8 @@ func (op *UpdateCertificateMapEntryOperation) Name() string { // UpdateDnsAuthorizationOperation manages a long-running operation from UpdateDnsAuthorization. type UpdateDnsAuthorizationOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateDnsAuthorizationOperation returns a new UpdateDnsAuthorizationOperation from a given name. @@ -2606,10 +5309,21 @@ func (c *gRPCClient) UpdateDnsAuthorizationOperation(name string) *UpdateDnsAuth } } +// UpdateDnsAuthorizationOperation returns a new UpdateDnsAuthorizationOperation from a given name. +// The name must be that of a previously created UpdateDnsAuthorizationOperation, possibly from a different process. +func (c *restClient) UpdateDnsAuthorizationOperation(name string) *UpdateDnsAuthorizationOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateDnsAuthorizationOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateDnsAuthorizationOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*certificatemanagerpb.DnsAuthorization, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp certificatemanagerpb.DnsAuthorization if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2627,6 +5341,7 @@ func (op *UpdateDnsAuthorizationOperation) Wait(ctx context.Context, opts ...gax // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateDnsAuthorizationOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*certificatemanagerpb.DnsAuthorization, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp certificatemanagerpb.DnsAuthorization if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/certificatemanager/apiv1/certificate_manager_client_example_test.go b/certificatemanager/apiv1/certificate_manager_client_example_test.go index 94972dc72d0d..96679ce83203 100644 --- a/certificatemanager/apiv1/certificate_manager_client_example_test.go +++ b/certificatemanager/apiv1/certificate_manager_client_example_test.go @@ -43,6 +43,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := certificatemanager.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_ListCertificates() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/certificatemanager/apiv1/certificatemanagerpb/certificate_issuance_config.pb.go b/certificatemanager/apiv1/certificatemanagerpb/certificate_issuance_config.pb.go index 6d41513aa48f..eba839865245 100644 --- a/certificatemanager/apiv1/certificatemanagerpb/certificate_issuance_config.pb.go +++ b/certificatemanager/apiv1/certificatemanagerpb/certificate_issuance_config.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/certificatemanager/v1/certificate_issuance_config.proto package certificatemanagerpb @@ -553,7 +553,6 @@ type CertificateIssuanceConfig_CertificateAuthorityConfig struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Kind: - // // *CertificateIssuanceConfig_CertificateAuthorityConfig_CertificateAuthorityServiceConfig_ Kind isCertificateIssuanceConfig_CertificateAuthorityConfig_Kind `protobuf_oneof:"kind"` } diff --git a/certificatemanager/apiv1/certificatemanagerpb/certificate_manager.pb.go b/certificatemanager/apiv1/certificatemanagerpb/certificate_manager.pb.go index 77447033818c..bdf09e118b50 100644 --- a/certificatemanager/apiv1/certificatemanagerpb/certificate_manager.pb.go +++ b/certificatemanager/apiv1/certificatemanagerpb/certificate_manager.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/certificatemanager/v1/certificate_manager.proto package certificatemanagerpb @@ -2108,7 +2108,6 @@ type Certificate struct { // Set of labels associated with a Certificate. Labels map[string]string `protobuf:"bytes,4,rep,name=labels,proto3" json:"labels,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` // Types that are assignable to Type: - // // *Certificate_SelfManaged // *Certificate_Managed Type isCertificate_Type `protobuf_oneof:"type"` @@ -2376,7 +2375,6 @@ type CertificateMapEntry struct { // Set of labels associated with a Certificate Map Entry. Labels map[string]string `protobuf:"bytes,4,rep,name=labels,proto3" json:"labels,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` // Types that are assignable to Match: - // // *CertificateMapEntry_Hostname // *CertificateMapEntry_Matcher_ Match isCertificateMapEntry_Match `protobuf_oneof:"match"` @@ -2937,7 +2935,6 @@ type CertificateMap_GclbTarget struct { // A Target Proxy to which this map is attached to. // // Types that are assignable to TargetProxy: - // // *CertificateMap_GclbTarget_TargetHttpsProxy // *CertificateMap_GclbTarget_TargetSslProxy TargetProxy isCertificateMap_GclbTarget_TargetProxy `protobuf_oneof:"target_proxy"` diff --git a/certificatemanager/apiv1/doc.go b/certificatemanager/apiv1/doc.go index d3503f71afd1..c328b4564444 100644 --- a/certificatemanager/apiv1/doc.go +++ b/certificatemanager/apiv1/doc.go @@ -84,6 +84,8 @@ package certificatemanager // import "cloud.google.com/go/certificatemanager/api import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -172,3 +174,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/certificatemanager/apiv1/gapic_metadata.json b/certificatemanager/apiv1/gapic_metadata.json index fbd2faf7d09b..597805db0238 100644 --- a/certificatemanager/apiv1/gapic_metadata.json +++ b/certificatemanager/apiv1/gapic_metadata.json @@ -161,6 +161,161 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "CreateCertificate": { + "methods": [ + "CreateCertificate" + ] + }, + "CreateCertificateIssuanceConfig": { + "methods": [ + "CreateCertificateIssuanceConfig" + ] + }, + "CreateCertificateMap": { + "methods": [ + "CreateCertificateMap" + ] + }, + "CreateCertificateMapEntry": { + "methods": [ + "CreateCertificateMapEntry" + ] + }, + "CreateDnsAuthorization": { + "methods": [ + "CreateDnsAuthorization" + ] + }, + "DeleteCertificate": { + "methods": [ + "DeleteCertificate" + ] + }, + "DeleteCertificateIssuanceConfig": { + "methods": [ + "DeleteCertificateIssuanceConfig" + ] + }, + "DeleteCertificateMap": { + "methods": [ + "DeleteCertificateMap" + ] + }, + "DeleteCertificateMapEntry": { + "methods": [ + "DeleteCertificateMapEntry" + ] + }, + "DeleteDnsAuthorization": { + "methods": [ + "DeleteDnsAuthorization" + ] + }, + "DeleteOperation": { + "methods": [ + "DeleteOperation" + ] + }, + "GetCertificate": { + "methods": [ + "GetCertificate" + ] + }, + "GetCertificateIssuanceConfig": { + "methods": [ + "GetCertificateIssuanceConfig" + ] + }, + "GetCertificateMap": { + "methods": [ + "GetCertificateMap" + ] + }, + "GetCertificateMapEntry": { + "methods": [ + "GetCertificateMapEntry" + ] + }, + "GetDnsAuthorization": { + "methods": [ + "GetDnsAuthorization" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ListCertificateIssuanceConfigs": { + "methods": [ + "ListCertificateIssuanceConfigs" + ] + }, + "ListCertificateMapEntries": { + "methods": [ + "ListCertificateMapEntries" + ] + }, + "ListCertificateMaps": { + "methods": [ + "ListCertificateMaps" + ] + }, + "ListCertificates": { + "methods": [ + "ListCertificates" + ] + }, + "ListDnsAuthorizations": { + "methods": [ + "ListDnsAuthorizations" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "UpdateCertificate": { + "methods": [ + "UpdateCertificate" + ] + }, + "UpdateCertificateMap": { + "methods": [ + "UpdateCertificateMap" + ] + }, + "UpdateCertificateMapEntry": { + "methods": [ + "UpdateCertificateMapEntry" + ] + }, + "UpdateDnsAuthorization": { + "methods": [ + "UpdateDnsAuthorization" + ] + } + } } } } diff --git a/channel/apiv1/channelpb/channel_partner_links.pb.go b/channel/apiv1/channelpb/channel_partner_links.pb.go index fd0e5815e181..24c4aec663ae 100644 --- a/channel/apiv1/channelpb/channel_partner_links.pb.go +++ b/channel/apiv1/channelpb/channel_partner_links.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/channel/v1/channel_partner_links.proto package channelpb diff --git a/channel/apiv1/channelpb/common.pb.go b/channel/apiv1/channelpb/common.pb.go index b29a4bb8b911..18a3fb305798 100644 --- a/channel/apiv1/channelpb/common.pb.go +++ b/channel/apiv1/channelpb/common.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/channel/v1/common.proto package channelpb @@ -408,7 +408,6 @@ type Value struct { // The kind of value. // // Types that are assignable to Kind: - // // *Value_Int64Value // *Value_StringValue // *Value_DoubleValue diff --git a/channel/apiv1/channelpb/customers.pb.go b/channel/apiv1/channelpb/customers.pb.go index a20c183e8119..11bf1b807b4d 100644 --- a/channel/apiv1/channelpb/customers.pb.go +++ b/channel/apiv1/channelpb/customers.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/channel/v1/customers.proto package channelpb diff --git a/channel/apiv1/channelpb/entitlements.pb.go b/channel/apiv1/channelpb/entitlements.pb.go index d06451b522e7..7be1a6dc09d7 100644 --- a/channel/apiv1/channelpb/entitlements.pb.go +++ b/channel/apiv1/channelpb/entitlements.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/channel/v1/entitlements.proto package channelpb diff --git a/channel/apiv1/channelpb/offers.pb.go b/channel/apiv1/channelpb/offers.pb.go index 45dc6e560852..b365e92b4830 100644 --- a/channel/apiv1/channelpb/offers.pb.go +++ b/channel/apiv1/channelpb/offers.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/channel/v1/offers.proto package channelpb diff --git a/channel/apiv1/channelpb/operations.pb.go b/channel/apiv1/channelpb/operations.pb.go index 70a4195674e5..4b11bc93b213 100644 --- a/channel/apiv1/channelpb/operations.pb.go +++ b/channel/apiv1/channelpb/operations.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/channel/v1/operations.proto package channelpb diff --git a/channel/apiv1/channelpb/products.pb.go b/channel/apiv1/channelpb/products.pb.go index 10fd14cf13f7..0b9027b9468f 100644 --- a/channel/apiv1/channelpb/products.pb.go +++ b/channel/apiv1/channelpb/products.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/channel/v1/products.proto package channelpb diff --git a/channel/apiv1/channelpb/reports_service.pb.go b/channel/apiv1/channelpb/reports_service.pb.go index 7018d71cdb25..bce516087e0d 100644 --- a/channel/apiv1/channelpb/reports_service.pb.go +++ b/channel/apiv1/channelpb/reports_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/channel/v1/reports_service.proto package channelpb @@ -990,7 +990,6 @@ type ReportValue struct { // A single report value. // // Types that are assignable to Value: - // // *ReportValue_StringValue // *ReportValue_IntValue // *ReportValue_DecimalValue @@ -1845,14 +1844,14 @@ type CloudChannelReportsServiceClient interface { // // Possible error codes: // - // - PERMISSION_DENIED: The user doesn't have access to this report. - // - INVALID_ARGUMENT: Required request parameters are missing - // or invalid. - // - NOT_FOUND: The report identifier was not found. - // - INTERNAL: Any non-user error related to a technical issue - // in the backend. Contact Cloud Channel support. - // - UNKNOWN: Any non-user error related to a technical issue - // in the backend. Contact Cloud Channel support. + // * PERMISSION_DENIED: The user doesn't have access to this report. + // * INVALID_ARGUMENT: Required request parameters are missing + // or invalid. + // * NOT_FOUND: The report identifier was not found. + // * INTERNAL: Any non-user error related to a technical issue + // in the backend. Contact Cloud Channel support. + // * UNKNOWN: Any non-user error related to a technical issue + // in the backend. Contact Cloud Channel support. // // Return value: // The ID of a long-running operation. @@ -1914,14 +1913,14 @@ type CloudChannelReportsServiceServer interface { // // Possible error codes: // - // - PERMISSION_DENIED: The user doesn't have access to this report. - // - INVALID_ARGUMENT: Required request parameters are missing - // or invalid. - // - NOT_FOUND: The report identifier was not found. - // - INTERNAL: Any non-user error related to a technical issue - // in the backend. Contact Cloud Channel support. - // - UNKNOWN: Any non-user error related to a technical issue - // in the backend. Contact Cloud Channel support. + // * PERMISSION_DENIED: The user doesn't have access to this report. + // * INVALID_ARGUMENT: Required request parameters are missing + // or invalid. + // * NOT_FOUND: The report identifier was not found. + // * INTERNAL: Any non-user error related to a technical issue + // in the backend. Contact Cloud Channel support. + // * UNKNOWN: Any non-user error related to a technical issue + // in the backend. Contact Cloud Channel support. // // Return value: // The ID of a long-running operation. diff --git a/channel/apiv1/channelpb/repricing.pb.go b/channel/apiv1/channelpb/repricing.pb.go index 37006a5677e5..dfad326fa6aa 100644 --- a/channel/apiv1/channelpb/repricing.pb.go +++ b/channel/apiv1/channelpb/repricing.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/channel/v1/repricing.proto package channelpb @@ -249,7 +249,6 @@ type RepricingConfig struct { // Required. Defines the granularity for repricing. // // Types that are assignable to Granularity: - // // *RepricingConfig_EntitlementGranularity_ // *RepricingConfig_ChannelPartnerGranularity_ Granularity isRepricingConfig_Granularity `protobuf_oneof:"granularity"` @@ -366,7 +365,6 @@ type RepricingAdjustment struct { // A oneof that represents the different types for this adjustment. // // Types that are assignable to Adjustment: - // // *RepricingAdjustment_PercentageAdjustment Adjustment isRepricingAdjustment_Adjustment `protobuf_oneof:"adjustment"` } diff --git a/channel/apiv1/channelpb/service.pb.go b/channel/apiv1/channelpb/service.pb.go index daaa34f521b9..b970122d2742 100644 --- a/channel/apiv1/channelpb/service.pb.go +++ b/channel/apiv1/channelpb/service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/channel/v1/service.proto package channelpb @@ -658,7 +658,6 @@ type ImportCustomerRequest struct { // option is valid. // // Types that are assignable to CustomerIdentity: - // // *ImportCustomerRequest_Domain // *ImportCustomerRequest_CloudIdentityId CustomerIdentity isImportCustomerRequest_CustomerIdentity `protobuf_oneof:"customer_identity"` @@ -1012,7 +1011,6 @@ type ListTransferableSkusRequest struct { // required to look up transferable SKUs. // // Types that are assignable to TransferredCustomerIdentity: - // // *ListTransferableSkusRequest_CloudIdentityId // *ListTransferableSkusRequest_CustomerName TransferredCustomerIdentity isListTransferableSkusRequest_TransferredCustomerIdentity `protobuf_oneof:"transferred_customer_identity"` @@ -1224,7 +1222,6 @@ type ListTransferableOffersRequest struct { // required to look up transferrable Offers. // // Types that are assignable to TransferredCustomerIdentity: - // // *ListTransferableOffersRequest_CloudIdentityId // *ListTransferableOffersRequest_CustomerName TransferredCustomerIdentity isListTransferableOffersRequest_TransferredCustomerIdentity `protobuf_oneof:"transferred_customer_identity"` @@ -3930,7 +3927,6 @@ type ListPurchasableSkusRequest struct { // Defines the intended purchase. // // Types that are assignable to PurchaseOption: - // // *ListPurchasableSkusRequest_CreateEntitlementPurchase_ // *ListPurchasableSkusRequest_ChangeOfferPurchase_ PurchaseOption isListPurchasableSkusRequest_PurchaseOption `protobuf_oneof:"purchase_option"` @@ -4167,7 +4163,6 @@ type ListPurchasableOffersRequest struct { // Defines the intended purchase. // // Types that are assignable to PurchaseOption: - // // *ListPurchasableOffersRequest_CreateEntitlementPurchase_ // *ListPurchasableOffersRequest_ChangeOfferPurchase_ PurchaseOption isListPurchasableOffersRequest_PurchaseOption `protobuf_oneof:"purchase_option"` @@ -7561,8 +7556,8 @@ type CloudChannelServiceClient interface { // * PERMISSION_DENIED: The reseller account making the request is different // from the reseller account in the API request. // * INVALID_ARGUMENT: - // - Required request parameters are missing or invalid. - // - Domain field value doesn't match the primary email domain. + // * Required request parameters are missing or invalid. + // * Domain field value doesn't match the primary email domain. // // Return value: // The newly created [Customer][google.cloud.channel.v1.Customer] resource. @@ -7613,13 +7608,12 @@ type CloudChannelServiceClient interface { // // Possible error codes: // - // - PERMISSION_DENIED: The customer doesn't belong to the reseller. - // - INVALID_ARGUMENT: Required request parameters are missing or invalid. - // - NOT_FOUND: The customer was not found. - // - ALREADY_EXISTS: The customer's primary email already exists. Retry - // after changing the customer's primary contact email. - // - INTERNAL: Any non-user error related to a technical issue in the - // + // * PERMISSION_DENIED: The customer doesn't belong to the reseller. + // * INVALID_ARGUMENT: Required request parameters are missing or invalid. + // * NOT_FOUND: The customer was not found. + // * ALREADY_EXISTS: The customer's primary email already exists. Retry + // after changing the customer's primary contact email. + // * INTERNAL: Any non-user error related to a technical issue in the // backend. Contact Cloud Channel support. // * UNKNOWN: Any non-user error related to a technical issue in the backend. // Contact Cloud Channel support. @@ -7651,11 +7645,10 @@ type CloudChannelServiceClient interface { // Possible error codes: // // * PERMISSION_DENIED: - // - The customer doesn't belong to the reseller and has no auth token. - // - The supplied auth token is invalid. - // - The reseller account making the request is different + // * The customer doesn't belong to the reseller and has no auth token. + // * The supplied auth token is invalid. + // * The reseller account making the request is different // from the reseller account in the query. - // // * INVALID_ARGUMENT: Required request parameters are missing or invalid. // // Return value: @@ -7671,12 +7664,11 @@ type CloudChannelServiceClient interface { // Possible error codes: // // * PERMISSION_DENIED: - // - The customer doesn't belong to the reseller and has no auth token. - // - The customer provided incorrect reseller information when generating + // * The customer doesn't belong to the reseller and has no auth token. + // * The customer provided incorrect reseller information when generating // auth token. - // - The reseller account making the request is different + // * The reseller account making the request is different // from the reseller account in the query. - // // * INVALID_ARGUMENT: Required request parameters are missing or invalid. // // Return value: @@ -7699,28 +7691,25 @@ type CloudChannelServiceClient interface { // // * PERMISSION_DENIED: The customer doesn't belong to the reseller. // * INVALID_ARGUMENT: - // - Required request parameters are missing or invalid. - // - There is already a customer entitlement for a SKU from the same + // * Required request parameters are missing or invalid. + // * There is already a customer entitlement for a SKU from the same // product family. - // // * INVALID_VALUE: Make sure the OfferId is valid. If it is, contact // Google Channel support for further troubleshooting. // * NOT_FOUND: The customer or offer resource was not found. // * ALREADY_EXISTS: - // - The SKU was already purchased for the customer. - // - The customer's primary email already exists. Retry + // * The SKU was already purchased for the customer. + // * The customer's primary email already exists. Retry // after changing the customer's primary contact email. - // // * CONDITION_NOT_MET or FAILED_PRECONDITION: - // - The domain required for purchasing a SKU has not been verified. - // - A pre-requisite SKU required to purchase an Add-On SKU is missing. + // * The domain required for purchasing a SKU has not been verified. + // * A pre-requisite SKU required to purchase an Add-On SKU is missing. // For example, Google Workspace Business Starter is required to purchase // Vault or Drive. - // - (Developer accounts only) Reseller and resold domain must meet the + // * (Developer accounts only) Reseller and resold domain must meet the // following naming requirements: - // - Domain names must start with goog-test. - // - Domain names must include the reseller domain. - // + // * Domain names must start with goog-test. + // * Domain names must include the reseller domain. // * INTERNAL: Any non-user error related to a technical issue in the // backend. Contact Cloud Channel support. // * UNKNOWN: Any non-user error related to a technical issue in the backend. @@ -7771,8 +7760,8 @@ type CloudChannelServiceClient interface { // commitment plan. Can't enable or disable renewals for non-commitment plans. // * INTERNAL: Any non-user error related to a technical issue in the // backend. Contact Cloud Channel support. - // - UNKNOWN: Any non-user error related to a technical issue in the backend. - // Contact Cloud Channel support. + // * UNKNOWN: Any non-user error related to a technical issue in the backend. + // Contact Cloud Channel support. // // Return value: // The ID of a long-running operation. @@ -7914,16 +7903,15 @@ type CloudChannelServiceClient interface { // * NOT_FOUND: The customer or offer resource was not found. // * ALREADY_EXISTS: The SKU was already transferred for the customer. // * CONDITION_NOT_MET or FAILED_PRECONDITION: - // - The SKU requires domain verification to transfer, but the domain is + // * The SKU requires domain verification to transfer, but the domain is // not verified. - // - An Add-On SKU (example, Vault or Drive) is missing the + // * An Add-On SKU (example, Vault or Drive) is missing the // pre-requisite SKU (example, G Suite Basic). - // - (Developer accounts only) Reseller and resold domain must meet the + // * (Developer accounts only) Reseller and resold domain must meet the // following naming requirements: - // - Domain names must start with goog-test. - // - Domain names must include the reseller domain. - // - Specify all transferring entitlements. - // + // * Domain names must start with goog-test. + // * Domain names must include the reseller domain. + // * Specify all transferring entitlements. // * INTERNAL: Any non-user error related to a technical issue in the // backend. Contact Cloud Channel support. // * UNKNOWN: Any non-user error related to a technical issue in the backend. @@ -7945,15 +7933,14 @@ type CloudChannelServiceClient interface { // * NOT_FOUND: The customer or offer resource was not found. // * ALREADY_EXISTS: The SKU was already transferred for the customer. // * CONDITION_NOT_MET or FAILED_PRECONDITION: - // - The SKU requires domain verification to transfer, but the domain is + // * The SKU requires domain verification to transfer, but the domain is // not verified. - // - An Add-On SKU (example, Vault or Drive) is missing the + // * An Add-On SKU (example, Vault or Drive) is missing the // pre-requisite SKU (example, G Suite Basic). - // - (Developer accounts only) Reseller and resold domain must meet the + // * (Developer accounts only) Reseller and resold domain must meet the // following naming requirements: - // - Domain names must start with goog-test. - // - Domain names must include the reseller domain. - // + // * Domain names must start with goog-test. + // * Domain names must include the reseller domain. // * INTERNAL: Any non-user error related to a technical issue in the // backend. Contact Cloud Channel support. // * UNKNOWN: Any non-user error related to a technical issue in the backend. @@ -8025,11 +8012,10 @@ type CloudChannelServiceClient interface { // * PERMISSION_DENIED: The reseller account making the request is different // from the reseller account in the API request. // * INVALID_ARGUMENT: - // - Required request parameters are missing or invalid. - // - Link state cannot change from invited to active or suspended. - // - Cannot send reseller_cloud_identity_id, invite_url, or name in update + // * Required request parameters are missing or invalid. + // * Link state cannot change from invited to active or suspended. + // * Cannot send reseller_cloud_identity_id, invite_url, or name in update // mask. - // // * NOT_FOUND: ChannelPartnerLink resource not found. // * INTERNAL: Any non-user error related to a technical issue in the // backend. Contact Cloud Channel support. @@ -8850,8 +8836,8 @@ type CloudChannelServiceServer interface { // * PERMISSION_DENIED: The reseller account making the request is different // from the reseller account in the API request. // * INVALID_ARGUMENT: - // - Required request parameters are missing or invalid. - // - Domain field value doesn't match the primary email domain. + // * Required request parameters are missing or invalid. + // * Domain field value doesn't match the primary email domain. // // Return value: // The newly created [Customer][google.cloud.channel.v1.Customer] resource. @@ -8902,13 +8888,12 @@ type CloudChannelServiceServer interface { // // Possible error codes: // - // - PERMISSION_DENIED: The customer doesn't belong to the reseller. - // - INVALID_ARGUMENT: Required request parameters are missing or invalid. - // - NOT_FOUND: The customer was not found. - // - ALREADY_EXISTS: The customer's primary email already exists. Retry - // after changing the customer's primary contact email. - // - INTERNAL: Any non-user error related to a technical issue in the - // + // * PERMISSION_DENIED: The customer doesn't belong to the reseller. + // * INVALID_ARGUMENT: Required request parameters are missing or invalid. + // * NOT_FOUND: The customer was not found. + // * ALREADY_EXISTS: The customer's primary email already exists. Retry + // after changing the customer's primary contact email. + // * INTERNAL: Any non-user error related to a technical issue in the // backend. Contact Cloud Channel support. // * UNKNOWN: Any non-user error related to a technical issue in the backend. // Contact Cloud Channel support. @@ -8940,11 +8925,10 @@ type CloudChannelServiceServer interface { // Possible error codes: // // * PERMISSION_DENIED: - // - The customer doesn't belong to the reseller and has no auth token. - // - The supplied auth token is invalid. - // - The reseller account making the request is different + // * The customer doesn't belong to the reseller and has no auth token. + // * The supplied auth token is invalid. + // * The reseller account making the request is different // from the reseller account in the query. - // // * INVALID_ARGUMENT: Required request parameters are missing or invalid. // // Return value: @@ -8960,12 +8944,11 @@ type CloudChannelServiceServer interface { // Possible error codes: // // * PERMISSION_DENIED: - // - The customer doesn't belong to the reseller and has no auth token. - // - The customer provided incorrect reseller information when generating + // * The customer doesn't belong to the reseller and has no auth token. + // * The customer provided incorrect reseller information when generating // auth token. - // - The reseller account making the request is different + // * The reseller account making the request is different // from the reseller account in the query. - // // * INVALID_ARGUMENT: Required request parameters are missing or invalid. // // Return value: @@ -8988,28 +8971,25 @@ type CloudChannelServiceServer interface { // // * PERMISSION_DENIED: The customer doesn't belong to the reseller. // * INVALID_ARGUMENT: - // - Required request parameters are missing or invalid. - // - There is already a customer entitlement for a SKU from the same + // * Required request parameters are missing or invalid. + // * There is already a customer entitlement for a SKU from the same // product family. - // // * INVALID_VALUE: Make sure the OfferId is valid. If it is, contact // Google Channel support for further troubleshooting. // * NOT_FOUND: The customer or offer resource was not found. // * ALREADY_EXISTS: - // - The SKU was already purchased for the customer. - // - The customer's primary email already exists. Retry + // * The SKU was already purchased for the customer. + // * The customer's primary email already exists. Retry // after changing the customer's primary contact email. - // // * CONDITION_NOT_MET or FAILED_PRECONDITION: - // - The domain required for purchasing a SKU has not been verified. - // - A pre-requisite SKU required to purchase an Add-On SKU is missing. + // * The domain required for purchasing a SKU has not been verified. + // * A pre-requisite SKU required to purchase an Add-On SKU is missing. // For example, Google Workspace Business Starter is required to purchase // Vault or Drive. - // - (Developer accounts only) Reseller and resold domain must meet the + // * (Developer accounts only) Reseller and resold domain must meet the // following naming requirements: - // - Domain names must start with goog-test. - // - Domain names must include the reseller domain. - // + // * Domain names must start with goog-test. + // * Domain names must include the reseller domain. // * INTERNAL: Any non-user error related to a technical issue in the // backend. Contact Cloud Channel support. // * UNKNOWN: Any non-user error related to a technical issue in the backend. @@ -9060,8 +9040,8 @@ type CloudChannelServiceServer interface { // commitment plan. Can't enable or disable renewals for non-commitment plans. // * INTERNAL: Any non-user error related to a technical issue in the // backend. Contact Cloud Channel support. - // - UNKNOWN: Any non-user error related to a technical issue in the backend. - // Contact Cloud Channel support. + // * UNKNOWN: Any non-user error related to a technical issue in the backend. + // Contact Cloud Channel support. // // Return value: // The ID of a long-running operation. @@ -9203,16 +9183,15 @@ type CloudChannelServiceServer interface { // * NOT_FOUND: The customer or offer resource was not found. // * ALREADY_EXISTS: The SKU was already transferred for the customer. // * CONDITION_NOT_MET or FAILED_PRECONDITION: - // - The SKU requires domain verification to transfer, but the domain is + // * The SKU requires domain verification to transfer, but the domain is // not verified. - // - An Add-On SKU (example, Vault or Drive) is missing the + // * An Add-On SKU (example, Vault or Drive) is missing the // pre-requisite SKU (example, G Suite Basic). - // - (Developer accounts only) Reseller and resold domain must meet the + // * (Developer accounts only) Reseller and resold domain must meet the // following naming requirements: - // - Domain names must start with goog-test. - // - Domain names must include the reseller domain. - // - Specify all transferring entitlements. - // + // * Domain names must start with goog-test. + // * Domain names must include the reseller domain. + // * Specify all transferring entitlements. // * INTERNAL: Any non-user error related to a technical issue in the // backend. Contact Cloud Channel support. // * UNKNOWN: Any non-user error related to a technical issue in the backend. @@ -9234,15 +9213,14 @@ type CloudChannelServiceServer interface { // * NOT_FOUND: The customer or offer resource was not found. // * ALREADY_EXISTS: The SKU was already transferred for the customer. // * CONDITION_NOT_MET or FAILED_PRECONDITION: - // - The SKU requires domain verification to transfer, but the domain is + // * The SKU requires domain verification to transfer, but the domain is // not verified. - // - An Add-On SKU (example, Vault or Drive) is missing the + // * An Add-On SKU (example, Vault or Drive) is missing the // pre-requisite SKU (example, G Suite Basic). - // - (Developer accounts only) Reseller and resold domain must meet the + // * (Developer accounts only) Reseller and resold domain must meet the // following naming requirements: - // - Domain names must start with goog-test. - // - Domain names must include the reseller domain. - // + // * Domain names must start with goog-test. + // * Domain names must include the reseller domain. // * INTERNAL: Any non-user error related to a technical issue in the // backend. Contact Cloud Channel support. // * UNKNOWN: Any non-user error related to a technical issue in the backend. @@ -9314,11 +9292,10 @@ type CloudChannelServiceServer interface { // * PERMISSION_DENIED: The reseller account making the request is different // from the reseller account in the API request. // * INVALID_ARGUMENT: - // - Required request parameters are missing or invalid. - // - Link state cannot change from invited to active or suspended. - // - Cannot send reseller_cloud_identity_id, invite_url, or name in update + // * Required request parameters are missing or invalid. + // * Link state cannot change from invited to active or suspended. + // * Cannot send reseller_cloud_identity_id, invite_url, or name in update // mask. - // // * NOT_FOUND: ChannelPartnerLink resource not found. // * INTERNAL: Any non-user error related to a technical issue in the // backend. Contact Cloud Channel support. diff --git a/channel/apiv1/channelpb/subscriber_event.pb.go b/channel/apiv1/channelpb/subscriber_event.pb.go index 57a70d1c873e..9ece0c4d5241 100644 --- a/channel/apiv1/channelpb/subscriber_event.pb.go +++ b/channel/apiv1/channelpb/subscriber_event.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/channel/v1/subscriber_event.proto package channelpb @@ -314,7 +314,6 @@ type SubscriberEvent struct { // This is a required field. // // Types that are assignable to Event: - // // *SubscriberEvent_CustomerEvent // *SubscriberEvent_EntitlementEvent Event isSubscriberEvent_Event `protobuf_oneof:"event"` diff --git a/channel/apiv1/cloud_channel_client.go b/channel/apiv1/cloud_channel_client.go index 89ec19da050b..3ae4a6cc29c7 100644 --- a/channel/apiv1/cloud_channel_client.go +++ b/channel/apiv1/cloud_channel_client.go @@ -17,9 +17,12 @@ package channel import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,14 +30,17 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -499,6 +505,366 @@ func defaultCloudChannelCallOptions() *CloudChannelCallOptions { } } +func defaultCloudChannelRESTCallOptions() *CloudChannelCallOptions { + return &CloudChannelCallOptions{ + ListCustomers: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetCustomer: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CheckCloudIdentityAccountsExist: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateCustomer: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UpdateCustomer: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeleteCustomer: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ImportCustomer: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ProvisionCloudIdentity: []gax.CallOption{}, + ListEntitlements: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListTransferableSkus: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListTransferableOffers: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetEntitlement: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateEntitlement: []gax.CallOption{}, + ChangeParameters: []gax.CallOption{}, + ChangeRenewalSettings: []gax.CallOption{}, + ChangeOffer: []gax.CallOption{}, + StartPaidService: []gax.CallOption{}, + SuspendEntitlement: []gax.CallOption{}, + CancelEntitlement: []gax.CallOption{}, + ActivateEntitlement: []gax.CallOption{}, + TransferEntitlements: []gax.CallOption{}, + TransferEntitlementsToGoogle: []gax.CallOption{}, + ListChannelPartnerLinks: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetChannelPartnerLink: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateChannelPartnerLink: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UpdateChannelPartnerLink: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetCustomerRepricingConfig: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListCustomerRepricingConfigs: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateCustomerRepricingConfig: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UpdateCustomerRepricingConfig: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeleteCustomerRepricingConfig: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetChannelPartnerRepricingConfig: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListChannelPartnerRepricingConfigs: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateChannelPartnerRepricingConfig: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UpdateChannelPartnerRepricingConfig: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeleteChannelPartnerRepricingConfig: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + LookupOffer: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListProducts: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListSkus: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListOffers: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListPurchasableSkus: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListPurchasableOffers: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + RegisterSubscriber: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UnregisterSubscriber: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListSubscribers: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CancelOperation: []gax.CallOption{}, + DeleteOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalCloudChannelClient is an interface that defines the methods available from Cloud Channel API. type internalCloudChannelClient interface { Close() error @@ -566,755 +932,3043 @@ type internalCloudChannelClient interface { ListOperations(context.Context, *longrunningpb.ListOperationsRequest, ...gax.CallOption) *OperationIterator } -// CloudChannelClient is a client for interacting with Cloud Channel API. -// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. -// -// CloudChannelService lets Google cloud resellers and distributors manage -// their customers, channel partners, entitlements, and reports. -// -// Using this service: -// -// Resellers and distributors can manage a customer entity. -// -// Distributors can register an authorized reseller in their channel and -// provide them with delegated admin access. -// -// Resellers and distributors can manage customer entitlements. -// -// CloudChannelService exposes the following resources: -// -// Customers: An entity—usually an enterprise—managed by a reseller or -// distributor. -// -// Entitlements: An entity that provides a customer with the means to use -// a service. Entitlements are created or updated as a result of a successful -// fulfillment. -// -// ChannelPartnerLinks: An entity that identifies links between -// distributors and their indirect resellers in a channel. -type CloudChannelClient struct { - // The internal transport-dependent client. - internalClient internalCloudChannelClient +// CloudChannelClient is a client for interacting with Cloud Channel API. +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// CloudChannelService lets Google cloud resellers and distributors manage +// their customers, channel partners, entitlements, and reports. +// +// Using this service: +// +// Resellers and distributors can manage a customer entity. +// +// Distributors can register an authorized reseller in their channel and +// provide them with delegated admin access. +// +// Resellers and distributors can manage customer entitlements. +// +// CloudChannelService exposes the following resources: +// +// Customers: An entity—usually an enterprise—managed by a reseller or +// distributor. +// +// Entitlements: An entity that provides a customer with the means to use +// a service. Entitlements are created or updated as a result of a successful +// fulfillment. +// +// ChannelPartnerLinks: An entity that identifies links between +// distributors and their indirect resellers in a channel. +type CloudChannelClient struct { + // The internal transport-dependent client. + internalClient internalCloudChannelClient + + // The call options for this service. + CallOptions *CloudChannelCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *CloudChannelClient) Close() error { + return c.internalClient.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 *CloudChannelClient) setGoogleClientInfo(keyval ...string) { + c.internalClient.setGoogleClientInfo(keyval...) +} + +// Connection returns a connection to the API service. +// +// Deprecated: Connections are now pooled so this method does not always +// return the same resource. +func (c *CloudChannelClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListCustomers list Customers. +// +// Possible error codes: +// +// PERMISSION_DENIED: The reseller account making the request is different +// from the reseller account in the API request. +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +// +// Return value: +// List of Customers, or an empty list if there are no customers. +func (c *CloudChannelClient) ListCustomers(ctx context.Context, req *channelpb.ListCustomersRequest, opts ...gax.CallOption) *CustomerIterator { + return c.internalClient.ListCustomers(ctx, req, opts...) +} + +// GetCustomer returns the requested Customer resource. +// +// Possible error codes: +// +// PERMISSION_DENIED: The reseller account making the request is different +// from the reseller account in the API request. +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +// +// NOT_FOUND: The customer resource doesn’t exist. Usually the result of an +// invalid name parameter. +// +// Return value: +// The Customer resource. +func (c *CloudChannelClient) GetCustomer(ctx context.Context, req *channelpb.GetCustomerRequest, opts ...gax.CallOption) (*channelpb.Customer, error) { + return c.internalClient.GetCustomer(ctx, req, opts...) +} + +// CheckCloudIdentityAccountsExist confirms the existence of Cloud Identity accounts based on the domain and +// if the Cloud Identity accounts are owned by the reseller. +// +// Possible error codes: +// +// PERMISSION_DENIED: The reseller account making the request is different +// from the reseller account in the API request. +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +// +// INVALID_VALUE: Invalid domain value in the request. +// +// Return value: +// A list of CloudIdentityCustomerAccount resources for the domain (may be +// empty) +// +// Note: in the v1alpha1 version of the API, a NOT_FOUND error returns if +// no CloudIdentityCustomerAccount resources match the domain. +func (c *CloudChannelClient) CheckCloudIdentityAccountsExist(ctx context.Context, req *channelpb.CheckCloudIdentityAccountsExistRequest, opts ...gax.CallOption) (*channelpb.CheckCloudIdentityAccountsExistResponse, error) { + return c.internalClient.CheckCloudIdentityAccountsExist(ctx, req, opts...) +} + +// CreateCustomer creates a new Customer resource under the reseller or distributor +// account. +// +// Possible error codes: +// +// PERMISSION_DENIED: The reseller account making the request is different +// from the reseller account in the API request. +// +// INVALID_ARGUMENT: +// +// Required request parameters are missing or invalid. +// +// Domain field value doesn’t match the primary email domain. +// +// Return value: +// The newly created Customer resource. +func (c *CloudChannelClient) CreateCustomer(ctx context.Context, req *channelpb.CreateCustomerRequest, opts ...gax.CallOption) (*channelpb.Customer, error) { + return c.internalClient.CreateCustomer(ctx, req, opts...) +} + +// UpdateCustomer updates an existing Customer resource for the reseller or +// distributor. +// +// Possible error codes: +// +// PERMISSION_DENIED: The reseller account making the request is different +// from the reseller account in the API request. +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +// +// NOT_FOUND: No Customer resource found for the name in the request. +// +// Return value: +// The updated Customer resource. +func (c *CloudChannelClient) UpdateCustomer(ctx context.Context, req *channelpb.UpdateCustomerRequest, opts ...gax.CallOption) (*channelpb.Customer, error) { + return c.internalClient.UpdateCustomer(ctx, req, opts...) +} + +// DeleteCustomer deletes the given Customer permanently. +// +// Possible error codes: +// +// PERMISSION_DENIED: The account making the request does not own +// this customer. +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +// +// FAILED_PRECONDITION: The customer has existing entitlements. +// +// NOT_FOUND: No Customer resource found for the name in the request. +func (c *CloudChannelClient) DeleteCustomer(ctx context.Context, req *channelpb.DeleteCustomerRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteCustomer(ctx, req, opts...) +} + +// ImportCustomer imports a Customer from the Cloud Identity associated with the provided +// Cloud Identity ID or domain before a TransferEntitlements call. If a +// linked Customer already exists and overwrite_if_exists is true, it will +// update that Customer’s data. +// +// Possible error codes: +// +// PERMISSION_DENIED: The reseller account making the request is different +// from the reseller account in the API request. +// +// NOT_FOUND: Cloud Identity doesn’t exist or was deleted. +// +// INVALID_ARGUMENT: Required parameters are missing, or the auth_token is +// expired or invalid. +// +// ALREADY_EXISTS: A customer already exists and has conflicting critical +// fields. Requires an overwrite. +// +// Return value: +// The Customer. +func (c *CloudChannelClient) ImportCustomer(ctx context.Context, req *channelpb.ImportCustomerRequest, opts ...gax.CallOption) (*channelpb.Customer, error) { + return c.internalClient.ImportCustomer(ctx, req, opts...) +} + +// ProvisionCloudIdentity creates a Cloud Identity for the given customer using the customer’s +// information, or the information provided here. +// +// Possible error codes: +// +// PERMISSION_DENIED: The customer doesn’t belong to the reseller. +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +// +// NOT_FOUND: The customer was not found. +// +// ALREADY_EXISTS: The customer’s primary email already exists. Retry +// after changing the customer’s primary contact email. +// +// INTERNAL: Any non-user error related to a technical issue in the +// backend. Contact Cloud Channel support. +// +// UNKNOWN: Any non-user error related to a technical issue in the backend. +// Contact Cloud Channel support. +// +// Return value: +// The ID of a long-running operation. +// +// To get the results of the operation, call the GetOperation method of +// CloudChannelOperationsService. The Operation metadata contains an +// instance of OperationMetadata. +func (c *CloudChannelClient) ProvisionCloudIdentity(ctx context.Context, req *channelpb.ProvisionCloudIdentityRequest, opts ...gax.CallOption) (*ProvisionCloudIdentityOperation, error) { + return c.internalClient.ProvisionCloudIdentity(ctx, req, opts...) +} + +// ProvisionCloudIdentityOperation returns a new ProvisionCloudIdentityOperation from a given name. +// The name must be that of a previously created ProvisionCloudIdentityOperation, possibly from a different process. +func (c *CloudChannelClient) ProvisionCloudIdentityOperation(name string) *ProvisionCloudIdentityOperation { + return c.internalClient.ProvisionCloudIdentityOperation(name) +} + +// ListEntitlements lists Entitlements belonging to a customer. +// +// Possible error codes: +// +// PERMISSION_DENIED: The customer doesn’t belong to the reseller. +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +// +// Return value: +// A list of the customer’s Entitlements. +func (c *CloudChannelClient) ListEntitlements(ctx context.Context, req *channelpb.ListEntitlementsRequest, opts ...gax.CallOption) *EntitlementIterator { + return c.internalClient.ListEntitlements(ctx, req, opts...) +} + +// ListTransferableSkus list TransferableSkus of a customer based on the Cloud Identity ID or +// Customer Name in the request. +// +// Use this method to list the entitlements information of an +// unowned customer. You should provide the customer’s +// Cloud Identity ID or Customer Name. +// +// Possible error codes: +// +// PERMISSION_DENIED: +// +// The customer doesn’t belong to the reseller and has no auth token. +// +// The supplied auth token is invalid. +// +// The reseller account making the request is different +// from the reseller account in the query. +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +// +// Return value: +// A list of the customer’s TransferableSku. +func (c *CloudChannelClient) ListTransferableSkus(ctx context.Context, req *channelpb.ListTransferableSkusRequest, opts ...gax.CallOption) *TransferableSkuIterator { + return c.internalClient.ListTransferableSkus(ctx, req, opts...) +} + +// ListTransferableOffers list TransferableOffers of a customer based on Cloud Identity ID or +// Customer Name in the request. +// +// Use this method when a reseller gets the entitlement information of an +// unowned customer. The reseller should provide the customer’s +// Cloud Identity ID or Customer Name. +// +// Possible error codes: +// +// PERMISSION_DENIED: +// +// The customer doesn’t belong to the reseller and has no auth token. +// +// The customer provided incorrect reseller information when generating +// auth token. +// +// The reseller account making the request is different +// from the reseller account in the query. +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +// +// Return value: +// List of TransferableOffer for the given customer and SKU. +func (c *CloudChannelClient) ListTransferableOffers(ctx context.Context, req *channelpb.ListTransferableOffersRequest, opts ...gax.CallOption) *TransferableOfferIterator { + return c.internalClient.ListTransferableOffers(ctx, req, opts...) +} + +// GetEntitlement returns the requested Entitlement resource. +// +// Possible error codes: +// +// PERMISSION_DENIED: The customer doesn’t belong to the reseller. +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +// +// NOT_FOUND: The customer entitlement was not found. +// +// Return value: +// The requested Entitlement resource. +func (c *CloudChannelClient) GetEntitlement(ctx context.Context, req *channelpb.GetEntitlementRequest, opts ...gax.CallOption) (*channelpb.Entitlement, error) { + return c.internalClient.GetEntitlement(ctx, req, opts...) +} + +// CreateEntitlement creates an entitlement for a customer. +// +// Possible error codes: +// +// PERMISSION_DENIED: The customer doesn’t belong to the reseller. +// +// INVALID_ARGUMENT: +// +// Required request parameters are missing or invalid. +// +// There is already a customer entitlement for a SKU from the same +// product family. +// +// INVALID_VALUE: Make sure the OfferId is valid. If it is, contact +// Google Channel support for further troubleshooting. +// +// NOT_FOUND: The customer or offer resource was not found. +// +// ALREADY_EXISTS: +// +// The SKU was already purchased for the customer. +// +// The customer’s primary email already exists. Retry +// after changing the customer’s primary contact email. +// +// CONDITION_NOT_MET or FAILED_PRECONDITION: +// +// The domain required for purchasing a SKU has not been verified. +// +// A pre-requisite SKU required to purchase an Add-On SKU is missing. +// For example, Google Workspace Business Starter is required to purchase +// Vault or Drive. +// +// (Developer accounts only) Reseller and resold domain must meet the +// following naming requirements: +// +// Domain names must start with goog-test. +// +// Domain names must include the reseller domain. +// +// INTERNAL: Any non-user error related to a technical issue in the +// backend. Contact Cloud Channel support. +// +// UNKNOWN: Any non-user error related to a technical issue in the backend. +// Contact Cloud Channel support. +// +// Return value: +// The ID of a long-running operation. +// +// To get the results of the operation, call the GetOperation method of +// CloudChannelOperationsService. The Operation metadata will contain an +// instance of OperationMetadata. +func (c *CloudChannelClient) CreateEntitlement(ctx context.Context, req *channelpb.CreateEntitlementRequest, opts ...gax.CallOption) (*CreateEntitlementOperation, error) { + return c.internalClient.CreateEntitlement(ctx, req, opts...) +} + +// CreateEntitlementOperation returns a new CreateEntitlementOperation from a given name. +// The name must be that of a previously created CreateEntitlementOperation, possibly from a different process. +func (c *CloudChannelClient) CreateEntitlementOperation(name string) *CreateEntitlementOperation { + return c.internalClient.CreateEntitlementOperation(name) +} + +// ChangeParameters change parameters of the entitlement. +// +// An entitlement update is a long-running operation and it updates the +// entitlement as a result of fulfillment. +// +// Possible error codes: +// +// PERMISSION_DENIED: The customer doesn’t belong to the reseller. +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +// For example, the number of seats being changed is greater than the allowed +// number of max seats, or decreasing seats for a commitment based plan. +// +// NOT_FOUND: Entitlement resource not found. +// +// INTERNAL: Any non-user error related to a technical issue in the +// backend. Contact Cloud Channel support. +// +// UNKNOWN: Any non-user error related to a technical issue in the backend. +// Contact Cloud Channel support. +// +// Return value: +// The ID of a long-running operation. +// +// To get the results of the operation, call the GetOperation method of +// CloudChannelOperationsService. The Operation metadata will contain an +// instance of OperationMetadata. +func (c *CloudChannelClient) ChangeParameters(ctx context.Context, req *channelpb.ChangeParametersRequest, opts ...gax.CallOption) (*ChangeParametersOperation, error) { + return c.internalClient.ChangeParameters(ctx, req, opts...) +} + +// ChangeParametersOperation returns a new ChangeParametersOperation from a given name. +// The name must be that of a previously created ChangeParametersOperation, possibly from a different process. +func (c *CloudChannelClient) ChangeParametersOperation(name string) *ChangeParametersOperation { + return c.internalClient.ChangeParametersOperation(name) +} + +// ChangeRenewalSettings updates the renewal settings for an existing customer entitlement. +// +// An entitlement update is a long-running operation and it updates the +// entitlement as a result of fulfillment. +// +// Possible error codes: +// +// PERMISSION_DENIED: The customer doesn’t belong to the reseller. +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +// +// NOT_FOUND: Entitlement resource not found. +// +// NOT_COMMITMENT_PLAN: Renewal Settings are only applicable for a +// commitment plan. Can’t enable or disable renewals for non-commitment plans. +// +// INTERNAL: Any non-user error related to a technical issue in the +// backend. Contact Cloud Channel support. +// +// UNKNOWN: Any non-user error related to a technical issue in the backend. +// Contact Cloud Channel support. +// +// Return value: +// The ID of a long-running operation. +// +// To get the results of the operation, call the GetOperation method of +// CloudChannelOperationsService. The Operation metadata will contain an +// instance of OperationMetadata. +func (c *CloudChannelClient) ChangeRenewalSettings(ctx context.Context, req *channelpb.ChangeRenewalSettingsRequest, opts ...gax.CallOption) (*ChangeRenewalSettingsOperation, error) { + return c.internalClient.ChangeRenewalSettings(ctx, req, opts...) +} + +// ChangeRenewalSettingsOperation returns a new ChangeRenewalSettingsOperation from a given name. +// The name must be that of a previously created ChangeRenewalSettingsOperation, possibly from a different process. +func (c *CloudChannelClient) ChangeRenewalSettingsOperation(name string) *ChangeRenewalSettingsOperation { + return c.internalClient.ChangeRenewalSettingsOperation(name) +} + +// ChangeOffer updates the Offer for an existing customer entitlement. +// +// An entitlement update is a long-running operation and it updates the +// entitlement as a result of fulfillment. +// +// Possible error codes: +// +// PERMISSION_DENIED: The customer doesn’t belong to the reseller. +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +// +// NOT_FOUND: Offer or Entitlement resource not found. +// +// INTERNAL: Any non-user error related to a technical issue in the +// backend. Contact Cloud Channel support. +// +// UNKNOWN: Any non-user error related to a technical issue in the backend. +// Contact Cloud Channel support. +// +// Return value: +// The ID of a long-running operation. +// +// To get the results of the operation, call the GetOperation method of +// CloudChannelOperationsService. The Operation metadata will contain an +// instance of OperationMetadata. +func (c *CloudChannelClient) ChangeOffer(ctx context.Context, req *channelpb.ChangeOfferRequest, opts ...gax.CallOption) (*ChangeOfferOperation, error) { + return c.internalClient.ChangeOffer(ctx, req, opts...) +} + +// ChangeOfferOperation returns a new ChangeOfferOperation from a given name. +// The name must be that of a previously created ChangeOfferOperation, possibly from a different process. +func (c *CloudChannelClient) ChangeOfferOperation(name string) *ChangeOfferOperation { + return c.internalClient.ChangeOfferOperation(name) +} + +// StartPaidService starts paid service for a trial entitlement. +// +// Starts paid service for a trial entitlement immediately. This method is +// only applicable if a plan is set up for a trial entitlement but has some +// trial days remaining. +// +// Possible error codes: +// +// PERMISSION_DENIED: The customer doesn’t belong to the reseller. +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +// +// NOT_FOUND: Entitlement resource not found. +// +// FAILED_PRECONDITION/NOT_IN_TRIAL: This method only works for +// entitlement on trial plans. +// +// INTERNAL: Any non-user error related to a technical issue in the +// backend. Contact Cloud Channel support. +// +// UNKNOWN: Any non-user error related to a technical issue in the backend. +// Contact Cloud Channel support. +// +// Return value: +// The ID of a long-running operation. +// +// To get the results of the operation, call the GetOperation method of +// CloudChannelOperationsService. The Operation metadata will contain an +// instance of OperationMetadata. +func (c *CloudChannelClient) StartPaidService(ctx context.Context, req *channelpb.StartPaidServiceRequest, opts ...gax.CallOption) (*StartPaidServiceOperation, error) { + return c.internalClient.StartPaidService(ctx, req, opts...) +} + +// StartPaidServiceOperation returns a new StartPaidServiceOperation from a given name. +// The name must be that of a previously created StartPaidServiceOperation, possibly from a different process. +func (c *CloudChannelClient) StartPaidServiceOperation(name string) *StartPaidServiceOperation { + return c.internalClient.StartPaidServiceOperation(name) +} + +// SuspendEntitlement suspends a previously fulfilled entitlement. +// +// An entitlement suspension is a long-running operation. +// +// Possible error codes: +// +// PERMISSION_DENIED: The customer doesn’t belong to the reseller. +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +// +// NOT_FOUND: Entitlement resource not found. +// +// NOT_ACTIVE: Entitlement is not active. +// +// INTERNAL: Any non-user error related to a technical issue in the +// backend. Contact Cloud Channel support. +// +// UNKNOWN: Any non-user error related to a technical issue in the backend. +// Contact Cloud Channel support. +// +// Return value: +// The ID of a long-running operation. +// +// To get the results of the operation, call the GetOperation method of +// CloudChannelOperationsService. The Operation metadata will contain an +// instance of OperationMetadata. +func (c *CloudChannelClient) SuspendEntitlement(ctx context.Context, req *channelpb.SuspendEntitlementRequest, opts ...gax.CallOption) (*SuspendEntitlementOperation, error) { + return c.internalClient.SuspendEntitlement(ctx, req, opts...) +} + +// SuspendEntitlementOperation returns a new SuspendEntitlementOperation from a given name. +// The name must be that of a previously created SuspendEntitlementOperation, possibly from a different process. +func (c *CloudChannelClient) SuspendEntitlementOperation(name string) *SuspendEntitlementOperation { + return c.internalClient.SuspendEntitlementOperation(name) +} + +// CancelEntitlement cancels a previously fulfilled entitlement. +// +// An entitlement cancellation is a long-running operation. +// +// Possible error codes: +// +// PERMISSION_DENIED: The reseller account making the request is different +// from the reseller account in the API request. +// +// FAILED_PRECONDITION: There are Google Cloud projects linked to the +// Google Cloud entitlement’s Cloud Billing subaccount. +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +// +// NOT_FOUND: Entitlement resource not found. +// +// DELETION_TYPE_NOT_ALLOWED: Cancel is only allowed for Google Workspace +// add-ons, or entitlements for Google Cloud’s development platform. +// +// INTERNAL: Any non-user error related to a technical issue in the +// backend. Contact Cloud Channel support. +// +// UNKNOWN: Any non-user error related to a technical issue in the backend. +// Contact Cloud Channel support. +// +// Return value: +// The ID of a long-running operation. +// +// To get the results of the operation, call the GetOperation method of +// CloudChannelOperationsService. The response will contain +// google.protobuf.Empty on success. The Operation metadata will contain an +// instance of OperationMetadata. +func (c *CloudChannelClient) CancelEntitlement(ctx context.Context, req *channelpb.CancelEntitlementRequest, opts ...gax.CallOption) (*CancelEntitlementOperation, error) { + return c.internalClient.CancelEntitlement(ctx, req, opts...) +} + +// CancelEntitlementOperation returns a new CancelEntitlementOperation from a given name. +// The name must be that of a previously created CancelEntitlementOperation, possibly from a different process. +func (c *CloudChannelClient) CancelEntitlementOperation(name string) *CancelEntitlementOperation { + return c.internalClient.CancelEntitlementOperation(name) +} + +// ActivateEntitlement activates a previously suspended entitlement. Entitlements suspended for +// pending ToS acceptance can’t be activated using this method. +// +// An entitlement activation is a long-running operation and it updates +// the state of the customer entitlement. +// +// Possible error codes: +// +// PERMISSION_DENIED: The reseller account making the request is different +// from the reseller account in the API request. +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +// +// NOT_FOUND: Entitlement resource not found. +// +// SUSPENSION_NOT_RESELLER_INITIATED: Can only activate reseller-initiated +// suspensions and entitlements that have accepted the TOS. +// +// NOT_SUSPENDED: Can only activate suspended entitlements not in an ACTIVE +// state. +// +// INTERNAL: Any non-user error related to a technical issue in the +// backend. Contact Cloud Channel support. +// +// UNKNOWN: Any non-user error related to a technical issue in the backend. +// Contact Cloud Channel support. +// +// Return value: +// The ID of a long-running operation. +// +// To get the results of the operation, call the GetOperation method of +// CloudChannelOperationsService. The Operation metadata will contain an +// instance of OperationMetadata. +func (c *CloudChannelClient) ActivateEntitlement(ctx context.Context, req *channelpb.ActivateEntitlementRequest, opts ...gax.CallOption) (*ActivateEntitlementOperation, error) { + return c.internalClient.ActivateEntitlement(ctx, req, opts...) +} + +// ActivateEntitlementOperation returns a new ActivateEntitlementOperation from a given name. +// The name must be that of a previously created ActivateEntitlementOperation, possibly from a different process. +func (c *CloudChannelClient) ActivateEntitlementOperation(name string) *ActivateEntitlementOperation { + return c.internalClient.ActivateEntitlementOperation(name) +} + +// TransferEntitlements transfers customer entitlements to new reseller. +// +// Possible error codes: +// +// PERMISSION_DENIED: The customer doesn’t belong to the reseller. +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +// +// NOT_FOUND: The customer or offer resource was not found. +// +// ALREADY_EXISTS: The SKU was already transferred for the customer. +// +// CONDITION_NOT_MET or FAILED_PRECONDITION: +// +// The SKU requires domain verification to transfer, but the domain is +// not verified. +// +// An Add-On SKU (example, Vault or Drive) is missing the +// pre-requisite SKU (example, G Suite Basic). +// +// (Developer accounts only) Reseller and resold domain must meet the +// following naming requirements: +// +// Domain names must start with goog-test. +// +// Domain names must include the reseller domain. +// +// Specify all transferring entitlements. +// +// INTERNAL: Any non-user error related to a technical issue in the +// backend. Contact Cloud Channel support. +// +// UNKNOWN: Any non-user error related to a technical issue in the backend. +// Contact Cloud Channel support. +// +// Return value: +// The ID of a long-running operation. +// +// To get the results of the operation, call the GetOperation method of +// CloudChannelOperationsService. The Operation metadata will contain an +// instance of OperationMetadata. +func (c *CloudChannelClient) TransferEntitlements(ctx context.Context, req *channelpb.TransferEntitlementsRequest, opts ...gax.CallOption) (*TransferEntitlementsOperation, error) { + return c.internalClient.TransferEntitlements(ctx, req, opts...) +} + +// TransferEntitlementsOperation returns a new TransferEntitlementsOperation from a given name. +// The name must be that of a previously created TransferEntitlementsOperation, possibly from a different process. +func (c *CloudChannelClient) TransferEntitlementsOperation(name string) *TransferEntitlementsOperation { + return c.internalClient.TransferEntitlementsOperation(name) +} + +// TransferEntitlementsToGoogle transfers customer entitlements from their current reseller to Google. +// +// Possible error codes: +// +// PERMISSION_DENIED: The customer doesn’t belong to the reseller. +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +// +// NOT_FOUND: The customer or offer resource was not found. +// +// ALREADY_EXISTS: The SKU was already transferred for the customer. +// +// CONDITION_NOT_MET or FAILED_PRECONDITION: +// +// The SKU requires domain verification to transfer, but the domain is +// not verified. +// +// An Add-On SKU (example, Vault or Drive) is missing the +// pre-requisite SKU (example, G Suite Basic). +// +// (Developer accounts only) Reseller and resold domain must meet the +// following naming requirements: +// +// Domain names must start with goog-test. +// +// Domain names must include the reseller domain. +// +// INTERNAL: Any non-user error related to a technical issue in the +// backend. Contact Cloud Channel support. +// +// UNKNOWN: Any non-user error related to a technical issue in the backend. +// Contact Cloud Channel support. +// +// Return value: +// The ID of a long-running operation. +// +// To get the results of the operation, call the GetOperation method of +// CloudChannelOperationsService. The response will contain +// google.protobuf.Empty on success. The Operation metadata will contain an +// instance of OperationMetadata. +func (c *CloudChannelClient) TransferEntitlementsToGoogle(ctx context.Context, req *channelpb.TransferEntitlementsToGoogleRequest, opts ...gax.CallOption) (*TransferEntitlementsToGoogleOperation, error) { + return c.internalClient.TransferEntitlementsToGoogle(ctx, req, opts...) +} + +// TransferEntitlementsToGoogleOperation returns a new TransferEntitlementsToGoogleOperation from a given name. +// The name must be that of a previously created TransferEntitlementsToGoogleOperation, possibly from a different process. +func (c *CloudChannelClient) TransferEntitlementsToGoogleOperation(name string) *TransferEntitlementsToGoogleOperation { + return c.internalClient.TransferEntitlementsToGoogleOperation(name) +} + +// ListChannelPartnerLinks list ChannelPartnerLinks belonging to a distributor. +// You must be a distributor to call this method. +// +// Possible error codes: +// +// PERMISSION_DENIED: The reseller account making the request is different +// from the reseller account in the API request. +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +// +// Return value: +// The list of the distributor account’s ChannelPartnerLink resources. +func (c *CloudChannelClient) ListChannelPartnerLinks(ctx context.Context, req *channelpb.ListChannelPartnerLinksRequest, opts ...gax.CallOption) *ChannelPartnerLinkIterator { + return c.internalClient.ListChannelPartnerLinks(ctx, req, opts...) +} + +// GetChannelPartnerLink returns the requested ChannelPartnerLink resource. +// You must be a distributor to call this method. +// +// Possible error codes: +// +// PERMISSION_DENIED: The reseller account making the request is different +// from the reseller account in the API request. +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +// +// NOT_FOUND: ChannelPartnerLink resource not found because of an +// invalid channel partner link name. +// +// Return value: +// The ChannelPartnerLink resource. +func (c *CloudChannelClient) GetChannelPartnerLink(ctx context.Context, req *channelpb.GetChannelPartnerLinkRequest, opts ...gax.CallOption) (*channelpb.ChannelPartnerLink, error) { + return c.internalClient.GetChannelPartnerLink(ctx, req, opts...) +} + +// CreateChannelPartnerLink initiates a channel partner link between a distributor and a reseller, or +// between resellers in an n-tier reseller channel. +// Invited partners need to follow the invite_link_uri provided in the +// response to accept. After accepting the invitation, a link is set up +// between the two parties. +// You must be a distributor to call this method. +// +// Possible error codes: +// +// PERMISSION_DENIED: The reseller account making the request is different +// from the reseller account in the API request. +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +// +// ALREADY_EXISTS: The ChannelPartnerLink sent in the request already +// exists. +// +// NOT_FOUND: No Cloud Identity customer exists for provided domain. +// +// INTERNAL: Any non-user error related to a technical issue in the +// backend. Contact Cloud Channel support. +// +// UNKNOWN: Any non-user error related to a technical issue in the backend. +// Contact Cloud Channel support. +// +// Return value: +// The new ChannelPartnerLink resource. +func (c *CloudChannelClient) CreateChannelPartnerLink(ctx context.Context, req *channelpb.CreateChannelPartnerLinkRequest, opts ...gax.CallOption) (*channelpb.ChannelPartnerLink, error) { + return c.internalClient.CreateChannelPartnerLink(ctx, req, opts...) +} + +// UpdateChannelPartnerLink updates a channel partner link. Distributors call this method to change a +// link’s status. For example, to suspend a partner link. +// You must be a distributor to call this method. +// +// Possible error codes: +// +// PERMISSION_DENIED: The reseller account making the request is different +// from the reseller account in the API request. +// +// INVALID_ARGUMENT: +// +// Required request parameters are missing or invalid. +// +// Link state cannot change from invited to active or suspended. +// +// Cannot send reseller_cloud_identity_id, invite_url, or name in update +// mask. +// +// NOT_FOUND: ChannelPartnerLink resource not found. +// +// INTERNAL: Any non-user error related to a technical issue in the +// backend. Contact Cloud Channel support. +// +// UNKNOWN: Any non-user error related to a technical issue in the backend. +// Contact Cloud Channel support. +// +// Return value: +// The updated ChannelPartnerLink resource. +func (c *CloudChannelClient) UpdateChannelPartnerLink(ctx context.Context, req *channelpb.UpdateChannelPartnerLinkRequest, opts ...gax.CallOption) (*channelpb.ChannelPartnerLink, error) { + return c.internalClient.UpdateChannelPartnerLink(ctx, req, opts...) +} + +// GetCustomerRepricingConfig gets information about how a Reseller modifies their bill before sending +// it to a Customer. +// +// Possible Error Codes: +// +// PERMISSION_DENIED: If the account making the request and the account +// being queried are different. +// +// NOT_FOUND: The CustomerRepricingConfig was not found. +// +// INTERNAL: Any non-user error related to technical issues in the +// backend. In this case, contact Cloud Channel support. +// +// Return Value: +// If successful, the CustomerRepricingConfig resource, otherwise returns +// an error. +func (c *CloudChannelClient) GetCustomerRepricingConfig(ctx context.Context, req *channelpb.GetCustomerRepricingConfigRequest, opts ...gax.CallOption) (*channelpb.CustomerRepricingConfig, error) { + return c.internalClient.GetCustomerRepricingConfig(ctx, req, opts...) +} + +// ListCustomerRepricingConfigs lists information about how a Reseller modifies their bill before sending +// it to a Customer. +// +// Possible Error Codes: +// +// PERMISSION_DENIED: If the account making the request and the account +// being queried are different. +// +// NOT_FOUND: The CustomerRepricingConfig specified does not exist or is +// not associated with the given account. +// +// INTERNAL: Any non-user error related to technical issues in the +// backend. In this case, contact Cloud Channel support. +// +// Return Value: +// If successful, the CustomerRepricingConfig resources. The +// data for each resource is displayed in the ascending order of: +// +// customer ID +// +// RepricingConfig.EntitlementGranularity.entitlement +// +// RepricingConfig.effective_invoice_month +// +// CustomerRepricingConfig.update_time +// +// If unsuccessful, returns an error. +func (c *CloudChannelClient) ListCustomerRepricingConfigs(ctx context.Context, req *channelpb.ListCustomerRepricingConfigsRequest, opts ...gax.CallOption) *CustomerRepricingConfigIterator { + return c.internalClient.ListCustomerRepricingConfigs(ctx, req, opts...) +} + +// CreateCustomerRepricingConfig creates a CustomerRepricingConfig. Call this method to set modifications +// for a specific customer’s bill. You can only create configs if the +// RepricingConfig.effective_invoice_month is a +// future month. If needed, you can create a config for the current month, +// with some restrictions. +// +// When creating a config for a future month, make sure there are no existing +// configs for that +// RepricingConfig.effective_invoice_month. +// +// The following restrictions are for creating configs in the current month. +// +// This functionality is reserved for recovering from an erroneous config, +// and should not be used for regular business cases. +// +// The new config will not modify exports used with other configs. +// Changes to the config may be immediate, but may take up to 24 hours. +// +// There is a limit of ten configs for any +// RepricingConfig.EntitlementGranularity.entitlement +// or RepricingConfig.effective_invoice_month. +// +// The contained CustomerRepricingConfig.repricing_config vaule must be +// different from the value used in the current config for a +// RepricingConfig.EntitlementGranularity.entitlement. +// +// Possible Error Codes: +// +// PERMISSION_DENIED: If the account making the request and the account +// being queried are different. +// +// INVALID_ARGUMENT: Missing or invalid required parameters in the +// request. Also displays if the updated config is for the current month or +// past months. +// +// NOT_FOUND: The CustomerRepricingConfig specified does not exist or is +// not associated with the given account. +// +// INTERNAL: Any non-user error related to technical issues in the +// backend. In this case, contact Cloud Channel support. +// +// Return Value: +// If successful, the updated CustomerRepricingConfig resource, otherwise +// returns an error. +func (c *CloudChannelClient) CreateCustomerRepricingConfig(ctx context.Context, req *channelpb.CreateCustomerRepricingConfigRequest, opts ...gax.CallOption) (*channelpb.CustomerRepricingConfig, error) { + return c.internalClient.CreateCustomerRepricingConfig(ctx, req, opts...) +} + +// UpdateCustomerRepricingConfig updates a CustomerRepricingConfig. Call this method to set modifications +// for a specific customer’s bill. This method overwrites the existing +// CustomerRepricingConfig. +// +// You can only update configs if the +// RepricingConfig.effective_invoice_month is a +// future month. To make changes to configs for the current month, use +// CreateCustomerRepricingConfig, taking note of its restrictions. You +// cannot update the RepricingConfig.effective_invoice_month. +// +// When updating a config in the future: +// +// This config must already exist. +// +// Possible Error Codes: +// +// PERMISSION_DENIED: If the account making the request and the account +// being queried are different. +// +// INVALID_ARGUMENT: Missing or invalid required parameters in the +// request. Also displays if the updated config is for the current month or +// past months. +// +// NOT_FOUND: The CustomerRepricingConfig specified does not exist or is +// not associated with the given account. +// +// INTERNAL: Any non-user error related to technical issues in the +// backend. In this case, contact Cloud Channel support. +// +// Return Value: +// If successful, the updated CustomerRepricingConfig resource, otherwise +// returns an error. +func (c *CloudChannelClient) UpdateCustomerRepricingConfig(ctx context.Context, req *channelpb.UpdateCustomerRepricingConfigRequest, opts ...gax.CallOption) (*channelpb.CustomerRepricingConfig, error) { + return c.internalClient.UpdateCustomerRepricingConfig(ctx, req, opts...) +} + +// DeleteCustomerRepricingConfig deletes the given CustomerRepricingConfig permanently. You can only +// delete configs if their RepricingConfig.effective_invoice_month is set +// to a date after the current month. +// +// Possible error codes: +// +// PERMISSION_DENIED: The account making the request does not own +// this customer. +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +// +// FAILED_PRECONDITION: The CustomerRepricingConfig is active or in the +// past. +// +// NOT_FOUND: No CustomerRepricingConfig found for the name in the +// request. +func (c *CloudChannelClient) DeleteCustomerRepricingConfig(ctx context.Context, req *channelpb.DeleteCustomerRepricingConfigRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteCustomerRepricingConfig(ctx, req, opts...) +} + +// GetChannelPartnerRepricingConfig gets information about how a Distributor modifies their bill before sending +// it to a ChannelPartner. +// +// Possible Error Codes: +// +// PERMISSION_DENIED: If the account making the request and the account +// being queried are different. +// +// NOT_FOUND: The ChannelPartnerRepricingConfig was not found. +// +// INTERNAL: Any non-user error related to technical issues in the +// backend. In this case, contact Cloud Channel support. +// +// Return Value: +// If successful, the ChannelPartnerRepricingConfig resource, otherwise +// returns an error. +func (c *CloudChannelClient) GetChannelPartnerRepricingConfig(ctx context.Context, req *channelpb.GetChannelPartnerRepricingConfigRequest, opts ...gax.CallOption) (*channelpb.ChannelPartnerRepricingConfig, error) { + return c.internalClient.GetChannelPartnerRepricingConfig(ctx, req, opts...) +} + +// ListChannelPartnerRepricingConfigs lists information about how a Reseller modifies their bill before sending +// it to a ChannelPartner. +// +// Possible Error Codes: +// +// PERMISSION_DENIED: If the account making the request and the account +// being queried are different. +// +// NOT_FOUND: The ChannelPartnerRepricingConfig specified does not exist +// or is not associated with the given account. +// +// INTERNAL: Any non-user error related to technical issues in the +// backend. In this case, contact Cloud Channel support. +// +// Return Value: +// If successful, the ChannelPartnerRepricingConfig resources. +// The data for each resource is displayed in the ascending order of: +// +// channel partner ID +// +// RepricingConfig.effective_invoice_month +// +// ChannelPartnerRepricingConfig.update_time +// +// If unsuccessful, returns an error. +func (c *CloudChannelClient) ListChannelPartnerRepricingConfigs(ctx context.Context, req *channelpb.ListChannelPartnerRepricingConfigsRequest, opts ...gax.CallOption) *ChannelPartnerRepricingConfigIterator { + return c.internalClient.ListChannelPartnerRepricingConfigs(ctx, req, opts...) +} + +// CreateChannelPartnerRepricingConfig creates a ChannelPartnerRepricingConfig. Call this method to set +// modifications for a specific ChannelPartner’s bill. You can only create +// configs if the RepricingConfig.effective_invoice_month is a future +// month. If needed, you can create a config for the current month, with some +// restrictions. +// +// When creating a config for a future month, make sure there are no existing +// configs for that +// RepricingConfig.effective_invoice_month. +// +// The following restrictions are for creating configs in the current month. +// +// This functionality is reserved for recovering from an erroneous config, +// and should not be used for regular business cases. +// +// The new config will not modify exports used with other configs. +// Changes to the config may be immediate, but may take up to 24 hours. +// +// There is a limit of ten configs for any ChannelPartner or +// RepricingConfig.effective_invoice_month. +// +// The contained ChannelPartnerRepricingConfig.repricing_config vaule +// must be different from the value used in the current config for a +// ChannelPartner. +// +// Possible Error Codes: +// +// PERMISSION_DENIED: If the account making the request and the account +// being queried are different. +// +// INVALID_ARGUMENT: Missing or invalid required parameters in the +// request. Also displays if the updated config is for the current month or +// past months. +// +// NOT_FOUND: The ChannelPartnerRepricingConfig specified does not exist +// or is not associated with the given account. +// +// INTERNAL: Any non-user error related to technical issues in the +// backend. In this case, contact Cloud Channel support. +// +// Return Value: +// If successful, the updated ChannelPartnerRepricingConfig resource, +// otherwise returns an error. +func (c *CloudChannelClient) CreateChannelPartnerRepricingConfig(ctx context.Context, req *channelpb.CreateChannelPartnerRepricingConfigRequest, opts ...gax.CallOption) (*channelpb.ChannelPartnerRepricingConfig, error) { + return c.internalClient.CreateChannelPartnerRepricingConfig(ctx, req, opts...) +} + +// UpdateChannelPartnerRepricingConfig updates a ChannelPartnerRepricingConfig. Call this method to set +// modifications for a specific ChannelPartner’s bill. This method overwrites +// the existing CustomerRepricingConfig. +// +// You can only update configs if the +// RepricingConfig.effective_invoice_month is a +// future month. To make changes to configs for the current month, use +// CreateChannelPartnerRepricingConfig, taking note of its restrictions. +// You cannot update the RepricingConfig.effective_invoice_month. +// +// When updating a config in the future: +// +// This config must already exist. +// +// Possible Error Codes: +// +// PERMISSION_DENIED: If the account making the request and the account +// being queried are different. +// +// INVALID_ARGUMENT: Missing or invalid required parameters in the +// request. Also displays if the updated config is for the current month or +// past months. +// +// NOT_FOUND: The ChannelPartnerRepricingConfig specified does not exist +// or is not associated with the given account. +// +// INTERNAL: Any non-user error related to technical issues in the +// backend. In this case, contact Cloud Channel support. +// +// Return Value: +// If successful, the updated ChannelPartnerRepricingConfig resource, +// otherwise returns an error. +func (c *CloudChannelClient) UpdateChannelPartnerRepricingConfig(ctx context.Context, req *channelpb.UpdateChannelPartnerRepricingConfigRequest, opts ...gax.CallOption) (*channelpb.ChannelPartnerRepricingConfig, error) { + return c.internalClient.UpdateChannelPartnerRepricingConfig(ctx, req, opts...) +} + +// DeleteChannelPartnerRepricingConfig deletes the given ChannelPartnerRepricingConfig permanently. You can +// only delete configs if their RepricingConfig.effective_invoice_month is +// set to a date after the current month. +// +// Possible error codes: +// +// PERMISSION_DENIED: The account making the request does not own +// this customer. +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +// +// FAILED_PRECONDITION: The ChannelPartnerRepricingConfig is active or +// in the past. +// +// NOT_FOUND: No ChannelPartnerRepricingConfig found for the name in the +// request. +func (c *CloudChannelClient) DeleteChannelPartnerRepricingConfig(ctx context.Context, req *channelpb.DeleteChannelPartnerRepricingConfigRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteChannelPartnerRepricingConfig(ctx, req, opts...) +} + +// LookupOffer returns the requested Offer resource. +// +// Possible error codes: +// +// PERMISSION_DENIED: The entitlement doesn’t belong to the reseller. +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +// +// NOT_FOUND: Entitlement or offer was not found. +// +// Return value: +// The Offer resource. +func (c *CloudChannelClient) LookupOffer(ctx context.Context, req *channelpb.LookupOfferRequest, opts ...gax.CallOption) (*channelpb.Offer, error) { + return c.internalClient.LookupOffer(ctx, req, opts...) +} + +// ListProducts lists the Products the reseller is authorized to sell. +// +// Possible error codes: +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +func (c *CloudChannelClient) ListProducts(ctx context.Context, req *channelpb.ListProductsRequest, opts ...gax.CallOption) *ProductIterator { + return c.internalClient.ListProducts(ctx, req, opts...) +} + +// ListSkus lists the SKUs for a product the reseller is authorized to sell. +// +// Possible error codes: +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +func (c *CloudChannelClient) ListSkus(ctx context.Context, req *channelpb.ListSkusRequest, opts ...gax.CallOption) *SkuIterator { + return c.internalClient.ListSkus(ctx, req, opts...) +} + +// ListOffers lists the Offers the reseller can sell. +// +// Possible error codes: +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +func (c *CloudChannelClient) ListOffers(ctx context.Context, req *channelpb.ListOffersRequest, opts ...gax.CallOption) *OfferIterator { + return c.internalClient.ListOffers(ctx, req, opts...) +} + +// ListPurchasableSkus lists the following: +// +// SKUs that you can purchase for a customer +// +// SKUs that you can upgrade or downgrade for an entitlement. +// +// Possible error codes: +// +// PERMISSION_DENIED: The customer doesn’t belong to the reseller. +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +func (c *CloudChannelClient) ListPurchasableSkus(ctx context.Context, req *channelpb.ListPurchasableSkusRequest, opts ...gax.CallOption) *PurchasableSkuIterator { + return c.internalClient.ListPurchasableSkus(ctx, req, opts...) +} + +// ListPurchasableOffers lists the following: +// +// Offers that you can purchase for a customer. +// +// Offers that you can change for an entitlement. +// +// Possible error codes: +// +// PERMISSION_DENIED: The customer doesn’t belong to the reseller +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +func (c *CloudChannelClient) ListPurchasableOffers(ctx context.Context, req *channelpb.ListPurchasableOffersRequest, opts ...gax.CallOption) *PurchasableOfferIterator { + return c.internalClient.ListPurchasableOffers(ctx, req, opts...) +} + +// RegisterSubscriber registers a service account with subscriber privileges on the Cloud Pub/Sub +// topic for this Channel Services account. After you create a +// subscriber, you get the events through SubscriberEvent +// +// Possible error codes: +// +// PERMISSION_DENIED: The reseller account making the request and the +// provided reseller account are different, or the impersonated user +// is not a super admin. +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +// +// INTERNAL: Any non-user error related to a technical issue in the +// backend. Contact Cloud Channel support. +// +// UNKNOWN: Any non-user error related to a technical issue in the backend. +// Contact Cloud Channel support. +// +// Return value: +// The topic name with the registered service email address. +func (c *CloudChannelClient) RegisterSubscriber(ctx context.Context, req *channelpb.RegisterSubscriberRequest, opts ...gax.CallOption) (*channelpb.RegisterSubscriberResponse, error) { + return c.internalClient.RegisterSubscriber(ctx, req, opts...) +} + +// UnregisterSubscriber unregisters a service account with subscriber privileges on the Cloud +// Pub/Sub topic created for this Channel Services account. If there are no +// service accounts left with subscriber privileges, this deletes the topic. +// You can call ListSubscribers to check for these accounts. +// +// Possible error codes: +// +// PERMISSION_DENIED: The reseller account making the request and the +// provided reseller account are different, or the impersonated user +// is not a super admin. +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +// +// NOT_FOUND: The topic resource doesn’t exist. +// +// INTERNAL: Any non-user error related to a technical issue in the +// backend. Contact Cloud Channel support. +// +// UNKNOWN: Any non-user error related to a technical issue in the backend. +// Contact Cloud Channel support. +// +// Return value: +// The topic name that unregistered the service email address. +// Returns a success response if the service email address wasn’t registered +// with the topic. +func (c *CloudChannelClient) UnregisterSubscriber(ctx context.Context, req *channelpb.UnregisterSubscriberRequest, opts ...gax.CallOption) (*channelpb.UnregisterSubscriberResponse, error) { + return c.internalClient.UnregisterSubscriber(ctx, req, opts...) +} + +// ListSubscribers lists service accounts with subscriber privileges on the Cloud Pub/Sub +// topic created for this Channel Services account. +// +// Possible error codes: +// +// PERMISSION_DENIED: The reseller account making the request and the +// provided reseller account are different, or the impersonated user +// is not a super admin. +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +// +// NOT_FOUND: The topic resource doesn’t exist. +// +// INTERNAL: Any non-user error related to a technical issue in the +// backend. Contact Cloud Channel support. +// +// UNKNOWN: Any non-user error related to a technical issue in the backend. +// Contact Cloud Channel support. +// +// Return value: +// A list of service email addresses. +func (c *CloudChannelClient) ListSubscribers(ctx context.Context, req *channelpb.ListSubscribersRequest, opts ...gax.CallOption) *StringIterator { + return c.internalClient.ListSubscribers(ctx, req, opts...) +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *CloudChannelClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + return c.internalClient.CancelOperation(ctx, req, opts...) +} + +// DeleteOperation is a utility method from google.longrunning.Operations. +func (c *CloudChannelClient) DeleteOperation(ctx context.Context, req *longrunningpb.DeleteOperationRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteOperation(ctx, req, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *CloudChannelClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + return c.internalClient.GetOperation(ctx, req, opts...) +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *CloudChannelClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + return c.internalClient.ListOperations(ctx, req, opts...) +} + +// cloudChannelGRPCClient is a client for interacting with Cloud Channel API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type cloudChannelGRPCClient struct { + // Connection pool of gRPC connections to the service. + connPool gtransport.ConnPool + + // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE + disableDeadlines bool + + // Points back to the CallOptions field of the containing CloudChannelClient + CallOptions **CloudChannelCallOptions + + // The gRPC API client. + cloudChannelClient channelpb.CloudChannelServiceClient + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + operationsClient longrunningpb.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD +} + +// NewCloudChannelClient creates a new cloud channel service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. +// +// CloudChannelService lets Google cloud resellers and distributors manage +// their customers, channel partners, entitlements, and reports. +// +// Using this service: +// +// Resellers and distributors can manage a customer entity. +// +// Distributors can register an authorized reseller in their channel and +// provide them with delegated admin access. +// +// Resellers and distributors can manage customer entitlements. +// +// CloudChannelService exposes the following resources: +// +// Customers: An entity—usually an enterprise—managed by a reseller or +// distributor. +// +// Entitlements: An entity that provides a customer with the means to use +// a service. Entitlements are created or updated as a result of a successful +// fulfillment. +// +// ChannelPartnerLinks: An entity that identifies links between +// distributors and their indirect resellers in a channel. +func NewCloudChannelClient(ctx context.Context, opts ...option.ClientOption) (*CloudChannelClient, error) { + clientOpts := defaultCloudChannelGRPCClientOptions() + if newCloudChannelClientHook != nil { + hookOpts, err := newCloudChannelClientHook(ctx, clientHookParams{}) + if err != nil { + return nil, err + } + clientOpts = append(clientOpts, hookOpts...) + } + + disableDeadlines, err := checkDisableDeadlines() + if err != nil { + return nil, err + } + + connPool, err := gtransport.DialPool(ctx, append(clientOpts, opts...)...) + if err != nil { + return nil, err + } + client := CloudChannelClient{CallOptions: defaultCloudChannelCallOptions()} + + c := &cloudChannelGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, + cloudChannelClient: channelpb.NewCloudChannelServiceClient(connPool), + CallOptions: &client.CallOptions, + operationsClient: longrunningpb.NewOperationsClient(connPool), + } + c.setGoogleClientInfo() + + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + if err != nil { + // This error "should not happen", since we are just reusing old connection pool + // and never actually need to dial. + // If this does happen, we could leak connp. However, we cannot close conn: + // If the user invoked the constructor with option.WithGRPCConn, + // we would close a connection that's still in use. + // TODO: investigate error conditions. + return nil, err + } + c.LROClient = &client.LROClient + return &client, nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: Connections are now pooled so this method does not always +// return the same resource. +func (c *cloudChannelGRPCClient) Connection() *grpc.ClientConn { + return c.connPool.Conn() +} + +// 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 *cloudChannelGRPCClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "grpc", grpc.Version) + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *cloudChannelGRPCClient) Close() error { + return c.connPool.Close() +} + +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type cloudChannelRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing CloudChannelClient + CallOptions **CloudChannelCallOptions +} + +// NewCloudChannelRESTClient creates a new cloud channel service rest client. +// +// CloudChannelService lets Google cloud resellers and distributors manage +// their customers, channel partners, entitlements, and reports. +// +// Using this service: +// +// Resellers and distributors can manage a customer entity. +// +// Distributors can register an authorized reseller in their channel and +// provide them with delegated admin access. +// +// Resellers and distributors can manage customer entitlements. +// +// CloudChannelService exposes the following resources: +// +// Customers: An entity—usually an enterprise—managed by a reseller or +// distributor. +// +// Entitlements: An entity that provides a customer with the means to use +// a service. Entitlements are created or updated as a result of a successful +// fulfillment. +// +// ChannelPartnerLinks: An entity that identifies links between +// distributors and their indirect resellers in a channel. +func NewCloudChannelRESTClient(ctx context.Context, opts ...option.ClientOption) (*CloudChannelClient, error) { + clientOpts := append(defaultCloudChannelRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultCloudChannelRESTCallOptions() + c := &cloudChannelRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &CloudChannelClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultCloudChannelRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://cloudchannel.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://cloudchannel.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://cloudchannel.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *cloudChannelRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *cloudChannelRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *cloudChannelRESTClient) Connection() *grpc.ClientConn { + return nil +} +func (c *cloudChannelGRPCClient) ListCustomers(ctx context.Context, req *channelpb.ListCustomersRequest, opts ...gax.CallOption) *CustomerIterator { + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).ListCustomers[0:len((*c.CallOptions).ListCustomers):len((*c.CallOptions).ListCustomers)], opts...) + it := &CustomerIterator{} + req = proto.Clone(req).(*channelpb.ListCustomersRequest) + it.InternalFetch = func(pageSize int, pageToken string) ([]*channelpb.Customer, string, error) { + resp := &channelpb.ListCustomersResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.cloudChannelClient.ListCustomers(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, "", err + } + + it.Response = resp + return resp.GetCustomers(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +func (c *cloudChannelGRPCClient) GetCustomer(ctx context.Context, req *channelpb.GetCustomerRequest, opts ...gax.CallOption) (*channelpb.Customer, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).GetCustomer[0:len((*c.CallOptions).GetCustomer):len((*c.CallOptions).GetCustomer)], opts...) + var resp *channelpb.Customer + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.cloudChannelClient.GetCustomer(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *cloudChannelGRPCClient) CheckCloudIdentityAccountsExist(ctx context.Context, req *channelpb.CheckCloudIdentityAccountsExistRequest, opts ...gax.CallOption) (*channelpb.CheckCloudIdentityAccountsExistResponse, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).CheckCloudIdentityAccountsExist[0:len((*c.CallOptions).CheckCloudIdentityAccountsExist):len((*c.CallOptions).CheckCloudIdentityAccountsExist)], opts...) + var resp *channelpb.CheckCloudIdentityAccountsExistResponse + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.cloudChannelClient.CheckCloudIdentityAccountsExist(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *cloudChannelGRPCClient) CreateCustomer(ctx context.Context, req *channelpb.CreateCustomerRequest, opts ...gax.CallOption) (*channelpb.Customer, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).CreateCustomer[0:len((*c.CallOptions).CreateCustomer):len((*c.CallOptions).CreateCustomer)], opts...) + var resp *channelpb.Customer + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.cloudChannelClient.CreateCustomer(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *cloudChannelGRPCClient) UpdateCustomer(ctx context.Context, req *channelpb.UpdateCustomerRequest, opts ...gax.CallOption) (*channelpb.Customer, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "customer.name", url.QueryEscape(req.GetCustomer().GetName()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).UpdateCustomer[0:len((*c.CallOptions).UpdateCustomer):len((*c.CallOptions).UpdateCustomer)], opts...) + var resp *channelpb.Customer + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.cloudChannelClient.UpdateCustomer(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *cloudChannelGRPCClient) DeleteCustomer(ctx context.Context, req *channelpb.DeleteCustomerRequest, opts ...gax.CallOption) error { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).DeleteCustomer[0:len((*c.CallOptions).DeleteCustomer):len((*c.CallOptions).DeleteCustomer)], opts...) + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + _, err = c.cloudChannelClient.DeleteCustomer(ctx, req, settings.GRPC...) + return err + }, opts...) + return err +} + +func (c *cloudChannelGRPCClient) ImportCustomer(ctx context.Context, req *channelpb.ImportCustomerRequest, opts ...gax.CallOption) (*channelpb.Customer, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).ImportCustomer[0:len((*c.CallOptions).ImportCustomer):len((*c.CallOptions).ImportCustomer)], opts...) + var resp *channelpb.Customer + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.cloudChannelClient.ImportCustomer(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *cloudChannelGRPCClient) ProvisionCloudIdentity(ctx context.Context, req *channelpb.ProvisionCloudIdentityRequest, opts ...gax.CallOption) (*ProvisionCloudIdentityOperation, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "customer", url.QueryEscape(req.GetCustomer()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).ProvisionCloudIdentity[0:len((*c.CallOptions).ProvisionCloudIdentity):len((*c.CallOptions).ProvisionCloudIdentity)], opts...) + var resp *longrunningpb.Operation + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.cloudChannelClient.ProvisionCloudIdentity(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return &ProvisionCloudIdentityOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + }, nil +} + +func (c *cloudChannelGRPCClient) ListEntitlements(ctx context.Context, req *channelpb.ListEntitlementsRequest, opts ...gax.CallOption) *EntitlementIterator { + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).ListEntitlements[0:len((*c.CallOptions).ListEntitlements):len((*c.CallOptions).ListEntitlements)], opts...) + it := &EntitlementIterator{} + req = proto.Clone(req).(*channelpb.ListEntitlementsRequest) + it.InternalFetch = func(pageSize int, pageToken string) ([]*channelpb.Entitlement, string, error) { + resp := &channelpb.ListEntitlementsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.cloudChannelClient.ListEntitlements(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, "", err + } + + it.Response = resp + return resp.GetEntitlements(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +func (c *cloudChannelGRPCClient) ListTransferableSkus(ctx context.Context, req *channelpb.ListTransferableSkusRequest, opts ...gax.CallOption) *TransferableSkuIterator { + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).ListTransferableSkus[0:len((*c.CallOptions).ListTransferableSkus):len((*c.CallOptions).ListTransferableSkus)], opts...) + it := &TransferableSkuIterator{} + req = proto.Clone(req).(*channelpb.ListTransferableSkusRequest) + it.InternalFetch = func(pageSize int, pageToken string) ([]*channelpb.TransferableSku, string, error) { + resp := &channelpb.ListTransferableSkusResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.cloudChannelClient.ListTransferableSkus(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, "", err + } + + it.Response = resp + return resp.GetTransferableSkus(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +func (c *cloudChannelGRPCClient) ListTransferableOffers(ctx context.Context, req *channelpb.ListTransferableOffersRequest, opts ...gax.CallOption) *TransferableOfferIterator { + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).ListTransferableOffers[0:len((*c.CallOptions).ListTransferableOffers):len((*c.CallOptions).ListTransferableOffers)], opts...) + it := &TransferableOfferIterator{} + req = proto.Clone(req).(*channelpb.ListTransferableOffersRequest) + it.InternalFetch = func(pageSize int, pageToken string) ([]*channelpb.TransferableOffer, string, error) { + resp := &channelpb.ListTransferableOffersResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.cloudChannelClient.ListTransferableOffers(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, "", err + } + + it.Response = resp + return resp.GetTransferableOffers(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +func (c *cloudChannelGRPCClient) GetEntitlement(ctx context.Context, req *channelpb.GetEntitlementRequest, opts ...gax.CallOption) (*channelpb.Entitlement, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).GetEntitlement[0:len((*c.CallOptions).GetEntitlement):len((*c.CallOptions).GetEntitlement)], opts...) + var resp *channelpb.Entitlement + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.cloudChannelClient.GetEntitlement(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *cloudChannelGRPCClient) CreateEntitlement(ctx context.Context, req *channelpb.CreateEntitlementRequest, opts ...gax.CallOption) (*CreateEntitlementOperation, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).CreateEntitlement[0:len((*c.CallOptions).CreateEntitlement):len((*c.CallOptions).CreateEntitlement)], opts...) + var resp *longrunningpb.Operation + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.cloudChannelClient.CreateEntitlement(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return &CreateEntitlementOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + }, nil +} + +func (c *cloudChannelGRPCClient) ChangeParameters(ctx context.Context, req *channelpb.ChangeParametersRequest, opts ...gax.CallOption) (*ChangeParametersOperation, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).ChangeParameters[0:len((*c.CallOptions).ChangeParameters):len((*c.CallOptions).ChangeParameters)], opts...) + var resp *longrunningpb.Operation + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.cloudChannelClient.ChangeParameters(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return &ChangeParametersOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + }, nil +} + +func (c *cloudChannelGRPCClient) ChangeRenewalSettings(ctx context.Context, req *channelpb.ChangeRenewalSettingsRequest, opts ...gax.CallOption) (*ChangeRenewalSettingsOperation, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).ChangeRenewalSettings[0:len((*c.CallOptions).ChangeRenewalSettings):len((*c.CallOptions).ChangeRenewalSettings)], opts...) + var resp *longrunningpb.Operation + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.cloudChannelClient.ChangeRenewalSettings(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return &ChangeRenewalSettingsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + }, nil +} + +func (c *cloudChannelGRPCClient) ChangeOffer(ctx context.Context, req *channelpb.ChangeOfferRequest, opts ...gax.CallOption) (*ChangeOfferOperation, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).ChangeOffer[0:len((*c.CallOptions).ChangeOffer):len((*c.CallOptions).ChangeOffer)], opts...) + var resp *longrunningpb.Operation + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.cloudChannelClient.ChangeOffer(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return &ChangeOfferOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + }, nil +} + +func (c *cloudChannelGRPCClient) StartPaidService(ctx context.Context, req *channelpb.StartPaidServiceRequest, opts ...gax.CallOption) (*StartPaidServiceOperation, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).StartPaidService[0:len((*c.CallOptions).StartPaidService):len((*c.CallOptions).StartPaidService)], opts...) + var resp *longrunningpb.Operation + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.cloudChannelClient.StartPaidService(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return &StartPaidServiceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + }, nil +} + +func (c *cloudChannelGRPCClient) SuspendEntitlement(ctx context.Context, req *channelpb.SuspendEntitlementRequest, opts ...gax.CallOption) (*SuspendEntitlementOperation, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).SuspendEntitlement[0:len((*c.CallOptions).SuspendEntitlement):len((*c.CallOptions).SuspendEntitlement)], opts...) + var resp *longrunningpb.Operation + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.cloudChannelClient.SuspendEntitlement(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return &SuspendEntitlementOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + }, nil +} + +func (c *cloudChannelGRPCClient) CancelEntitlement(ctx context.Context, req *channelpb.CancelEntitlementRequest, opts ...gax.CallOption) (*CancelEntitlementOperation, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).CancelEntitlement[0:len((*c.CallOptions).CancelEntitlement):len((*c.CallOptions).CancelEntitlement)], opts...) + var resp *longrunningpb.Operation + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.cloudChannelClient.CancelEntitlement(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return &CancelEntitlementOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + }, nil +} + +func (c *cloudChannelGRPCClient) ActivateEntitlement(ctx context.Context, req *channelpb.ActivateEntitlementRequest, opts ...gax.CallOption) (*ActivateEntitlementOperation, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).ActivateEntitlement[0:len((*c.CallOptions).ActivateEntitlement):len((*c.CallOptions).ActivateEntitlement)], opts...) + var resp *longrunningpb.Operation + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.cloudChannelClient.ActivateEntitlement(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return &ActivateEntitlementOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + }, nil +} + +func (c *cloudChannelGRPCClient) TransferEntitlements(ctx context.Context, req *channelpb.TransferEntitlementsRequest, opts ...gax.CallOption) (*TransferEntitlementsOperation, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).TransferEntitlements[0:len((*c.CallOptions).TransferEntitlements):len((*c.CallOptions).TransferEntitlements)], opts...) + var resp *longrunningpb.Operation + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.cloudChannelClient.TransferEntitlements(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return &TransferEntitlementsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + }, nil +} + +func (c *cloudChannelGRPCClient) TransferEntitlementsToGoogle(ctx context.Context, req *channelpb.TransferEntitlementsToGoogleRequest, opts ...gax.CallOption) (*TransferEntitlementsToGoogleOperation, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).TransferEntitlementsToGoogle[0:len((*c.CallOptions).TransferEntitlementsToGoogle):len((*c.CallOptions).TransferEntitlementsToGoogle)], opts...) + var resp *longrunningpb.Operation + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.cloudChannelClient.TransferEntitlementsToGoogle(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return &TransferEntitlementsToGoogleOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + }, nil +} + +func (c *cloudChannelGRPCClient) ListChannelPartnerLinks(ctx context.Context, req *channelpb.ListChannelPartnerLinksRequest, opts ...gax.CallOption) *ChannelPartnerLinkIterator { + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).ListChannelPartnerLinks[0:len((*c.CallOptions).ListChannelPartnerLinks):len((*c.CallOptions).ListChannelPartnerLinks)], opts...) + it := &ChannelPartnerLinkIterator{} + req = proto.Clone(req).(*channelpb.ListChannelPartnerLinksRequest) + it.InternalFetch = func(pageSize int, pageToken string) ([]*channelpb.ChannelPartnerLink, string, error) { + resp := &channelpb.ListChannelPartnerLinksResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.cloudChannelClient.ListChannelPartnerLinks(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, "", err + } + + it.Response = resp + return resp.GetChannelPartnerLinks(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +func (c *cloudChannelGRPCClient) GetChannelPartnerLink(ctx context.Context, req *channelpb.GetChannelPartnerLinkRequest, opts ...gax.CallOption) (*channelpb.ChannelPartnerLink, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).GetChannelPartnerLink[0:len((*c.CallOptions).GetChannelPartnerLink):len((*c.CallOptions).GetChannelPartnerLink)], opts...) + var resp *channelpb.ChannelPartnerLink + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.cloudChannelClient.GetChannelPartnerLink(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *cloudChannelGRPCClient) CreateChannelPartnerLink(ctx context.Context, req *channelpb.CreateChannelPartnerLinkRequest, opts ...gax.CallOption) (*channelpb.ChannelPartnerLink, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).CreateChannelPartnerLink[0:len((*c.CallOptions).CreateChannelPartnerLink):len((*c.CallOptions).CreateChannelPartnerLink)], opts...) + var resp *channelpb.ChannelPartnerLink + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.cloudChannelClient.CreateChannelPartnerLink(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *cloudChannelGRPCClient) UpdateChannelPartnerLink(ctx context.Context, req *channelpb.UpdateChannelPartnerLinkRequest, opts ...gax.CallOption) (*channelpb.ChannelPartnerLink, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).UpdateChannelPartnerLink[0:len((*c.CallOptions).UpdateChannelPartnerLink):len((*c.CallOptions).UpdateChannelPartnerLink)], opts...) + var resp *channelpb.ChannelPartnerLink + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.cloudChannelClient.UpdateChannelPartnerLink(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *cloudChannelGRPCClient) GetCustomerRepricingConfig(ctx context.Context, req *channelpb.GetCustomerRepricingConfigRequest, opts ...gax.CallOption) (*channelpb.CustomerRepricingConfig, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).GetCustomerRepricingConfig[0:len((*c.CallOptions).GetCustomerRepricingConfig):len((*c.CallOptions).GetCustomerRepricingConfig)], opts...) + var resp *channelpb.CustomerRepricingConfig + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.cloudChannelClient.GetCustomerRepricingConfig(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *cloudChannelGRPCClient) ListCustomerRepricingConfigs(ctx context.Context, req *channelpb.ListCustomerRepricingConfigsRequest, opts ...gax.CallOption) *CustomerRepricingConfigIterator { + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).ListCustomerRepricingConfigs[0:len((*c.CallOptions).ListCustomerRepricingConfigs):len((*c.CallOptions).ListCustomerRepricingConfigs)], opts...) + it := &CustomerRepricingConfigIterator{} + req = proto.Clone(req).(*channelpb.ListCustomerRepricingConfigsRequest) + it.InternalFetch = func(pageSize int, pageToken string) ([]*channelpb.CustomerRepricingConfig, string, error) { + resp := &channelpb.ListCustomerRepricingConfigsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.cloudChannelClient.ListCustomerRepricingConfigs(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, "", err + } + + it.Response = resp + return resp.GetCustomerRepricingConfigs(), resp.GetNextPageToken(), 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 + } - // The call options for this service. - CallOptions *CloudChannelCallOptions + it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() - // LROClient is used internally to handle long-running operations. - // It is exposed so that its CallOptions can be modified if required. - // Users should not Close this client. - LROClient *lroauto.OperationsClient + return it } -// Wrapper methods routed to the internal client. +func (c *cloudChannelGRPCClient) CreateCustomerRepricingConfig(ctx context.Context, req *channelpb.CreateCustomerRepricingConfigRequest, opts ...gax.CallOption) (*channelpb.CustomerRepricingConfig, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *CloudChannelClient) Close() error { - return c.internalClient.Close() + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).CreateCustomerRepricingConfig[0:len((*c.CallOptions).CreateCustomerRepricingConfig):len((*c.CallOptions).CreateCustomerRepricingConfig)], opts...) + var resp *channelpb.CustomerRepricingConfig + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.cloudChannelClient.CreateCustomerRepricingConfig(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return resp, nil } -// 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 *CloudChannelClient) setGoogleClientInfo(keyval ...string) { - c.internalClient.setGoogleClientInfo(keyval...) -} +func (c *cloudChannelGRPCClient) UpdateCustomerRepricingConfig(ctx context.Context, req *channelpb.UpdateCustomerRepricingConfigRequest, opts ...gax.CallOption) (*channelpb.CustomerRepricingConfig, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "customer_repricing_config.name", url.QueryEscape(req.GetCustomerRepricingConfig().GetName()))) -// Connection returns a connection to the API service. -// -// Deprecated: Connections are now pooled so this method does not always -// return the same resource. -func (c *CloudChannelClient) Connection() *grpc.ClientConn { - return c.internalClient.Connection() + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).UpdateCustomerRepricingConfig[0:len((*c.CallOptions).UpdateCustomerRepricingConfig):len((*c.CallOptions).UpdateCustomerRepricingConfig)], opts...) + var resp *channelpb.CustomerRepricingConfig + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.cloudChannelClient.UpdateCustomerRepricingConfig(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return resp, nil } -// ListCustomers list Customers. -// -// Possible error codes: -// -// PERMISSION_DENIED: The reseller account making the request is different -// from the reseller account in the API request. -// -// INVALID_ARGUMENT: Required request parameters are missing or invalid. -// -// Return value: -// List of Customers, or an empty list if there are no customers. -func (c *CloudChannelClient) ListCustomers(ctx context.Context, req *channelpb.ListCustomersRequest, opts ...gax.CallOption) *CustomerIterator { - return c.internalClient.ListCustomers(ctx, req, opts...) -} +func (c *cloudChannelGRPCClient) DeleteCustomerRepricingConfig(ctx context.Context, req *channelpb.DeleteCustomerRepricingConfigRequest, opts ...gax.CallOption) error { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) -// GetCustomer returns the requested Customer resource. -// -// Possible error codes: -// -// PERMISSION_DENIED: The reseller account making the request is different -// from the reseller account in the API request. -// -// INVALID_ARGUMENT: Required request parameters are missing or invalid. -// -// NOT_FOUND: The customer resource doesn’t exist. Usually the result of an -// invalid name parameter. -// -// Return value: -// The Customer resource. -func (c *CloudChannelClient) GetCustomer(ctx context.Context, req *channelpb.GetCustomerRequest, opts ...gax.CallOption) (*channelpb.Customer, error) { - return c.internalClient.GetCustomer(ctx, req, opts...) + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).DeleteCustomerRepricingConfig[0:len((*c.CallOptions).DeleteCustomerRepricingConfig):len((*c.CallOptions).DeleteCustomerRepricingConfig)], opts...) + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + _, err = c.cloudChannelClient.DeleteCustomerRepricingConfig(ctx, req, settings.GRPC...) + return err + }, opts...) + return err } -// CheckCloudIdentityAccountsExist confirms the existence of Cloud Identity accounts based on the domain and -// if the Cloud Identity accounts are owned by the reseller. -// -// Possible error codes: -// -// PERMISSION_DENIED: The reseller account making the request is different -// from the reseller account in the API request. -// -// INVALID_ARGUMENT: Required request parameters are missing or invalid. -// -// INVALID_VALUE: Invalid domain value in the request. -// -// Return value: -// A list of CloudIdentityCustomerAccount resources for the domain (may be -// empty) -// -// Note: in the v1alpha1 version of the API, a NOT_FOUND error returns if -// no CloudIdentityCustomerAccount resources match the domain. -func (c *CloudChannelClient) CheckCloudIdentityAccountsExist(ctx context.Context, req *channelpb.CheckCloudIdentityAccountsExistRequest, opts ...gax.CallOption) (*channelpb.CheckCloudIdentityAccountsExistResponse, error) { - return c.internalClient.CheckCloudIdentityAccountsExist(ctx, req, opts...) -} +func (c *cloudChannelGRPCClient) GetChannelPartnerRepricingConfig(ctx context.Context, req *channelpb.GetChannelPartnerRepricingConfigRequest, opts ...gax.CallOption) (*channelpb.ChannelPartnerRepricingConfig, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) -// CreateCustomer creates a new Customer resource under the reseller or distributor -// account. -// -// Possible error codes: -// -// PERMISSION_DENIED: The reseller account making the request is different -// from the reseller account in the API request. -// -// INVALID_ARGUMENT: -// -// Required request parameters are missing or invalid. -// -// Domain field value doesn’t match the primary email domain. -// -// Return value: -// The newly created Customer resource. -func (c *CloudChannelClient) CreateCustomer(ctx context.Context, req *channelpb.CreateCustomerRequest, opts ...gax.CallOption) (*channelpb.Customer, error) { - return c.internalClient.CreateCustomer(ctx, req, opts...) + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).GetChannelPartnerRepricingConfig[0:len((*c.CallOptions).GetChannelPartnerRepricingConfig):len((*c.CallOptions).GetChannelPartnerRepricingConfig)], opts...) + var resp *channelpb.ChannelPartnerRepricingConfig + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.cloudChannelClient.GetChannelPartnerRepricingConfig(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return resp, nil } -// UpdateCustomer updates an existing Customer resource for the reseller or -// distributor. -// -// Possible error codes: -// -// PERMISSION_DENIED: The reseller account making the request is different -// from the reseller account in the API request. -// -// INVALID_ARGUMENT: Required request parameters are missing or invalid. -// -// NOT_FOUND: No Customer resource found for the name in the request. -// -// Return value: -// The updated Customer resource. -func (c *CloudChannelClient) UpdateCustomer(ctx context.Context, req *channelpb.UpdateCustomerRequest, opts ...gax.CallOption) (*channelpb.Customer, error) { - return c.internalClient.UpdateCustomer(ctx, req, opts...) +func (c *cloudChannelGRPCClient) ListChannelPartnerRepricingConfigs(ctx context.Context, req *channelpb.ListChannelPartnerRepricingConfigsRequest, opts ...gax.CallOption) *ChannelPartnerRepricingConfigIterator { + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).ListChannelPartnerRepricingConfigs[0:len((*c.CallOptions).ListChannelPartnerRepricingConfigs):len((*c.CallOptions).ListChannelPartnerRepricingConfigs)], opts...) + it := &ChannelPartnerRepricingConfigIterator{} + req = proto.Clone(req).(*channelpb.ListChannelPartnerRepricingConfigsRequest) + it.InternalFetch = func(pageSize int, pageToken string) ([]*channelpb.ChannelPartnerRepricingConfig, string, error) { + resp := &channelpb.ListChannelPartnerRepricingConfigsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.cloudChannelClient.ListChannelPartnerRepricingConfigs(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, "", err + } + + it.Response = resp + return resp.GetChannelPartnerRepricingConfigs(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it } -// DeleteCustomer deletes the given Customer permanently. -// -// Possible error codes: -// -// PERMISSION_DENIED: The account making the request does not own -// this customer. -// -// INVALID_ARGUMENT: Required request parameters are missing or invalid. -// -// FAILED_PRECONDITION: The customer has existing entitlements. -// -// NOT_FOUND: No Customer resource found for the name in the request. -func (c *CloudChannelClient) DeleteCustomer(ctx context.Context, req *channelpb.DeleteCustomerRequest, opts ...gax.CallOption) error { - return c.internalClient.DeleteCustomer(ctx, req, opts...) +func (c *cloudChannelGRPCClient) CreateChannelPartnerRepricingConfig(ctx context.Context, req *channelpb.CreateChannelPartnerRepricingConfigRequest, opts ...gax.CallOption) (*channelpb.ChannelPartnerRepricingConfig, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).CreateChannelPartnerRepricingConfig[0:len((*c.CallOptions).CreateChannelPartnerRepricingConfig):len((*c.CallOptions).CreateChannelPartnerRepricingConfig)], opts...) + var resp *channelpb.ChannelPartnerRepricingConfig + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.cloudChannelClient.CreateChannelPartnerRepricingConfig(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return resp, nil } -// ImportCustomer imports a Customer from the Cloud Identity associated with the provided -// Cloud Identity ID or domain before a TransferEntitlements call. If a -// linked Customer already exists and overwrite_if_exists is true, it will -// update that Customer’s data. -// -// Possible error codes: -// -// PERMISSION_DENIED: The reseller account making the request is different -// from the reseller account in the API request. -// -// NOT_FOUND: Cloud Identity doesn’t exist or was deleted. -// -// INVALID_ARGUMENT: Required parameters are missing, or the auth_token is -// expired or invalid. -// -// ALREADY_EXISTS: A customer already exists and has conflicting critical -// fields. Requires an overwrite. -// -// Return value: -// The Customer. -func (c *CloudChannelClient) ImportCustomer(ctx context.Context, req *channelpb.ImportCustomerRequest, opts ...gax.CallOption) (*channelpb.Customer, error) { - return c.internalClient.ImportCustomer(ctx, req, opts...) +func (c *cloudChannelGRPCClient) UpdateChannelPartnerRepricingConfig(ctx context.Context, req *channelpb.UpdateChannelPartnerRepricingConfigRequest, opts ...gax.CallOption) (*channelpb.ChannelPartnerRepricingConfig, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "channel_partner_repricing_config.name", url.QueryEscape(req.GetChannelPartnerRepricingConfig().GetName()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).UpdateChannelPartnerRepricingConfig[0:len((*c.CallOptions).UpdateChannelPartnerRepricingConfig):len((*c.CallOptions).UpdateChannelPartnerRepricingConfig)], opts...) + var resp *channelpb.ChannelPartnerRepricingConfig + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.cloudChannelClient.UpdateChannelPartnerRepricingConfig(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return resp, nil } -// ProvisionCloudIdentity creates a Cloud Identity for the given customer using the customer’s -// information, or the information provided here. -// -// Possible error codes: -// -// PERMISSION_DENIED: The customer doesn’t belong to the reseller. -// -// INVALID_ARGUMENT: Required request parameters are missing or invalid. -// -// NOT_FOUND: The customer was not found. -// -// ALREADY_EXISTS: The customer’s primary email already exists. Retry -// after changing the customer’s primary contact email. -// -// INTERNAL: Any non-user error related to a technical issue in the -// backend. Contact Cloud Channel support. -// -// UNKNOWN: Any non-user error related to a technical issue in the backend. -// Contact Cloud Channel support. -// -// Return value: -// The ID of a long-running operation. -// -// To get the results of the operation, call the GetOperation method of -// CloudChannelOperationsService. The Operation metadata contains an -// instance of OperationMetadata. -func (c *CloudChannelClient) ProvisionCloudIdentity(ctx context.Context, req *channelpb.ProvisionCloudIdentityRequest, opts ...gax.CallOption) (*ProvisionCloudIdentityOperation, error) { - return c.internalClient.ProvisionCloudIdentity(ctx, req, opts...) +func (c *cloudChannelGRPCClient) DeleteChannelPartnerRepricingConfig(ctx context.Context, req *channelpb.DeleteChannelPartnerRepricingConfigRequest, opts ...gax.CallOption) error { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).DeleteChannelPartnerRepricingConfig[0:len((*c.CallOptions).DeleteChannelPartnerRepricingConfig):len((*c.CallOptions).DeleteChannelPartnerRepricingConfig)], opts...) + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + _, err = c.cloudChannelClient.DeleteChannelPartnerRepricingConfig(ctx, req, settings.GRPC...) + return err + }, opts...) + return err } -// ProvisionCloudIdentityOperation returns a new ProvisionCloudIdentityOperation from a given name. -// The name must be that of a previously created ProvisionCloudIdentityOperation, possibly from a different process. -func (c *CloudChannelClient) ProvisionCloudIdentityOperation(name string) *ProvisionCloudIdentityOperation { - return c.internalClient.ProvisionCloudIdentityOperation(name) +func (c *cloudChannelGRPCClient) LookupOffer(ctx context.Context, req *channelpb.LookupOfferRequest, opts ...gax.CallOption) (*channelpb.Offer, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "entitlement", url.QueryEscape(req.GetEntitlement()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).LookupOffer[0:len((*c.CallOptions).LookupOffer):len((*c.CallOptions).LookupOffer)], opts...) + var resp *channelpb.Offer + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.cloudChannelClient.LookupOffer(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return resp, nil } -// ListEntitlements lists Entitlements belonging to a customer. -// -// Possible error codes: -// -// PERMISSION_DENIED: The customer doesn’t belong to the reseller. -// -// INVALID_ARGUMENT: Required request parameters are missing or invalid. -// -// Return value: -// A list of the customer’s Entitlements. -func (c *CloudChannelClient) ListEntitlements(ctx context.Context, req *channelpb.ListEntitlementsRequest, opts ...gax.CallOption) *EntitlementIterator { - return c.internalClient.ListEntitlements(ctx, req, opts...) +func (c *cloudChannelGRPCClient) ListProducts(ctx context.Context, req *channelpb.ListProductsRequest, opts ...gax.CallOption) *ProductIterator { + ctx = insertMetadata(ctx, c.xGoogMetadata) + opts = append((*c.CallOptions).ListProducts[0:len((*c.CallOptions).ListProducts):len((*c.CallOptions).ListProducts)], opts...) + it := &ProductIterator{} + req = proto.Clone(req).(*channelpb.ListProductsRequest) + it.InternalFetch = func(pageSize int, pageToken string) ([]*channelpb.Product, string, error) { + resp := &channelpb.ListProductsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.cloudChannelClient.ListProducts(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, "", err + } + + it.Response = resp + return resp.GetProducts(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it } -// ListTransferableSkus list TransferableSkus of a customer based on the Cloud Identity ID or -// Customer Name in the request. -// -// Use this method to list the entitlements information of an -// unowned customer. You should provide the customer’s -// Cloud Identity ID or Customer Name. -// -// Possible error codes: -// -// PERMISSION_DENIED: -// -// The customer doesn’t belong to the reseller and has no auth token. -// -// The supplied auth token is invalid. -// -// The reseller account making the request is different -// from the reseller account in the query. -// -// INVALID_ARGUMENT: Required request parameters are missing or invalid. -// -// Return value: -// A list of the customer’s TransferableSku. -func (c *CloudChannelClient) ListTransferableSkus(ctx context.Context, req *channelpb.ListTransferableSkusRequest, opts ...gax.CallOption) *TransferableSkuIterator { - return c.internalClient.ListTransferableSkus(ctx, req, opts...) +func (c *cloudChannelGRPCClient) ListSkus(ctx context.Context, req *channelpb.ListSkusRequest, opts ...gax.CallOption) *SkuIterator { + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).ListSkus[0:len((*c.CallOptions).ListSkus):len((*c.CallOptions).ListSkus)], opts...) + it := &SkuIterator{} + req = proto.Clone(req).(*channelpb.ListSkusRequest) + it.InternalFetch = func(pageSize int, pageToken string) ([]*channelpb.Sku, string, error) { + resp := &channelpb.ListSkusResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.cloudChannelClient.ListSkus(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, "", err + } + + it.Response = resp + return resp.GetSkus(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it } -// ListTransferableOffers list TransferableOffers of a customer based on Cloud Identity ID or -// Customer Name in the request. -// -// Use this method when a reseller gets the entitlement information of an -// unowned customer. The reseller should provide the customer’s -// Cloud Identity ID or Customer Name. -// -// Possible error codes: -// -// PERMISSION_DENIED: -// -// The customer doesn’t belong to the reseller and has no auth token. -// -// The customer provided incorrect reseller information when generating -// auth token. -// -// The reseller account making the request is different -// from the reseller account in the query. -// -// INVALID_ARGUMENT: Required request parameters are missing or invalid. -// -// Return value: -// List of TransferableOffer for the given customer and SKU. -func (c *CloudChannelClient) ListTransferableOffers(ctx context.Context, req *channelpb.ListTransferableOffersRequest, opts ...gax.CallOption) *TransferableOfferIterator { - return c.internalClient.ListTransferableOffers(ctx, req, opts...) -} +func (c *cloudChannelGRPCClient) ListOffers(ctx context.Context, req *channelpb.ListOffersRequest, opts ...gax.CallOption) *OfferIterator { + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) -// GetEntitlement returns the requested Entitlement resource. -// -// Possible error codes: -// -// PERMISSION_DENIED: The customer doesn’t belong to the reseller. -// -// INVALID_ARGUMENT: Required request parameters are missing or invalid. -// -// NOT_FOUND: The customer entitlement was not found. -// -// Return value: -// The requested Entitlement resource. -func (c *CloudChannelClient) GetEntitlement(ctx context.Context, req *channelpb.GetEntitlementRequest, opts ...gax.CallOption) (*channelpb.Entitlement, error) { - return c.internalClient.GetEntitlement(ctx, req, opts...) -} + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).ListOffers[0:len((*c.CallOptions).ListOffers):len((*c.CallOptions).ListOffers)], opts...) + it := &OfferIterator{} + req = proto.Clone(req).(*channelpb.ListOffersRequest) + it.InternalFetch = func(pageSize int, pageToken string) ([]*channelpb.Offer, string, error) { + resp := &channelpb.ListOffersResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.cloudChannelClient.ListOffers(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, "", err + } -// CreateEntitlement creates an entitlement for a customer. -// -// Possible error codes: -// -// PERMISSION_DENIED: The customer doesn’t belong to the reseller. -// -// INVALID_ARGUMENT: -// -// Required request parameters are missing or invalid. -// -// There is already a customer entitlement for a SKU from the same -// product family. -// -// INVALID_VALUE: Make sure the OfferId is valid. If it is, contact -// Google Channel support for further troubleshooting. -// -// NOT_FOUND: The customer or offer resource was not found. -// -// ALREADY_EXISTS: -// -// The SKU was already purchased for the customer. -// -// The customer’s primary email already exists. Retry -// after changing the customer’s primary contact email. -// -// CONDITION_NOT_MET or FAILED_PRECONDITION: -// -// The domain required for purchasing a SKU has not been verified. -// -// A pre-requisite SKU required to purchase an Add-On SKU is missing. -// For example, Google Workspace Business Starter is required to purchase -// Vault or Drive. -// -// (Developer accounts only) Reseller and resold domain must meet the -// following naming requirements: -// -// Domain names must start with goog-test. -// -// Domain names must include the reseller domain. -// -// INTERNAL: Any non-user error related to a technical issue in the -// backend. Contact Cloud Channel support. -// -// UNKNOWN: Any non-user error related to a technical issue in the backend. -// Contact Cloud Channel support. -// -// Return value: -// The ID of a long-running operation. -// -// To get the results of the operation, call the GetOperation method of -// CloudChannelOperationsService. The Operation metadata will contain an -// instance of OperationMetadata. -func (c *CloudChannelClient) CreateEntitlement(ctx context.Context, req *channelpb.CreateEntitlementRequest, opts ...gax.CallOption) (*CreateEntitlementOperation, error) { - return c.internalClient.CreateEntitlement(ctx, req, opts...) -} + it.Response = resp + return resp.GetOffers(), resp.GetNextPageToken(), 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 + } -// CreateEntitlementOperation returns a new CreateEntitlementOperation from a given name. -// The name must be that of a previously created CreateEntitlementOperation, possibly from a different process. -func (c *CloudChannelClient) CreateEntitlementOperation(name string) *CreateEntitlementOperation { - return c.internalClient.CreateEntitlementOperation(name) -} + it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() -// ChangeParameters change parameters of the entitlement. -// -// An entitlement update is a long-running operation and it updates the -// entitlement as a result of fulfillment. -// -// Possible error codes: -// -// PERMISSION_DENIED: The customer doesn’t belong to the reseller. -// -// INVALID_ARGUMENT: Required request parameters are missing or invalid. -// For example, the number of seats being changed is greater than the allowed -// number of max seats, or decreasing seats for a commitment based plan. -// -// NOT_FOUND: Entitlement resource not found. -// -// INTERNAL: Any non-user error related to a technical issue in the -// backend. Contact Cloud Channel support. -// -// UNKNOWN: Any non-user error related to a technical issue in the backend. -// Contact Cloud Channel support. -// -// Return value: -// The ID of a long-running operation. -// -// To get the results of the operation, call the GetOperation method of -// CloudChannelOperationsService. The Operation metadata will contain an -// instance of OperationMetadata. -func (c *CloudChannelClient) ChangeParameters(ctx context.Context, req *channelpb.ChangeParametersRequest, opts ...gax.CallOption) (*ChangeParametersOperation, error) { - return c.internalClient.ChangeParameters(ctx, req, opts...) + return it } -// ChangeParametersOperation returns a new ChangeParametersOperation from a given name. -// The name must be that of a previously created ChangeParametersOperation, possibly from a different process. -func (c *CloudChannelClient) ChangeParametersOperation(name string) *ChangeParametersOperation { - return c.internalClient.ChangeParametersOperation(name) -} +func (c *cloudChannelGRPCClient) ListPurchasableSkus(ctx context.Context, req *channelpb.ListPurchasableSkusRequest, opts ...gax.CallOption) *PurchasableSkuIterator { + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "customer", url.QueryEscape(req.GetCustomer()))) -// ChangeRenewalSettings updates the renewal settings for an existing customer entitlement. -// -// An entitlement update is a long-running operation and it updates the -// entitlement as a result of fulfillment. -// -// Possible error codes: -// -// PERMISSION_DENIED: The customer doesn’t belong to the reseller. -// -// INVALID_ARGUMENT: Required request parameters are missing or invalid. -// -// NOT_FOUND: Entitlement resource not found. -// -// NOT_COMMITMENT_PLAN: Renewal Settings are only applicable for a -// commitment plan. Can’t enable or disable renewals for non-commitment plans. -// -// INTERNAL: Any non-user error related to a technical issue in the -// backend. Contact Cloud Channel support. -// -// UNKNOWN: Any non-user error related to a technical issue in the backend. -// Contact Cloud Channel support. -// -// Return value: -// The ID of a long-running operation. -// -// To get the results of the operation, call the GetOperation method of -// CloudChannelOperationsService. The Operation metadata will contain an -// instance of OperationMetadata. -func (c *CloudChannelClient) ChangeRenewalSettings(ctx context.Context, req *channelpb.ChangeRenewalSettingsRequest, opts ...gax.CallOption) (*ChangeRenewalSettingsOperation, error) { - return c.internalClient.ChangeRenewalSettings(ctx, req, opts...) -} + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).ListPurchasableSkus[0:len((*c.CallOptions).ListPurchasableSkus):len((*c.CallOptions).ListPurchasableSkus)], opts...) + it := &PurchasableSkuIterator{} + req = proto.Clone(req).(*channelpb.ListPurchasableSkusRequest) + it.InternalFetch = func(pageSize int, pageToken string) ([]*channelpb.PurchasableSku, string, error) { + resp := &channelpb.ListPurchasableSkusResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.cloudChannelClient.ListPurchasableSkus(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, "", err + } -// ChangeRenewalSettingsOperation returns a new ChangeRenewalSettingsOperation from a given name. -// The name must be that of a previously created ChangeRenewalSettingsOperation, possibly from a different process. -func (c *CloudChannelClient) ChangeRenewalSettingsOperation(name string) *ChangeRenewalSettingsOperation { - return c.internalClient.ChangeRenewalSettingsOperation(name) -} + it.Response = resp + return resp.GetPurchasableSkus(), resp.GetNextPageToken(), 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 + } -// ChangeOffer updates the Offer for an existing customer entitlement. -// -// An entitlement update is a long-running operation and it updates the -// entitlement as a result of fulfillment. -// -// Possible error codes: -// -// PERMISSION_DENIED: The customer doesn’t belong to the reseller. -// -// INVALID_ARGUMENT: Required request parameters are missing or invalid. -// -// NOT_FOUND: Offer or Entitlement resource not found. -// -// INTERNAL: Any non-user error related to a technical issue in the -// backend. Contact Cloud Channel support. -// -// UNKNOWN: Any non-user error related to a technical issue in the backend. -// Contact Cloud Channel support. -// -// Return value: -// The ID of a long-running operation. -// -// To get the results of the operation, call the GetOperation method of -// CloudChannelOperationsService. The Operation metadata will contain an -// instance of OperationMetadata. -func (c *CloudChannelClient) ChangeOffer(ctx context.Context, req *channelpb.ChangeOfferRequest, opts ...gax.CallOption) (*ChangeOfferOperation, error) { - return c.internalClient.ChangeOffer(ctx, req, opts...) -} + it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() -// ChangeOfferOperation returns a new ChangeOfferOperation from a given name. -// The name must be that of a previously created ChangeOfferOperation, possibly from a different process. -func (c *CloudChannelClient) ChangeOfferOperation(name string) *ChangeOfferOperation { - return c.internalClient.ChangeOfferOperation(name) + return it } -// StartPaidService starts paid service for a trial entitlement. -// -// Starts paid service for a trial entitlement immediately. This method is -// only applicable if a plan is set up for a trial entitlement but has some -// trial days remaining. -// -// Possible error codes: -// -// PERMISSION_DENIED: The customer doesn’t belong to the reseller. -// -// INVALID_ARGUMENT: Required request parameters are missing or invalid. -// -// NOT_FOUND: Entitlement resource not found. -// -// FAILED_PRECONDITION/NOT_IN_TRIAL: This method only works for -// entitlement on trial plans. -// -// INTERNAL: Any non-user error related to a technical issue in the -// backend. Contact Cloud Channel support. -// -// UNKNOWN: Any non-user error related to a technical issue in the backend. -// Contact Cloud Channel support. -// -// Return value: -// The ID of a long-running operation. -// -// To get the results of the operation, call the GetOperation method of -// CloudChannelOperationsService. The Operation metadata will contain an -// instance of OperationMetadata. -func (c *CloudChannelClient) StartPaidService(ctx context.Context, req *channelpb.StartPaidServiceRequest, opts ...gax.CallOption) (*StartPaidServiceOperation, error) { - return c.internalClient.StartPaidService(ctx, req, opts...) -} +func (c *cloudChannelGRPCClient) ListPurchasableOffers(ctx context.Context, req *channelpb.ListPurchasableOffersRequest, opts ...gax.CallOption) *PurchasableOfferIterator { + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "customer", url.QueryEscape(req.GetCustomer()))) -// StartPaidServiceOperation returns a new StartPaidServiceOperation from a given name. -// The name must be that of a previously created StartPaidServiceOperation, possibly from a different process. -func (c *CloudChannelClient) StartPaidServiceOperation(name string) *StartPaidServiceOperation { - return c.internalClient.StartPaidServiceOperation(name) -} + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).ListPurchasableOffers[0:len((*c.CallOptions).ListPurchasableOffers):len((*c.CallOptions).ListPurchasableOffers)], opts...) + it := &PurchasableOfferIterator{} + req = proto.Clone(req).(*channelpb.ListPurchasableOffersRequest) + it.InternalFetch = func(pageSize int, pageToken string) ([]*channelpb.PurchasableOffer, string, error) { + resp := &channelpb.ListPurchasableOffersResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.cloudChannelClient.ListPurchasableOffers(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, "", err + } -// SuspendEntitlement suspends a previously fulfilled entitlement. -// -// An entitlement suspension is a long-running operation. -// -// Possible error codes: -// -// PERMISSION_DENIED: The customer doesn’t belong to the reseller. -// -// INVALID_ARGUMENT: Required request parameters are missing or invalid. -// -// NOT_FOUND: Entitlement resource not found. -// -// NOT_ACTIVE: Entitlement is not active. -// -// INTERNAL: Any non-user error related to a technical issue in the -// backend. Contact Cloud Channel support. -// -// UNKNOWN: Any non-user error related to a technical issue in the backend. -// Contact Cloud Channel support. -// -// Return value: -// The ID of a long-running operation. -// -// To get the results of the operation, call the GetOperation method of -// CloudChannelOperationsService. The Operation metadata will contain an -// instance of OperationMetadata. -func (c *CloudChannelClient) SuspendEntitlement(ctx context.Context, req *channelpb.SuspendEntitlementRequest, opts ...gax.CallOption) (*SuspendEntitlementOperation, error) { - return c.internalClient.SuspendEntitlement(ctx, req, opts...) + it.Response = resp + return resp.GetPurchasableOffers(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it } -// SuspendEntitlementOperation returns a new SuspendEntitlementOperation from a given name. -// The name must be that of a previously created SuspendEntitlementOperation, possibly from a different process. -func (c *CloudChannelClient) SuspendEntitlementOperation(name string) *SuspendEntitlementOperation { - return c.internalClient.SuspendEntitlementOperation(name) +func (c *cloudChannelGRPCClient) RegisterSubscriber(ctx context.Context, req *channelpb.RegisterSubscriberRequest, opts ...gax.CallOption) (*channelpb.RegisterSubscriberResponse, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "account", url.QueryEscape(req.GetAccount()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).RegisterSubscriber[0:len((*c.CallOptions).RegisterSubscriber):len((*c.CallOptions).RegisterSubscriber)], opts...) + var resp *channelpb.RegisterSubscriberResponse + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.cloudChannelClient.RegisterSubscriber(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return resp, nil } -// CancelEntitlement cancels a previously fulfilled entitlement. -// -// An entitlement cancellation is a long-running operation. -// -// Possible error codes: -// -// PERMISSION_DENIED: The reseller account making the request is different -// from the reseller account in the API request. -// -// FAILED_PRECONDITION: There are Google Cloud projects linked to the -// Google Cloud entitlement’s Cloud Billing subaccount. -// -// INVALID_ARGUMENT: Required request parameters are missing or invalid. -// -// NOT_FOUND: Entitlement resource not found. -// -// DELETION_TYPE_NOT_ALLOWED: Cancel is only allowed for Google Workspace -// add-ons, or entitlements for Google Cloud’s development platform. -// -// INTERNAL: Any non-user error related to a technical issue in the -// backend. Contact Cloud Channel support. -// -// UNKNOWN: Any non-user error related to a technical issue in the backend. -// Contact Cloud Channel support. -// -// Return value: -// The ID of a long-running operation. -// -// To get the results of the operation, call the GetOperation method of -// CloudChannelOperationsService. The response will contain -// google.protobuf.Empty on success. The Operation metadata will contain an -// instance of OperationMetadata. -func (c *CloudChannelClient) CancelEntitlement(ctx context.Context, req *channelpb.CancelEntitlementRequest, opts ...gax.CallOption) (*CancelEntitlementOperation, error) { - return c.internalClient.CancelEntitlement(ctx, req, opts...) +func (c *cloudChannelGRPCClient) UnregisterSubscriber(ctx context.Context, req *channelpb.UnregisterSubscriberRequest, opts ...gax.CallOption) (*channelpb.UnregisterSubscriberResponse, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "account", url.QueryEscape(req.GetAccount()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).UnregisterSubscriber[0:len((*c.CallOptions).UnregisterSubscriber):len((*c.CallOptions).UnregisterSubscriber)], opts...) + var resp *channelpb.UnregisterSubscriberResponse + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.cloudChannelClient.UnregisterSubscriber(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return resp, nil } -// CancelEntitlementOperation returns a new CancelEntitlementOperation from a given name. -// The name must be that of a previously created CancelEntitlementOperation, possibly from a different process. -func (c *CloudChannelClient) CancelEntitlementOperation(name string) *CancelEntitlementOperation { - return c.internalClient.CancelEntitlementOperation(name) +func (c *cloudChannelGRPCClient) ListSubscribers(ctx context.Context, req *channelpb.ListSubscribersRequest, opts ...gax.CallOption) *StringIterator { + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "account", url.QueryEscape(req.GetAccount()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).ListSubscribers[0:len((*c.CallOptions).ListSubscribers):len((*c.CallOptions).ListSubscribers)], opts...) + it := &StringIterator{} + req = proto.Clone(req).(*channelpb.ListSubscribersRequest) + it.InternalFetch = func(pageSize int, pageToken string) ([]string, string, error) { + resp := &channelpb.ListSubscribersResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.cloudChannelClient.ListSubscribers(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, "", err + } + + it.Response = resp + return resp.GetServiceAccounts(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it } -// ActivateEntitlement activates a previously suspended entitlement. Entitlements suspended for -// pending ToS acceptance can’t be activated using this method. -// -// An entitlement activation is a long-running operation and it updates -// the state of the customer entitlement. -// -// Possible error codes: -// -// PERMISSION_DENIED: The reseller account making the request is different -// from the reseller account in the API request. -// -// INVALID_ARGUMENT: Required request parameters are missing or invalid. -// -// NOT_FOUND: Entitlement resource not found. -// -// SUSPENSION_NOT_RESELLER_INITIATED: Can only activate reseller-initiated -// suspensions and entitlements that have accepted the TOS. -// -// NOT_SUSPENDED: Can only activate suspended entitlements not in an ACTIVE -// state. -// -// INTERNAL: Any non-user error related to a technical issue in the -// backend. Contact Cloud Channel support. -// -// UNKNOWN: Any non-user error related to a technical issue in the backend. -// Contact Cloud Channel support. -// -// Return value: -// The ID of a long-running operation. -// -// To get the results of the operation, call the GetOperation method of -// CloudChannelOperationsService. The Operation metadata will contain an -// instance of OperationMetadata. -func (c *CloudChannelClient) ActivateEntitlement(ctx context.Context, req *channelpb.ActivateEntitlementRequest, opts ...gax.CallOption) (*ActivateEntitlementOperation, error) { - return c.internalClient.ActivateEntitlement(ctx, req, opts...) +func (c *cloudChannelGRPCClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + 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 } -// ActivateEntitlementOperation returns a new ActivateEntitlementOperation from a given name. -// The name must be that of a previously created ActivateEntitlementOperation, possibly from a different process. -func (c *CloudChannelClient) ActivateEntitlementOperation(name string) *ActivateEntitlementOperation { - return c.internalClient.ActivateEntitlementOperation(name) +func (c *cloudChannelGRPCClient) DeleteOperation(ctx context.Context, req *longrunningpb.DeleteOperationRequest, opts ...gax.CallOption) error { + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + 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 } -// TransferEntitlements transfers customer entitlements to new reseller. -// -// Possible error codes: -// -// PERMISSION_DENIED: The customer doesn’t belong to the reseller. -// -// INVALID_ARGUMENT: Required request parameters are missing or invalid. -// -// NOT_FOUND: The customer or offer resource was not found. -// -// ALREADY_EXISTS: The SKU was already transferred for the customer. -// -// CONDITION_NOT_MET or FAILED_PRECONDITION: -// -// The SKU requires domain verification to transfer, but the domain is -// not verified. -// -// An Add-On SKU (example, Vault or Drive) is missing the -// pre-requisite SKU (example, G Suite Basic). -// -// (Developer accounts only) Reseller and resold domain must meet the -// following naming requirements: -// -// Domain names must start with goog-test. -// -// Domain names must include the reseller domain. -// -// Specify all transferring entitlements. -// -// INTERNAL: Any non-user error related to a technical issue in the -// backend. Contact Cloud Channel support. -// -// UNKNOWN: Any non-user error related to a technical issue in the backend. -// Contact Cloud Channel support. -// -// Return value: -// The ID of a long-running operation. -// -// To get the results of the operation, call the GetOperation method of -// CloudChannelOperationsService. The Operation metadata will contain an -// instance of OperationMetadata. -func (c *CloudChannelClient) TransferEntitlements(ctx context.Context, req *channelpb.TransferEntitlementsRequest, opts ...gax.CallOption) (*TransferEntitlementsOperation, error) { - return c.internalClient.TransferEntitlements(ctx, req, opts...) +func (c *cloudChannelGRPCClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + 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 } -// TransferEntitlementsOperation returns a new TransferEntitlementsOperation from a given name. -// The name must be that of a previously created TransferEntitlementsOperation, possibly from a different process. -func (c *CloudChannelClient) TransferEntitlementsOperation(name string) *TransferEntitlementsOperation { - return c.internalClient.TransferEntitlementsOperation(name) +func (c *cloudChannelGRPCClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).ListOperations[0:len((*c.CallOptions).ListOperations):len((*c.CallOptions).ListOperations)], opts...) + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + 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 + } + + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it } -// TransferEntitlementsToGoogle transfers customer entitlements from their current reseller to Google. +// ListCustomers list Customers. // // Possible error codes: // -// PERMISSION_DENIED: The customer doesn’t belong to the reseller. +// PERMISSION_DENIED: The reseller account making the request is different +// from the reseller account in the API request. // // INVALID_ARGUMENT: Required request parameters are missing or invalid. // -// NOT_FOUND: The customer or offer resource was not found. -// -// ALREADY_EXISTS: The SKU was already transferred for the customer. -// -// CONDITION_NOT_MET or FAILED_PRECONDITION: -// -// The SKU requires domain verification to transfer, but the domain is -// not verified. -// -// An Add-On SKU (example, Vault or Drive) is missing the -// pre-requisite SKU (example, G Suite Basic). -// -// (Developer accounts only) Reseller and resold domain must meet the -// following naming requirements: -// -// Domain names must start with goog-test. -// -// Domain names must include the reseller domain. -// -// INTERNAL: Any non-user error related to a technical issue in the -// backend. Contact Cloud Channel support. -// -// UNKNOWN: Any non-user error related to a technical issue in the backend. -// Contact Cloud Channel support. -// // Return value: -// The ID of a long-running operation. -// -// To get the results of the operation, call the GetOperation method of -// CloudChannelOperationsService. The response will contain -// google.protobuf.Empty on success. The Operation metadata will contain an -// instance of OperationMetadata. -func (c *CloudChannelClient) TransferEntitlementsToGoogle(ctx context.Context, req *channelpb.TransferEntitlementsToGoogleRequest, opts ...gax.CallOption) (*TransferEntitlementsToGoogleOperation, error) { - return c.internalClient.TransferEntitlementsToGoogle(ctx, req, opts...) -} +// List of Customers, or an empty list if there are no customers. +func (c *cloudChannelRESTClient) ListCustomers(ctx context.Context, req *channelpb.ListCustomersRequest, opts ...gax.CallOption) *CustomerIterator { + it := &CustomerIterator{} + req = proto.Clone(req).(*channelpb.ListCustomersRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*channelpb.Customer, string, error) { + resp := &channelpb.ListCustomersResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/customers", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetCustomers(), resp.GetNextPageToken(), nil + } -// TransferEntitlementsToGoogleOperation returns a new TransferEntitlementsToGoogleOperation from a given name. -// The name must be that of a previously created TransferEntitlementsToGoogleOperation, possibly from a different process. -func (c *CloudChannelClient) TransferEntitlementsToGoogleOperation(name string) *TransferEntitlementsToGoogleOperation { - return c.internalClient.TransferEntitlementsToGoogleOperation(name) + 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it } -// ListChannelPartnerLinks list ChannelPartnerLinks belonging to a distributor. -// You must be a distributor to call this method. +// GetCustomer returns the requested Customer resource. // // Possible error codes: // @@ -1323,14 +3977,70 @@ func (c *CloudChannelClient) TransferEntitlementsToGoogleOperation(name string) // // INVALID_ARGUMENT: Required request parameters are missing or invalid. // +// NOT_FOUND: The customer resource doesn’t exist. Usually the result of an +// invalid name parameter. +// // Return value: -// The list of the distributor account’s ChannelPartnerLink resources. -func (c *CloudChannelClient) ListChannelPartnerLinks(ctx context.Context, req *channelpb.ListChannelPartnerLinksRequest, opts ...gax.CallOption) *ChannelPartnerLinkIterator { - return c.internalClient.ListChannelPartnerLinks(ctx, req, opts...) +// The Customer resource. +func (c *cloudChannelRESTClient) GetCustomer(ctx context.Context, req *channelpb.GetCustomerRequest, opts ...gax.CallOption) (*channelpb.Customer, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetCustomer[0:len((*c.CallOptions).GetCustomer):len((*c.CallOptions).GetCustomer)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &channelpb.Customer{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil } -// GetChannelPartnerLink returns the requested ChannelPartnerLink resource. -// You must be a distributor to call this method. +// CheckCloudIdentityAccountsExist confirms the existence of Cloud Identity accounts based on the domain and +// if the Cloud Identity accounts are owned by the reseller. // // Possible error codes: // @@ -1339,469 +4049,987 @@ func (c *CloudChannelClient) ListChannelPartnerLinks(ctx context.Context, req *c // // INVALID_ARGUMENT: Required request parameters are missing or invalid. // -// NOT_FOUND: ChannelPartnerLink resource not found because of an -// invalid channel partner link name. +// INVALID_VALUE: Invalid domain value in the request. // // Return value: -// The ChannelPartnerLink resource. -func (c *CloudChannelClient) GetChannelPartnerLink(ctx context.Context, req *channelpb.GetChannelPartnerLinkRequest, opts ...gax.CallOption) (*channelpb.ChannelPartnerLink, error) { - return c.internalClient.GetChannelPartnerLink(ctx, req, opts...) +// A list of CloudIdentityCustomerAccount resources for the domain (may be +// empty) +// +// Note: in the v1alpha1 version of the API, a NOT_FOUND error returns if +// no CloudIdentityCustomerAccount resources match the domain. +func (c *cloudChannelRESTClient) CheckCloudIdentityAccountsExist(ctx context.Context, req *channelpb.CheckCloudIdentityAccountsExistRequest, opts ...gax.CallOption) (*channelpb.CheckCloudIdentityAccountsExistResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:checkCloudIdentityAccountsExist", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CheckCloudIdentityAccountsExist[0:len((*c.CallOptions).CheckCloudIdentityAccountsExist):len((*c.CallOptions).CheckCloudIdentityAccountsExist)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &channelpb.CheckCloudIdentityAccountsExistResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil } -// CreateChannelPartnerLink initiates a channel partner link between a distributor and a reseller, or -// between resellers in an n-tier reseller channel. -// Invited partners need to follow the invite_link_uri provided in the -// response to accept. After accepting the invitation, a link is set up -// between the two parties. -// You must be a distributor to call this method. +// CreateCustomer creates a new Customer resource under the reseller or distributor +// account. // // Possible error codes: // // PERMISSION_DENIED: The reseller account making the request is different // from the reseller account in the API request. // -// INVALID_ARGUMENT: Required request parameters are missing or invalid. -// -// ALREADY_EXISTS: The ChannelPartnerLink sent in the request already -// exists. -// -// NOT_FOUND: No Cloud Identity customer exists for provided domain. +// INVALID_ARGUMENT: // -// INTERNAL: Any non-user error related to a technical issue in the -// backend. Contact Cloud Channel support. +// Required request parameters are missing or invalid. // -// UNKNOWN: Any non-user error related to a technical issue in the backend. -// Contact Cloud Channel support. +// Domain field value doesn’t match the primary email domain. // // Return value: -// The new ChannelPartnerLink resource. -func (c *CloudChannelClient) CreateChannelPartnerLink(ctx context.Context, req *channelpb.CreateChannelPartnerLinkRequest, opts ...gax.CallOption) (*channelpb.ChannelPartnerLink, error) { - return c.internalClient.CreateChannelPartnerLink(ctx, req, opts...) +// The newly created Customer resource. +func (c *cloudChannelRESTClient) CreateCustomer(ctx context.Context, req *channelpb.CreateCustomerRequest, opts ...gax.CallOption) (*channelpb.Customer, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetCustomer() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/customers", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateCustomer[0:len((*c.CallOptions).CreateCustomer):len((*c.CallOptions).CreateCustomer)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &channelpb.Customer{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil } -// UpdateChannelPartnerLink updates a channel partner link. Distributors call this method to change a -// link’s status. For example, to suspend a partner link. -// You must be a distributor to call this method. +// UpdateCustomer updates an existing Customer resource for the reseller or +// distributor. // // Possible error codes: // // PERMISSION_DENIED: The reseller account making the request is different // from the reseller account in the API request. // -// INVALID_ARGUMENT: -// -// Required request parameters are missing or invalid. -// -// Link state cannot change from invited to active or suspended. -// -// Cannot send reseller_cloud_identity_id, invite_url, or name in update -// mask. -// -// NOT_FOUND: ChannelPartnerLink resource not found. -// -// INTERNAL: Any non-user error related to a technical issue in the -// backend. Contact Cloud Channel support. +// INVALID_ARGUMENT: Required request parameters are missing or invalid. // -// UNKNOWN: Any non-user error related to a technical issue in the backend. -// Contact Cloud Channel support. +// NOT_FOUND: No Customer resource found for the name in the request. // // Return value: -// The updated ChannelPartnerLink resource. -func (c *CloudChannelClient) UpdateChannelPartnerLink(ctx context.Context, req *channelpb.UpdateChannelPartnerLinkRequest, opts ...gax.CallOption) (*channelpb.ChannelPartnerLink, error) { - return c.internalClient.UpdateChannelPartnerLink(ctx, req, opts...) -} +// The updated Customer resource. +func (c *cloudChannelRESTClient) UpdateCustomer(ctx context.Context, req *channelpb.UpdateCustomerRequest, opts ...gax.CallOption) (*channelpb.Customer, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetCustomer() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } -// GetCustomerRepricingConfig gets information about how a Reseller modifies their bill before sending -// it to a Customer. -// -// Possible Error Codes: -// -// PERMISSION_DENIED: If the account making the request and the account -// being queried are different. -// -// NOT_FOUND: The CustomerRepricingConfig was not found. -// -// INTERNAL: Any non-user error related to technical issues in the -// backend. In this case, contact Cloud Channel support. -// -// Return Value: -// If successful, the CustomerRepricingConfig resource, otherwise returns -// an error. -func (c *CloudChannelClient) GetCustomerRepricingConfig(ctx context.Context, req *channelpb.GetCustomerRepricingConfigRequest, opts ...gax.CallOption) (*channelpb.CustomerRepricingConfig, error) { - return c.internalClient.GetCustomerRepricingConfig(ctx, req, opts...) -} + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetCustomer().GetName()) -// ListCustomerRepricingConfigs lists information about how a Reseller modifies their bill before sending -// it to a Customer. -// -// Possible Error Codes: -// -// PERMISSION_DENIED: If the account making the request and the account -// being queried are different. -// -// NOT_FOUND: The CustomerRepricingConfig specified does not exist or is -// not associated with the given account. -// -// INTERNAL: Any non-user error related to technical issues in the -// backend. In this case, contact Cloud Channel support. -// -// Return Value: -// If successful, the CustomerRepricingConfig resources. The -// data for each resource is displayed in the ascending order of: -// -// customer ID -// -// RepricingConfig.EntitlementGranularity.entitlement -// -// RepricingConfig.effective_invoice_month -// -// CustomerRepricingConfig.update_time -// -// If unsuccessful, returns an error. -func (c *CloudChannelClient) ListCustomerRepricingConfigs(ctx context.Context, req *channelpb.ListCustomerRepricingConfigsRequest, opts ...gax.CallOption) *CustomerRepricingConfigIterator { - return c.internalClient.ListCustomerRepricingConfigs(ctx, req, opts...) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "customer.name", url.QueryEscape(req.GetCustomer().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateCustomer[0:len((*c.CallOptions).UpdateCustomer):len((*c.CallOptions).UpdateCustomer)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &channelpb.Customer{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil } -// CreateCustomerRepricingConfig creates a CustomerRepricingConfig. Call this method to set modifications -// for a specific customer’s bill. You can only create configs if the -// RepricingConfig.effective_invoice_month is a -// future month. If needed, you can create a config for the current month, -// with some restrictions. -// -// When creating a config for a future month, make sure there are no existing -// configs for that -// RepricingConfig.effective_invoice_month. +// DeleteCustomer deletes the given Customer permanently. // -// The following restrictions are for creating configs in the current month. +// Possible error codes: // -// This functionality is reserved for recovering from an erroneous config, -// and should not be used for regular business cases. +// PERMISSION_DENIED: The account making the request does not own +// this customer. // -// The new config will not modify exports used with other configs. -// Changes to the config may be immediate, but may take up to 24 hours. +// INVALID_ARGUMENT: Required request parameters are missing or invalid. // -// There is a limit of ten configs for any -// RepricingConfig.EntitlementGranularity.entitlement -// or RepricingConfig.effective_invoice_month. +// FAILED_PRECONDITION: The customer has existing entitlements. // -// The contained CustomerRepricingConfig.repricing_config vaule must be -// different from the value used in the current config for a -// RepricingConfig.EntitlementGranularity.entitlement. +// NOT_FOUND: No Customer resource found for the name in the request. +func (c *cloudChannelRESTClient) DeleteCustomer(ctx context.Context, req *channelpb.DeleteCustomerRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// ImportCustomer imports a Customer from the Cloud Identity associated with the provided +// Cloud Identity ID or domain before a TransferEntitlements call. If a +// linked Customer already exists and overwrite_if_exists is true, it will +// update that Customer’s data. // -// Possible Error Codes: +// Possible error codes: // -// PERMISSION_DENIED: If the account making the request and the account -// being queried are different. +// PERMISSION_DENIED: The reseller account making the request is different +// from the reseller account in the API request. // -// INVALID_ARGUMENT: Missing or invalid required parameters in the -// request. Also displays if the updated config is for the current month or -// past months. +// NOT_FOUND: Cloud Identity doesn’t exist or was deleted. // -// NOT_FOUND: The CustomerRepricingConfig specified does not exist or is -// not associated with the given account. +// INVALID_ARGUMENT: Required parameters are missing, or the auth_token is +// expired or invalid. // -// INTERNAL: Any non-user error related to technical issues in the -// backend. In this case, contact Cloud Channel support. +// ALREADY_EXISTS: A customer already exists and has conflicting critical +// fields. Requires an overwrite. // -// Return Value: -// If successful, the updated CustomerRepricingConfig resource, otherwise -// returns an error. -func (c *CloudChannelClient) CreateCustomerRepricingConfig(ctx context.Context, req *channelpb.CreateCustomerRepricingConfigRequest, opts ...gax.CallOption) (*channelpb.CustomerRepricingConfig, error) { - return c.internalClient.CreateCustomerRepricingConfig(ctx, req, opts...) +// Return value: +// The Customer. +func (c *cloudChannelRESTClient) ImportCustomer(ctx context.Context, req *channelpb.ImportCustomerRequest, opts ...gax.CallOption) (*channelpb.Customer, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/customers:import", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).ImportCustomer[0:len((*c.CallOptions).ImportCustomer):len((*c.CallOptions).ImportCustomer)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &channelpb.Customer{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil } -// UpdateCustomerRepricingConfig updates a CustomerRepricingConfig. Call this method to set modifications -// for a specific customer’s bill. This method overwrites the existing -// CustomerRepricingConfig. +// ProvisionCloudIdentity creates a Cloud Identity for the given customer using the customer’s +// information, or the information provided here. // -// You can only update configs if the -// RepricingConfig.effective_invoice_month is a -// future month. To make changes to configs for the current month, use -// CreateCustomerRepricingConfig, taking note of its restrictions. You -// cannot update the RepricingConfig.effective_invoice_month. +// Possible error codes: // -// When updating a config in the future: +// PERMISSION_DENIED: The customer doesn’t belong to the reseller. // -// This config must already exist. +// INVALID_ARGUMENT: Required request parameters are missing or invalid. // -// Possible Error Codes: +// NOT_FOUND: The customer was not found. // -// PERMISSION_DENIED: If the account making the request and the account -// being queried are different. +// ALREADY_EXISTS: The customer’s primary email already exists. Retry +// after changing the customer’s primary contact email. // -// INVALID_ARGUMENT: Missing or invalid required parameters in the -// request. Also displays if the updated config is for the current month or -// past months. +// INTERNAL: Any non-user error related to a technical issue in the +// backend. Contact Cloud Channel support. // -// NOT_FOUND: The CustomerRepricingConfig specified does not exist or is -// not associated with the given account. +// UNKNOWN: Any non-user error related to a technical issue in the backend. +// Contact Cloud Channel support. // -// INTERNAL: Any non-user error related to technical issues in the -// backend. In this case, contact Cloud Channel support. +// Return value: +// The ID of a long-running operation. // -// Return Value: -// If successful, the updated CustomerRepricingConfig resource, otherwise -// returns an error. -func (c *CloudChannelClient) UpdateCustomerRepricingConfig(ctx context.Context, req *channelpb.UpdateCustomerRepricingConfigRequest, opts ...gax.CallOption) (*channelpb.CustomerRepricingConfig, error) { - return c.internalClient.UpdateCustomerRepricingConfig(ctx, req, opts...) +// To get the results of the operation, call the GetOperation method of +// CloudChannelOperationsService. The Operation metadata contains an +// instance of OperationMetadata. +func (c *cloudChannelRESTClient) ProvisionCloudIdentity(ctx context.Context, req *channelpb.ProvisionCloudIdentityRequest, opts ...gax.CallOption) (*ProvisionCloudIdentityOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:provisionCloudIdentity", req.GetCustomer()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "customer", url.QueryEscape(req.GetCustomer()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &ProvisionCloudIdentityOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil } -// DeleteCustomerRepricingConfig deletes the given CustomerRepricingConfig permanently. You can only -// delete configs if their RepricingConfig.effective_invoice_month is set -// to a date after the current month. +// ListEntitlements lists Entitlements belonging to a customer. // // Possible error codes: // -// PERMISSION_DENIED: The account making the request does not own -// this customer. +// PERMISSION_DENIED: The customer doesn’t belong to the reseller. // // INVALID_ARGUMENT: Required request parameters are missing or invalid. // -// FAILED_PRECONDITION: The CustomerRepricingConfig is active or in the -// past. -// -// NOT_FOUND: No CustomerRepricingConfig found for the name in the -// request. -func (c *CloudChannelClient) DeleteCustomerRepricingConfig(ctx context.Context, req *channelpb.DeleteCustomerRepricingConfigRequest, opts ...gax.CallOption) error { - return c.internalClient.DeleteCustomerRepricingConfig(ctx, req, opts...) -} +// Return value: +// A list of the customer’s Entitlements. +func (c *cloudChannelRESTClient) ListEntitlements(ctx context.Context, req *channelpb.ListEntitlementsRequest, opts ...gax.CallOption) *EntitlementIterator { + it := &EntitlementIterator{} + req = proto.Clone(req).(*channelpb.ListEntitlementsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*channelpb.Entitlement, string, error) { + resp := &channelpb.ListEntitlementsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/entitlements", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetEntitlements(), resp.GetNextPageToken(), 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 + } -// GetChannelPartnerRepricingConfig gets information about how a Distributor modifies their bill before sending -// it to a ChannelPartner. -// -// Possible Error Codes: -// -// PERMISSION_DENIED: If the account making the request and the account -// being queried are different. -// -// NOT_FOUND: The ChannelPartnerRepricingConfig was not found. -// -// INTERNAL: Any non-user error related to technical issues in the -// backend. In this case, contact Cloud Channel support. -// -// Return Value: -// If successful, the ChannelPartnerRepricingConfig resource, otherwise -// returns an error. -func (c *CloudChannelClient) GetChannelPartnerRepricingConfig(ctx context.Context, req *channelpb.GetChannelPartnerRepricingConfigRequest, opts ...gax.CallOption) (*channelpb.ChannelPartnerRepricingConfig, error) { - return c.internalClient.GetChannelPartnerRepricingConfig(ctx, req, opts...) + it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it } -// ListChannelPartnerRepricingConfigs lists information about how a Reseller modifies their bill before sending -// it to a ChannelPartner. -// -// Possible Error Codes: +// ListTransferableSkus list TransferableSkus of a customer based on the Cloud Identity ID or +// Customer Name in the request. // -// PERMISSION_DENIED: If the account making the request and the account -// being queried are different. +// Use this method to list the entitlements information of an +// unowned customer. You should provide the customer’s +// Cloud Identity ID or Customer Name. // -// NOT_FOUND: The ChannelPartnerRepricingConfig specified does not exist -// or is not associated with the given account. +// Possible error codes: // -// INTERNAL: Any non-user error related to technical issues in the -// backend. In this case, contact Cloud Channel support. +// PERMISSION_DENIED: // -// Return Value: -// If successful, the ChannelPartnerRepricingConfig resources. -// The data for each resource is displayed in the ascending order of: +// The customer doesn’t belong to the reseller and has no auth token. // -// channel partner ID +// The supplied auth token is invalid. // -// RepricingConfig.effective_invoice_month +// The reseller account making the request is different +// from the reseller account in the query. // -// ChannelPartnerRepricingConfig.update_time +// INVALID_ARGUMENT: Required request parameters are missing or invalid. // -// If unsuccessful, returns an error. -func (c *CloudChannelClient) ListChannelPartnerRepricingConfigs(ctx context.Context, req *channelpb.ListChannelPartnerRepricingConfigsRequest, opts ...gax.CallOption) *ChannelPartnerRepricingConfigIterator { - return c.internalClient.ListChannelPartnerRepricingConfigs(ctx, req, opts...) +// Return value: +// A list of the customer’s TransferableSku. +func (c *cloudChannelRESTClient) ListTransferableSkus(ctx context.Context, req *channelpb.ListTransferableSkusRequest, opts ...gax.CallOption) *TransferableSkuIterator { + it := &TransferableSkuIterator{} + req = proto.Clone(req).(*channelpb.ListTransferableSkusRequest) + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*channelpb.TransferableSku, string, error) { + resp := &channelpb.ListTransferableSkusResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, "", err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:listTransferableSkus", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetTransferableSkus(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it } -// CreateChannelPartnerRepricingConfig creates a ChannelPartnerRepricingConfig. Call this method to set -// modifications for a specific ChannelPartner’s bill. You can only create -// configs if the RepricingConfig.effective_invoice_month is a future -// month. If needed, you can create a config for the current month, with some -// restrictions. -// -// When creating a config for a future month, make sure there are no existing -// configs for that -// RepricingConfig.effective_invoice_month. -// -// The following restrictions are for creating configs in the current month. -// -// This functionality is reserved for recovering from an erroneous config, -// and should not be used for regular business cases. -// -// The new config will not modify exports used with other configs. -// Changes to the config may be immediate, but may take up to 24 hours. +// ListTransferableOffers list TransferableOffers of a customer based on Cloud Identity ID or +// Customer Name in the request. // -// There is a limit of ten configs for any ChannelPartner or -// RepricingConfig.effective_invoice_month. +// Use this method when a reseller gets the entitlement information of an +// unowned customer. The reseller should provide the customer’s +// Cloud Identity ID or Customer Name. // -// The contained ChannelPartnerRepricingConfig.repricing_config vaule -// must be different from the value used in the current config for a -// ChannelPartner. +// Possible error codes: // -// Possible Error Codes: +// PERMISSION_DENIED: // -// PERMISSION_DENIED: If the account making the request and the account -// being queried are different. +// The customer doesn’t belong to the reseller and has no auth token. // -// INVALID_ARGUMENT: Missing or invalid required parameters in the -// request. Also displays if the updated config is for the current month or -// past months. +// The customer provided incorrect reseller information when generating +// auth token. // -// NOT_FOUND: The ChannelPartnerRepricingConfig specified does not exist -// or is not associated with the given account. +// The reseller account making the request is different +// from the reseller account in the query. // -// INTERNAL: Any non-user error related to technical issues in the -// backend. In this case, contact Cloud Channel support. +// INVALID_ARGUMENT: Required request parameters are missing or invalid. // -// Return Value: -// If successful, the updated ChannelPartnerRepricingConfig resource, -// otherwise returns an error. -func (c *CloudChannelClient) CreateChannelPartnerRepricingConfig(ctx context.Context, req *channelpb.CreateChannelPartnerRepricingConfigRequest, opts ...gax.CallOption) (*channelpb.ChannelPartnerRepricingConfig, error) { - return c.internalClient.CreateChannelPartnerRepricingConfig(ctx, req, opts...) +// Return value: +// List of TransferableOffer for the given customer and SKU. +func (c *cloudChannelRESTClient) ListTransferableOffers(ctx context.Context, req *channelpb.ListTransferableOffersRequest, opts ...gax.CallOption) *TransferableOfferIterator { + it := &TransferableOfferIterator{} + req = proto.Clone(req).(*channelpb.ListTransferableOffersRequest) + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*channelpb.TransferableOffer, string, error) { + resp := &channelpb.ListTransferableOffersResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, "", err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:listTransferableOffers", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetTransferableOffers(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it } -// UpdateChannelPartnerRepricingConfig updates a ChannelPartnerRepricingConfig. Call this method to set -// modifications for a specific ChannelPartner’s bill. This method overwrites -// the existing CustomerRepricingConfig. -// -// You can only update configs if the -// RepricingConfig.effective_invoice_month is a -// future month. To make changes to configs for the current month, use -// CreateChannelPartnerRepricingConfig, taking note of its restrictions. -// You cannot update the RepricingConfig.effective_invoice_month. -// -// When updating a config in the future: -// -// This config must already exist. -// -// Possible Error Codes: +// GetEntitlement returns the requested Entitlement resource. // -// PERMISSION_DENIED: If the account making the request and the account -// being queried are different. +// Possible error codes: // -// INVALID_ARGUMENT: Missing or invalid required parameters in the -// request. Also displays if the updated config is for the current month or -// past months. +// PERMISSION_DENIED: The customer doesn’t belong to the reseller. // -// NOT_FOUND: The ChannelPartnerRepricingConfig specified does not exist -// or is not associated with the given account. +// INVALID_ARGUMENT: Required request parameters are missing or invalid. // -// INTERNAL: Any non-user error related to technical issues in the -// backend. In this case, contact Cloud Channel support. +// NOT_FOUND: The customer entitlement was not found. // -// Return Value: -// If successful, the updated ChannelPartnerRepricingConfig resource, -// otherwise returns an error. -func (c *CloudChannelClient) UpdateChannelPartnerRepricingConfig(ctx context.Context, req *channelpb.UpdateChannelPartnerRepricingConfigRequest, opts ...gax.CallOption) (*channelpb.ChannelPartnerRepricingConfig, error) { - return c.internalClient.UpdateChannelPartnerRepricingConfig(ctx, req, opts...) +// Return value: +// The requested Entitlement resource. +func (c *cloudChannelRESTClient) GetEntitlement(ctx context.Context, req *channelpb.GetEntitlementRequest, opts ...gax.CallOption) (*channelpb.Entitlement, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetEntitlement[0:len((*c.CallOptions).GetEntitlement):len((*c.CallOptions).GetEntitlement)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &channelpb.Entitlement{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil } -// DeleteChannelPartnerRepricingConfig deletes the given ChannelPartnerRepricingConfig permanently. You can -// only delete configs if their RepricingConfig.effective_invoice_month is -// set to a date after the current month. +// CreateEntitlement creates an entitlement for a customer. // // Possible error codes: // -// PERMISSION_DENIED: The account making the request does not own -// this customer. -// -// INVALID_ARGUMENT: Required request parameters are missing or invalid. +// PERMISSION_DENIED: The customer doesn’t belong to the reseller. // -// FAILED_PRECONDITION: The ChannelPartnerRepricingConfig is active or -// in the past. +// INVALID_ARGUMENT: // -// NOT_FOUND: No ChannelPartnerRepricingConfig found for the name in the -// request. -func (c *CloudChannelClient) DeleteChannelPartnerRepricingConfig(ctx context.Context, req *channelpb.DeleteChannelPartnerRepricingConfigRequest, opts ...gax.CallOption) error { - return c.internalClient.DeleteChannelPartnerRepricingConfig(ctx, req, opts...) -} - -// LookupOffer returns the requested Offer resource. +// Required request parameters are missing or invalid. // -// Possible error codes: +// There is already a customer entitlement for a SKU from the same +// product family. // -// PERMISSION_DENIED: The entitlement doesn’t belong to the reseller. +// INVALID_VALUE: Make sure the OfferId is valid. If it is, contact +// Google Channel support for further troubleshooting. // -// INVALID_ARGUMENT: Required request parameters are missing or invalid. +// NOT_FOUND: The customer or offer resource was not found. // -// NOT_FOUND: Entitlement or offer was not found. +// ALREADY_EXISTS: // -// Return value: -// The Offer resource. -func (c *CloudChannelClient) LookupOffer(ctx context.Context, req *channelpb.LookupOfferRequest, opts ...gax.CallOption) (*channelpb.Offer, error) { - return c.internalClient.LookupOffer(ctx, req, opts...) -} - -// ListProducts lists the Products the reseller is authorized to sell. +// The SKU was already purchased for the customer. // -// Possible error codes: +// The customer’s primary email already exists. Retry +// after changing the customer’s primary contact email. // -// INVALID_ARGUMENT: Required request parameters are missing or invalid. -func (c *CloudChannelClient) ListProducts(ctx context.Context, req *channelpb.ListProductsRequest, opts ...gax.CallOption) *ProductIterator { - return c.internalClient.ListProducts(ctx, req, opts...) -} - -// ListSkus lists the SKUs for a product the reseller is authorized to sell. +// CONDITION_NOT_MET or FAILED_PRECONDITION: // -// Possible error codes: +// The domain required for purchasing a SKU has not been verified. // -// INVALID_ARGUMENT: Required request parameters are missing or invalid. -func (c *CloudChannelClient) ListSkus(ctx context.Context, req *channelpb.ListSkusRequest, opts ...gax.CallOption) *SkuIterator { - return c.internalClient.ListSkus(ctx, req, opts...) -} - -// ListOffers lists the Offers the reseller can sell. +// A pre-requisite SKU required to purchase an Add-On SKU is missing. +// For example, Google Workspace Business Starter is required to purchase +// Vault or Drive. // -// Possible error codes: +// (Developer accounts only) Reseller and resold domain must meet the +// following naming requirements: // -// INVALID_ARGUMENT: Required request parameters are missing or invalid. -func (c *CloudChannelClient) ListOffers(ctx context.Context, req *channelpb.ListOffersRequest, opts ...gax.CallOption) *OfferIterator { - return c.internalClient.ListOffers(ctx, req, opts...) -} - -// ListPurchasableSkus lists the following: +// Domain names must start with goog-test. // -// SKUs that you can purchase for a customer +// Domain names must include the reseller domain. // -// SKUs that you can upgrade or downgrade for an entitlement. +// INTERNAL: Any non-user error related to a technical issue in the +// backend. Contact Cloud Channel support. // -// Possible error codes: +// UNKNOWN: Any non-user error related to a technical issue in the backend. +// Contact Cloud Channel support. // -// PERMISSION_DENIED: The customer doesn’t belong to the reseller. +// Return value: +// The ID of a long-running operation. // -// INVALID_ARGUMENT: Required request parameters are missing or invalid. -func (c *CloudChannelClient) ListPurchasableSkus(ctx context.Context, req *channelpb.ListPurchasableSkusRequest, opts ...gax.CallOption) *PurchasableSkuIterator { - return c.internalClient.ListPurchasableSkus(ctx, req, opts...) +// To get the results of the operation, call the GetOperation method of +// CloudChannelOperationsService. The Operation metadata will contain an +// instance of OperationMetadata. +func (c *cloudChannelRESTClient) CreateEntitlement(ctx context.Context, req *channelpb.CreateEntitlementRequest, opts ...gax.CallOption) (*CreateEntitlementOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/entitlements", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateEntitlementOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil } -// ListPurchasableOffers lists the following: -// -// Offers that you can purchase for a customer. +// ChangeParameters change parameters of the entitlement. // -// Offers that you can change for an entitlement. +// An entitlement update is a long-running operation and it updates the +// entitlement as a result of fulfillment. // // Possible error codes: // -// PERMISSION_DENIED: The customer doesn’t belong to the reseller +// PERMISSION_DENIED: The customer doesn’t belong to the reseller. // // INVALID_ARGUMENT: Required request parameters are missing or invalid. -func (c *CloudChannelClient) ListPurchasableOffers(ctx context.Context, req *channelpb.ListPurchasableOffersRequest, opts ...gax.CallOption) *PurchasableOfferIterator { - return c.internalClient.ListPurchasableOffers(ctx, req, opts...) -} - -// RegisterSubscriber registers a service account with subscriber privileges on the Cloud Pub/Sub -// topic for this Channel Services account. After you create a -// subscriber, you get the events through SubscriberEvent -// -// Possible error codes: -// -// PERMISSION_DENIED: The reseller account making the request and the -// provided reseller account are different, or the impersonated user -// is not a super admin. +// For example, the number of seats being changed is greater than the allowed +// number of max seats, or decreasing seats for a commitment based plan. // -// INVALID_ARGUMENT: Required request parameters are missing or invalid. +// NOT_FOUND: Entitlement resource not found. // // INTERNAL: Any non-user error related to a technical issue in the // backend. Contact Cloud Channel support. @@ -1810,25 +5038,93 @@ func (c *CloudChannelClient) ListPurchasableOffers(ctx context.Context, req *cha // Contact Cloud Channel support. // // Return value: -// The topic name with the registered service email address. -func (c *CloudChannelClient) RegisterSubscriber(ctx context.Context, req *channelpb.RegisterSubscriberRequest, opts ...gax.CallOption) (*channelpb.RegisterSubscriberResponse, error) { - return c.internalClient.RegisterSubscriber(ctx, req, opts...) +// The ID of a long-running operation. +// +// To get the results of the operation, call the GetOperation method of +// CloudChannelOperationsService. The Operation metadata will contain an +// instance of OperationMetadata. +func (c *cloudChannelRESTClient) ChangeParameters(ctx context.Context, req *channelpb.ChangeParametersRequest, opts ...gax.CallOption) (*ChangeParametersOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:changeParameters", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &ChangeParametersOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil } -// UnregisterSubscriber unregisters a service account with subscriber privileges on the Cloud -// Pub/Sub topic created for this Channel Services account. If there are no -// service accounts left with subscriber privileges, this deletes the topic. -// You can call ListSubscribers to check for these accounts. +// ChangeRenewalSettings updates the renewal settings for an existing customer entitlement. +// +// An entitlement update is a long-running operation and it updates the +// entitlement as a result of fulfillment. // // Possible error codes: // -// PERMISSION_DENIED: The reseller account making the request and the -// provided reseller account are different, or the impersonated user -// is not a super admin. +// PERMISSION_DENIED: The customer doesn’t belong to the reseller. // // INVALID_ARGUMENT: Required request parameters are missing or invalid. // -// NOT_FOUND: The topic resource doesn’t exist. +// NOT_FOUND: Entitlement resource not found. +// +// NOT_COMMITMENT_PLAN: Renewal Settings are only applicable for a +// commitment plan. Can’t enable or disable renewals for non-commitment plans. // // INTERNAL: Any non-user error related to a technical issue in the // backend. Contact Cloud Channel support. @@ -1837,25 +5133,90 @@ func (c *CloudChannelClient) RegisterSubscriber(ctx context.Context, req *channe // Contact Cloud Channel support. // // Return value: -// The topic name that unregistered the service email address. -// Returns a success response if the service email address wasn’t registered -// with the topic. -func (c *CloudChannelClient) UnregisterSubscriber(ctx context.Context, req *channelpb.UnregisterSubscriberRequest, opts ...gax.CallOption) (*channelpb.UnregisterSubscriberResponse, error) { - return c.internalClient.UnregisterSubscriber(ctx, req, opts...) +// The ID of a long-running operation. +// +// To get the results of the operation, call the GetOperation method of +// CloudChannelOperationsService. The Operation metadata will contain an +// instance of OperationMetadata. +func (c *cloudChannelRESTClient) ChangeRenewalSettings(ctx context.Context, req *channelpb.ChangeRenewalSettingsRequest, opts ...gax.CallOption) (*ChangeRenewalSettingsOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:changeRenewalSettings", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &ChangeRenewalSettingsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil } -// ListSubscribers lists service accounts with subscriber privileges on the Cloud Pub/Sub -// topic created for this Channel Services account. +// ChangeOffer updates the Offer for an existing customer entitlement. +// +// An entitlement update is a long-running operation and it updates the +// entitlement as a result of fulfillment. // // Possible error codes: // -// PERMISSION_DENIED: The reseller account making the request and the -// provided reseller account are different, or the impersonated user -// is not a super admin. +// PERMISSION_DENIED: The customer doesn’t belong to the reseller. // // INVALID_ARGUMENT: Required request parameters are missing or invalid. // -// NOT_FOUND: The topic resource doesn’t exist. +// NOT_FOUND: Offer or Entitlement resource not found. // // INTERNAL: Any non-user error related to a technical issue in the // backend. Contact Cloud Channel support. @@ -1864,887 +5225,1144 @@ func (c *CloudChannelClient) UnregisterSubscriber(ctx context.Context, req *chan // Contact Cloud Channel support. // // Return value: -// A list of service email addresses. -func (c *CloudChannelClient) ListSubscribers(ctx context.Context, req *channelpb.ListSubscribersRequest, opts ...gax.CallOption) *StringIterator { - return c.internalClient.ListSubscribers(ctx, req, opts...) -} +// The ID of a long-running operation. +// +// To get the results of the operation, call the GetOperation method of +// CloudChannelOperationsService. The Operation metadata will contain an +// instance of OperationMetadata. +func (c *cloudChannelRESTClient) ChangeOffer(ctx context.Context, req *channelpb.ChangeOfferRequest, opts ...gax.CallOption) (*ChangeOfferOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } -// CancelOperation is a utility method from google.longrunning.Operations. -func (c *CloudChannelClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { - return c.internalClient.CancelOperation(ctx, req, opts...) -} + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:changeOffer", req.GetName()) -// DeleteOperation is a utility method from google.longrunning.Operations. -func (c *CloudChannelClient) DeleteOperation(ctx context.Context, req *longrunningpb.DeleteOperationRequest, opts ...gax.CallOption) error { - return c.internalClient.DeleteOperation(ctx, req, opts...) -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") -// GetOperation is a utility method from google.longrunning.Operations. -func (c *CloudChannelClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { - return c.internalClient.GetOperation(ctx, req, opts...) -} + baseUrl.RawQuery = params.Encode() -// ListOperations is a utility method from google.longrunning.Operations. -func (c *CloudChannelClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { - return c.internalClient.ListOperations(ctx, req, opts...) -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) -// cloudChannelGRPCClient is a client for interacting with Cloud Channel API over gRPC transport. -// -// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. -type cloudChannelGRPCClient struct { - // Connection pool of gRPC connections to the service. - connPool gtransport.ConnPool + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers - // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE - disableDeadlines bool + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() - // Points back to the CallOptions field of the containing CloudChannelClient - CallOptions **CloudChannelCallOptions + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } - // The gRPC API client. - cloudChannelClient channelpb.CloudChannelServiceClient + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } - // LROClient is used internally to handle long-running operations. - // It is exposed so that its CallOptions can be modified if required. - // Users should not Close this client. - LROClient **lroauto.OperationsClient + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } - operationsClient longrunningpb.OperationsClient + return nil + }, opts...) + if e != nil { + return nil, e + } - // The x-goog-* metadata to be sent with each request. - xGoogMetadata metadata.MD + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &ChangeOfferOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil } -// NewCloudChannelClient creates a new cloud channel service client based on gRPC. -// The returned client must be Closed when it is done being used to clean up its underlying connections. +// StartPaidService starts paid service for a trial entitlement. // -// CloudChannelService lets Google cloud resellers and distributors manage -// their customers, channel partners, entitlements, and reports. +// Starts paid service for a trial entitlement immediately. This method is +// only applicable if a plan is set up for a trial entitlement but has some +// trial days remaining. // -// Using this service: +// Possible error codes: // -// Resellers and distributors can manage a customer entity. +// PERMISSION_DENIED: The customer doesn’t belong to the reseller. // -// Distributors can register an authorized reseller in their channel and -// provide them with delegated admin access. +// INVALID_ARGUMENT: Required request parameters are missing or invalid. // -// Resellers and distributors can manage customer entitlements. +// NOT_FOUND: Entitlement resource not found. // -// CloudChannelService exposes the following resources: +// FAILED_PRECONDITION/NOT_IN_TRIAL: This method only works for +// entitlement on trial plans. // -// Customers: An entity—usually an enterprise—managed by a reseller or -// distributor. +// INTERNAL: Any non-user error related to a technical issue in the +// backend. Contact Cloud Channel support. // -// Entitlements: An entity that provides a customer with the means to use -// a service. Entitlements are created or updated as a result of a successful -// fulfillment. +// UNKNOWN: Any non-user error related to a technical issue in the backend. +// Contact Cloud Channel support. // -// ChannelPartnerLinks: An entity that identifies links between -// distributors and their indirect resellers in a channel. -func NewCloudChannelClient(ctx context.Context, opts ...option.ClientOption) (*CloudChannelClient, error) { - clientOpts := defaultCloudChannelGRPCClientOptions() - if newCloudChannelClientHook != nil { - hookOpts, err := newCloudChannelClientHook(ctx, clientHookParams{}) - if err != nil { - return nil, err - } - clientOpts = append(clientOpts, hookOpts...) - } - - disableDeadlines, err := checkDisableDeadlines() - if err != nil { - return nil, err - } - - connPool, err := gtransport.DialPool(ctx, append(clientOpts, opts...)...) +// Return value: +// The ID of a long-running operation. +// +// To get the results of the operation, call the GetOperation method of +// CloudChannelOperationsService. The Operation metadata will contain an +// instance of OperationMetadata. +func (c *cloudChannelRESTClient) StartPaidService(ctx context.Context, req *channelpb.StartPaidServiceRequest, opts ...gax.CallOption) (*StartPaidServiceOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) if err != nil { return nil, err } - client := CloudChannelClient{CallOptions: defaultCloudChannelCallOptions()} - - c := &cloudChannelGRPCClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - cloudChannelClient: channelpb.NewCloudChannelServiceClient(connPool), - CallOptions: &client.CallOptions, - operationsClient: longrunningpb.NewOperationsClient(connPool), - } - c.setGoogleClientInfo() - - client.internalClient = c - client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + baseUrl, err := url.Parse(c.endpoint) if err != nil { - // This error "should not happen", since we are just reusing old connection pool - // and never actually need to dial. - // If this does happen, we could leak connp. However, we cannot close conn: - // If the user invoked the constructor with option.WithGRPCConn, - // we would close a connection that's still in use. - // TODO: investigate error conditions. return nil, err } - c.LROClient = &client.LROClient - return &client, nil -} - -// Connection returns a connection to the API service. -// -// Deprecated: Connections are now pooled so this method does not always -// return the same resource. -func (c *cloudChannelGRPCClient) Connection() *grpc.ClientConn { - return c.connPool.Conn() -} + baseUrl.Path += fmt.Sprintf("/v1/%v:startPaidService", req.GetName()) -// 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 *cloudChannelGRPCClient) setGoogleClientInfo(keyval ...string) { - kv := append([]string{"gl-go", versionGo()}, keyval...) - kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "grpc", grpc.Version) - c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *cloudChannelGRPCClient) Close() error { - return c.connPool.Close() -} + baseUrl.RawQuery = params.Encode() -func (c *cloudChannelGRPCClient) ListCustomers(ctx context.Context, req *channelpb.ListCustomersRequest, opts ...gax.CallOption) *CustomerIterator { - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).ListCustomers[0:len((*c.CallOptions).ListCustomers):len((*c.CallOptions).ListCustomers)], opts...) - it := &CustomerIterator{} - req = proto.Clone(req).(*channelpb.ListCustomersRequest) - it.InternalFetch = func(pageSize int, pageToken string) ([]*channelpb.Customer, string, error) { - resp := &channelpb.ListCustomersResponse{} - if pageToken != "" { - req.PageToken = pageToken - } - if pageSize > math.MaxInt32 { - req.PageSize = math.MaxInt32 - } else if pageSize != 0 { - req.PageSize = int32(pageSize) + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path } - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.cloudChannelClient.ListCustomers(ctx, req, settings.GRPC...) - return err - }, opts...) + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) if err != nil { - return nil, "", err + return err } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers - it.Response = resp - return resp.GetCustomers(), resp.GetNextPageToken(), nil - } - fetch := func(pageSize int, pageToken string) (string, error) { - items, nextPageToken, err := it.InternalFetch(pageSize, pageToken) + httpRsp, err := c.httpClient.Do(httpReq) 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) - it.pageInfo.MaxSize = int(req.GetPageSize()) - it.pageInfo.Token = req.GetPageToken() - - return it -} - -func (c *cloudChannelGRPCClient) GetCustomer(ctx context.Context, req *channelpb.GetCustomerRequest, opts ...gax.CallOption) (*channelpb.Customer, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx - } - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) - - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).GetCustomer[0:len((*c.CallOptions).GetCustomer):len((*c.CallOptions).GetCustomer)], opts...) - var resp *channelpb.Customer - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.cloudChannelClient.GetCustomer(ctx, req, settings.GRPC...) - return err - }, opts...) - if err != nil { - return nil, err - } - return resp, nil -} - -func (c *cloudChannelGRPCClient) CheckCloudIdentityAccountsExist(ctx context.Context, req *channelpb.CheckCloudIdentityAccountsExistRequest, opts ...gax.CallOption) (*channelpb.CheckCloudIdentityAccountsExistResponse, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx - } - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) - - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).CheckCloudIdentityAccountsExist[0:len((*c.CallOptions).CheckCloudIdentityAccountsExist):len((*c.CallOptions).CheckCloudIdentityAccountsExist)], opts...) - var resp *channelpb.CheckCloudIdentityAccountsExistResponse - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.cloudChannelClient.CheckCloudIdentityAccountsExist(ctx, req, settings.GRPC...) - return err - }, opts...) - if err != nil { - return nil, err - } - return resp, nil -} + return err + } + defer httpRsp.Body.Close() -func (c *cloudChannelGRPCClient) CreateCustomer(ctx context.Context, req *channelpb.CreateCustomerRequest, opts ...gax.CallOption) (*channelpb.Customer, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx - } - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).CreateCustomer[0:len((*c.CallOptions).CreateCustomer):len((*c.CallOptions).CreateCustomer)], opts...) - var resp *channelpb.Customer - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.cloudChannelClient.CreateCustomer(ctx, req, settings.GRPC...) - return err + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil }, opts...) - if err != nil { - return nil, err + if e != nil { + return nil, e } - return resp, nil + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &StartPaidServiceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil } -func (c *cloudChannelGRPCClient) UpdateCustomer(ctx context.Context, req *channelpb.UpdateCustomerRequest, opts ...gax.CallOption) (*channelpb.Customer, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx +// SuspendEntitlement suspends a previously fulfilled entitlement. +// +// An entitlement suspension is a long-running operation. +// +// Possible error codes: +// +// PERMISSION_DENIED: The customer doesn’t belong to the reseller. +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +// +// NOT_FOUND: Entitlement resource not found. +// +// NOT_ACTIVE: Entitlement is not active. +// +// INTERNAL: Any non-user error related to a technical issue in the +// backend. Contact Cloud Channel support. +// +// UNKNOWN: Any non-user error related to a technical issue in the backend. +// Contact Cloud Channel support. +// +// Return value: +// The ID of a long-running operation. +// +// To get the results of the operation, call the GetOperation method of +// CloudChannelOperationsService. The Operation metadata will contain an +// instance of OperationMetadata. +func (c *cloudChannelRESTClient) SuspendEntitlement(ctx context.Context, req *channelpb.SuspendEntitlementRequest, opts ...gax.CallOption) (*SuspendEntitlementOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err } - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "customer.name", url.QueryEscape(req.GetCustomer().GetName()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).UpdateCustomer[0:len((*c.CallOptions).UpdateCustomer):len((*c.CallOptions).UpdateCustomer)], opts...) - var resp *channelpb.Customer - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.cloudChannelClient.UpdateCustomer(ctx, req, settings.GRPC...) - return err - }, opts...) + baseUrl, err := url.Parse(c.endpoint) if err != nil { return nil, err } - return resp, nil -} + baseUrl.Path += fmt.Sprintf("/v1/%v:suspend", req.GetName()) -func (c *cloudChannelGRPCClient) DeleteCustomer(ctx context.Context, req *channelpb.DeleteCustomerRequest, opts ...gax.CallOption) error { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx - } + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).DeleteCustomer[0:len((*c.CallOptions).DeleteCustomer):len((*c.CallOptions).DeleteCustomer)], opts...) - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - _, err = c.cloudChannelClient.DeleteCustomer(ctx, req, settings.GRPC...) - return err - }, opts...) - return err -} + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers -func (c *cloudChannelGRPCClient) ImportCustomer(ctx context.Context, req *channelpb.ImportCustomerRequest, opts ...gax.CallOption) (*channelpb.Customer, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx - } - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).ImportCustomer[0:len((*c.CallOptions).ImportCustomer):len((*c.CallOptions).ImportCustomer)], opts...) - var resp *channelpb.Customer - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.cloudChannelClient.ImportCustomer(ctx, req, settings.GRPC...) - return err + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil }, opts...) - if err != nil { - return nil, err + if e != nil { + return nil, e } - return resp, nil + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &SuspendEntitlementOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil } -func (c *cloudChannelGRPCClient) ProvisionCloudIdentity(ctx context.Context, req *channelpb.ProvisionCloudIdentityRequest, opts ...gax.CallOption) (*ProvisionCloudIdentityOperation, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx +// CancelEntitlement cancels a previously fulfilled entitlement. +// +// An entitlement cancellation is a long-running operation. +// +// Possible error codes: +// +// PERMISSION_DENIED: The reseller account making the request is different +// from the reseller account in the API request. +// +// FAILED_PRECONDITION: There are Google Cloud projects linked to the +// Google Cloud entitlement’s Cloud Billing subaccount. +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +// +// NOT_FOUND: Entitlement resource not found. +// +// DELETION_TYPE_NOT_ALLOWED: Cancel is only allowed for Google Workspace +// add-ons, or entitlements for Google Cloud’s development platform. +// +// INTERNAL: Any non-user error related to a technical issue in the +// backend. Contact Cloud Channel support. +// +// UNKNOWN: Any non-user error related to a technical issue in the backend. +// Contact Cloud Channel support. +// +// Return value: +// The ID of a long-running operation. +// +// To get the results of the operation, call the GetOperation method of +// CloudChannelOperationsService. The response will contain +// google.protobuf.Empty on success. The Operation metadata will contain an +// instance of OperationMetadata. +func (c *cloudChannelRESTClient) CancelEntitlement(ctx context.Context, req *channelpb.CancelEntitlementRequest, opts ...gax.CallOption) (*CancelEntitlementOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err } - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "customer", url.QueryEscape(req.GetCustomer()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).ProvisionCloudIdentity[0:len((*c.CallOptions).ProvisionCloudIdentity):len((*c.CallOptions).ProvisionCloudIdentity)], opts...) - var resp *longrunningpb.Operation - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.cloudChannelClient.ProvisionCloudIdentity(ctx, req, settings.GRPC...) - return err - }, opts...) + baseUrl, err := url.Parse(c.endpoint) if err != nil { return nil, err } - return &ProvisionCloudIdentityOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, resp), - }, nil -} + baseUrl.Path += fmt.Sprintf("/v1/%v:cancel", req.GetName()) -func (c *cloudChannelGRPCClient) ListEntitlements(ctx context.Context, req *channelpb.ListEntitlementsRequest, opts ...gax.CallOption) *EntitlementIterator { - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).ListEntitlements[0:len((*c.CallOptions).ListEntitlements):len((*c.CallOptions).ListEntitlements)], opts...) - it := &EntitlementIterator{} - req = proto.Clone(req).(*channelpb.ListEntitlementsRequest) - it.InternalFetch = func(pageSize int, pageToken string) ([]*channelpb.Entitlement, string, error) { - resp := &channelpb.ListEntitlementsResponse{} - if pageToken != "" { - req.PageToken = pageToken + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path } - if pageSize > math.MaxInt32 { - req.PageSize = math.MaxInt32 - } else if pageSize != 0 { - req.PageSize = int32(pageSize) + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err } - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.cloudChannelClient.ListEntitlements(ctx, req, settings.GRPC...) + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { return err - }, opts...) + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) if err != nil { - return nil, "", err + return err } - it.Response = resp - return resp.GetEntitlements(), resp.GetNextPageToken(), nil + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CancelEntitlementOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ActivateEntitlement activates a previously suspended entitlement. Entitlements suspended for +// pending ToS acceptance can’t be activated using this method. +// +// An entitlement activation is a long-running operation and it updates +// the state of the customer entitlement. +// +// Possible error codes: +// +// PERMISSION_DENIED: The reseller account making the request is different +// from the reseller account in the API request. +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +// +// NOT_FOUND: Entitlement resource not found. +// +// SUSPENSION_NOT_RESELLER_INITIATED: Can only activate reseller-initiated +// suspensions and entitlements that have accepted the TOS. +// +// NOT_SUSPENDED: Can only activate suspended entitlements not in an ACTIVE +// state. +// +// INTERNAL: Any non-user error related to a technical issue in the +// backend. Contact Cloud Channel support. +// +// UNKNOWN: Any non-user error related to a technical issue in the backend. +// Contact Cloud Channel support. +// +// Return value: +// The ID of a long-running operation. +// +// To get the results of the operation, call the GetOperation method of +// CloudChannelOperationsService. The Operation metadata will contain an +// instance of OperationMetadata. +func (c *cloudChannelRESTClient) ActivateEntitlement(ctx context.Context, req *channelpb.ActivateEntitlementRequest, opts ...gax.CallOption) (*ActivateEntitlementOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err } - 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 + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err } + baseUrl.Path += fmt.Sprintf("/v1/%v:activate", req.GetName()) - it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf) - it.pageInfo.MaxSize = int(req.GetPageSize()) - it.pageInfo.Token = req.GetPageToken() + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") - return it -} + baseUrl.RawQuery = params.Encode() -func (c *cloudChannelGRPCClient) ListTransferableSkus(ctx context.Context, req *channelpb.ListTransferableSkusRequest, opts ...gax.CallOption) *TransferableSkuIterator { - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).ListTransferableSkus[0:len((*c.CallOptions).ListTransferableSkus):len((*c.CallOptions).ListTransferableSkus)], opts...) - it := &TransferableSkuIterator{} - req = proto.Clone(req).(*channelpb.ListTransferableSkusRequest) - it.InternalFetch = func(pageSize int, pageToken string) ([]*channelpb.TransferableSku, string, error) { - resp := &channelpb.ListTransferableSkusResponse{} - if pageToken != "" { - req.PageToken = pageToken - } - if pageSize > math.MaxInt32 { - req.PageSize = math.MaxInt32 - } else if pageSize != 0 { - req.PageSize = int32(pageSize) + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path } - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.cloudChannelClient.ListTransferableSkus(ctx, req, settings.GRPC...) - return err - }, opts...) + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) if err != nil { - return nil, "", err + return err } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers - it.Response = resp - return resp.GetTransferableSkus(), resp.GetNextPageToken(), nil - } - fetch := func(pageSize int, pageToken string) (string, error) { - items, nextPageToken, err := it.InternalFetch(pageSize, pageToken) + httpRsp, err := c.httpClient.Do(httpReq) if err != nil { - return "", err + return err } - it.items = append(it.items, items...) - return nextPageToken, nil - } - - it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf) - it.pageInfo.MaxSize = int(req.GetPageSize()) - it.pageInfo.Token = req.GetPageToken() - - return it -} + defer httpRsp.Body.Close() -func (c *cloudChannelGRPCClient) ListTransferableOffers(ctx context.Context, req *channelpb.ListTransferableOffersRequest, opts ...gax.CallOption) *TransferableOfferIterator { - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) - - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).ListTransferableOffers[0:len((*c.CallOptions).ListTransferableOffers):len((*c.CallOptions).ListTransferableOffers)], opts...) - it := &TransferableOfferIterator{} - req = proto.Clone(req).(*channelpb.ListTransferableOffersRequest) - it.InternalFetch = func(pageSize int, pageToken string) ([]*channelpb.TransferableOffer, string, error) { - resp := &channelpb.ListTransferableOffersResponse{} - if pageToken != "" { - req.PageToken = pageToken - } - if pageSize > math.MaxInt32 { - req.PageSize = math.MaxInt32 - } else if pageSize != 0 { - req.PageSize = int32(pageSize) - } - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.cloudChannelClient.ListTransferableOffers(ctx, req, settings.GRPC...) + if err = googleapi.CheckResponse(httpRsp); err != nil { return err - }, opts...) - if err != nil { - return nil, "", err } - it.Response = resp - return resp.GetTransferableOffers(), resp.GetNextPageToken(), nil - } - fetch := func(pageSize int, pageToken string) (string, error) { - items, nextPageToken, err := it.InternalFetch(pageSize, pageToken) + buf, err := ioutil.ReadAll(httpRsp.Body) if err != nil { - return "", err + return err } - it.items = append(it.items, items...) - return nextPageToken, nil - } - it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf) - it.pageInfo.MaxSize = int(req.GetPageSize()) - it.pageInfo.Token = req.GetPageToken() + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } - return it + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &ActivateEntitlementOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil } -func (c *cloudChannelGRPCClient) GetEntitlement(ctx context.Context, req *channelpb.GetEntitlementRequest, opts ...gax.CallOption) (*channelpb.Entitlement, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx +// TransferEntitlements transfers customer entitlements to new reseller. +// +// Possible error codes: +// +// PERMISSION_DENIED: The customer doesn’t belong to the reseller. +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +// +// NOT_FOUND: The customer or offer resource was not found. +// +// ALREADY_EXISTS: The SKU was already transferred for the customer. +// +// CONDITION_NOT_MET or FAILED_PRECONDITION: +// +// The SKU requires domain verification to transfer, but the domain is +// not verified. +// +// An Add-On SKU (example, Vault or Drive) is missing the +// pre-requisite SKU (example, G Suite Basic). +// +// (Developer accounts only) Reseller and resold domain must meet the +// following naming requirements: +// +// Domain names must start with goog-test. +// +// Domain names must include the reseller domain. +// +// Specify all transferring entitlements. +// +// INTERNAL: Any non-user error related to a technical issue in the +// backend. Contact Cloud Channel support. +// +// UNKNOWN: Any non-user error related to a technical issue in the backend. +// Contact Cloud Channel support. +// +// Return value: +// The ID of a long-running operation. +// +// To get the results of the operation, call the GetOperation method of +// CloudChannelOperationsService. The Operation metadata will contain an +// instance of OperationMetadata. +func (c *cloudChannelRESTClient) TransferEntitlements(ctx context.Context, req *channelpb.TransferEntitlementsRequest, opts ...gax.CallOption) (*TransferEntitlementsOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err } - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).GetEntitlement[0:len((*c.CallOptions).GetEntitlement):len((*c.CallOptions).GetEntitlement)], opts...) - var resp *channelpb.Entitlement - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.cloudChannelClient.GetEntitlement(ctx, req, settings.GRPC...) - return err - }, opts...) + baseUrl, err := url.Parse(c.endpoint) if err != nil { return nil, err } - return resp, nil -} + baseUrl.Path += fmt.Sprintf("/v1/%v:transferEntitlements", req.GetParent()) -func (c *cloudChannelGRPCClient) CreateEntitlement(ctx context.Context, req *channelpb.CreateEntitlementRequest, opts ...gax.CallOption) (*CreateEntitlementOperation, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx - } + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).CreateEntitlement[0:len((*c.CallOptions).CreateEntitlement):len((*c.CallOptions).CreateEntitlement)], opts...) - var resp *longrunningpb.Operation - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.cloudChannelClient.CreateEntitlement(ctx, req, settings.GRPC...) - return err - }, opts...) - if err != nil { - return nil, err - } - return &CreateEntitlementOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, resp), - }, nil -} + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers -func (c *cloudChannelGRPCClient) ChangeParameters(ctx context.Context, req *channelpb.ChangeParametersRequest, opts ...gax.CallOption) (*ChangeParametersOperation, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx - } - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).ChangeParameters[0:len((*c.CallOptions).ChangeParameters):len((*c.CallOptions).ChangeParameters)], opts...) - var resp *longrunningpb.Operation - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.cloudChannelClient.ChangeParameters(ctx, req, settings.GRPC...) - return err + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil }, opts...) - if err != nil { - return nil, err + if e != nil { + return nil, e } - return &ChangeParametersOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, resp), + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &TransferEntitlementsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, }, nil } -func (c *cloudChannelGRPCClient) ChangeRenewalSettings(ctx context.Context, req *channelpb.ChangeRenewalSettingsRequest, opts ...gax.CallOption) (*ChangeRenewalSettingsOperation, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx - } - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) - - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).ChangeRenewalSettings[0:len((*c.CallOptions).ChangeRenewalSettings):len((*c.CallOptions).ChangeRenewalSettings)], opts...) - var resp *longrunningpb.Operation - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.cloudChannelClient.ChangeRenewalSettings(ctx, req, settings.GRPC...) - return err - }, opts...) +// TransferEntitlementsToGoogle transfers customer entitlements from their current reseller to Google. +// +// Possible error codes: +// +// PERMISSION_DENIED: The customer doesn’t belong to the reseller. +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +// +// NOT_FOUND: The customer or offer resource was not found. +// +// ALREADY_EXISTS: The SKU was already transferred for the customer. +// +// CONDITION_NOT_MET or FAILED_PRECONDITION: +// +// The SKU requires domain verification to transfer, but the domain is +// not verified. +// +// An Add-On SKU (example, Vault or Drive) is missing the +// pre-requisite SKU (example, G Suite Basic). +// +// (Developer accounts only) Reseller and resold domain must meet the +// following naming requirements: +// +// Domain names must start with goog-test. +// +// Domain names must include the reseller domain. +// +// INTERNAL: Any non-user error related to a technical issue in the +// backend. Contact Cloud Channel support. +// +// UNKNOWN: Any non-user error related to a technical issue in the backend. +// Contact Cloud Channel support. +// +// Return value: +// The ID of a long-running operation. +// +// To get the results of the operation, call the GetOperation method of +// CloudChannelOperationsService. The response will contain +// google.protobuf.Empty on success. The Operation metadata will contain an +// instance of OperationMetadata. +func (c *cloudChannelRESTClient) TransferEntitlementsToGoogle(ctx context.Context, req *channelpb.TransferEntitlementsToGoogleRequest, opts ...gax.CallOption) (*TransferEntitlementsToGoogleOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) if err != nil { return nil, err } - return &ChangeRenewalSettingsOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, resp), - }, nil -} - -func (c *cloudChannelGRPCClient) ChangeOffer(ctx context.Context, req *channelpb.ChangeOfferRequest, opts ...gax.CallOption) (*ChangeOfferOperation, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx - } - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).ChangeOffer[0:len((*c.CallOptions).ChangeOffer):len((*c.CallOptions).ChangeOffer)], opts...) - var resp *longrunningpb.Operation - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.cloudChannelClient.ChangeOffer(ctx, req, settings.GRPC...) - return err - }, opts...) + baseUrl, err := url.Parse(c.endpoint) if err != nil { return nil, err } - return &ChangeOfferOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, resp), - }, nil -} + baseUrl.Path += fmt.Sprintf("/v1/%v:transferEntitlementsToGoogle", req.GetParent()) -func (c *cloudChannelGRPCClient) StartPaidService(ctx context.Context, req *channelpb.StartPaidServiceRequest, opts ...gax.CallOption) (*StartPaidServiceOperation, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx - } - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).StartPaidService[0:len((*c.CallOptions).StartPaidService):len((*c.CallOptions).StartPaidService)], opts...) - var resp *longrunningpb.Operation - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.cloudChannelClient.StartPaidService(ctx, req, settings.GRPC...) - return err + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil }, opts...) - if err != nil { - return nil, err + if e != nil { + return nil, e } - return &StartPaidServiceOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, resp), + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &TransferEntitlementsToGoogleOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, }, nil } -func (c *cloudChannelGRPCClient) SuspendEntitlement(ctx context.Context, req *channelpb.SuspendEntitlementRequest, opts ...gax.CallOption) (*SuspendEntitlementOperation, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx - } - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) +// ListChannelPartnerLinks list ChannelPartnerLinks belonging to a distributor. +// You must be a distributor to call this method. +// +// Possible error codes: +// +// PERMISSION_DENIED: The reseller account making the request is different +// from the reseller account in the API request. +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +// +// Return value: +// The list of the distributor account’s ChannelPartnerLink resources. +func (c *cloudChannelRESTClient) ListChannelPartnerLinks(ctx context.Context, req *channelpb.ListChannelPartnerLinksRequest, opts ...gax.CallOption) *ChannelPartnerLinkIterator { + it := &ChannelPartnerLinkIterator{} + req = proto.Clone(req).(*channelpb.ListChannelPartnerLinksRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*channelpb.ChannelPartnerLink, string, error) { + resp := &channelpb.ListChannelPartnerLinksResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/channelPartnerLinks", req.GetParent()) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).SuspendEntitlement[0:len((*c.CallOptions).SuspendEntitlement):len((*c.CallOptions).SuspendEntitlement)], opts...) - var resp *longrunningpb.Operation - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.cloudChannelClient.SuspendEntitlement(ctx, req, settings.GRPC...) - return err - }, opts...) - if err != nil { - return nil, err + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + if req.GetView() != 0 { + params.Add("view", fmt.Sprintf("%v", req.GetView())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetChannelPartnerLinks(), resp.GetNextPageToken(), nil } - return &SuspendEntitlementOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, resp), - }, nil -} -func (c *cloudChannelGRPCClient) CancelEntitlement(ctx context.Context, req *channelpb.CancelEntitlementRequest, opts ...gax.CallOption) (*CancelEntitlementOperation, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx + 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 } - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).CancelEntitlement[0:len((*c.CallOptions).CancelEntitlement):len((*c.CallOptions).CancelEntitlement)], opts...) - var resp *longrunningpb.Operation - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.cloudChannelClient.CancelEntitlement(ctx, req, settings.GRPC...) - return err - }, opts...) + it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetChannelPartnerLink returns the requested ChannelPartnerLink resource. +// You must be a distributor to call this method. +// +// Possible error codes: +// +// PERMISSION_DENIED: The reseller account making the request is different +// from the reseller account in the API request. +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +// +// NOT_FOUND: ChannelPartnerLink resource not found because of an +// invalid channel partner link name. +// +// Return value: +// The ChannelPartnerLink resource. +func (c *cloudChannelRESTClient) GetChannelPartnerLink(ctx context.Context, req *channelpb.GetChannelPartnerLinkRequest, opts ...gax.CallOption) (*channelpb.ChannelPartnerLink, error) { + baseUrl, err := url.Parse(c.endpoint) if err != nil { return nil, err } - return &CancelEntitlementOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, resp), - }, nil -} + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) -func (c *cloudChannelGRPCClient) ActivateEntitlement(ctx context.Context, req *channelpb.ActivateEntitlementRequest, opts ...gax.CallOption) (*ActivateEntitlementOperation, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetView() != 0 { + params.Add("view", fmt.Sprintf("%v", req.GetView())) } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).ActivateEntitlement[0:len((*c.CallOptions).ActivateEntitlement):len((*c.CallOptions).ActivateEntitlement)], opts...) - var resp *longrunningpb.Operation - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.cloudChannelClient.ActivateEntitlement(ctx, req, settings.GRPC...) - return err + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetChannelPartnerLink[0:len((*c.CallOptions).GetChannelPartnerLink):len((*c.CallOptions).GetChannelPartnerLink)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &channelpb.ChannelPartnerLink{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil }, opts...) - if err != nil { - return nil, err + if e != nil { + return nil, e } - return &ActivateEntitlementOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, resp), - }, nil + return resp, nil } -func (c *cloudChannelGRPCClient) TransferEntitlements(ctx context.Context, req *channelpb.TransferEntitlementsRequest, opts ...gax.CallOption) (*TransferEntitlementsOperation, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx - } - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) - - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).TransferEntitlements[0:len((*c.CallOptions).TransferEntitlements):len((*c.CallOptions).TransferEntitlements)], opts...) - var resp *longrunningpb.Operation - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.cloudChannelClient.TransferEntitlements(ctx, req, settings.GRPC...) - return err - }, opts...) +// CreateChannelPartnerLink initiates a channel partner link between a distributor and a reseller, or +// between resellers in an n-tier reseller channel. +// Invited partners need to follow the invite_link_uri provided in the +// response to accept. After accepting the invitation, a link is set up +// between the two parties. +// You must be a distributor to call this method. +// +// Possible error codes: +// +// PERMISSION_DENIED: The reseller account making the request is different +// from the reseller account in the API request. +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +// +// ALREADY_EXISTS: The ChannelPartnerLink sent in the request already +// exists. +// +// NOT_FOUND: No Cloud Identity customer exists for provided domain. +// +// INTERNAL: Any non-user error related to a technical issue in the +// backend. Contact Cloud Channel support. +// +// UNKNOWN: Any non-user error related to a technical issue in the backend. +// Contact Cloud Channel support. +// +// Return value: +// The new ChannelPartnerLink resource. +func (c *cloudChannelRESTClient) CreateChannelPartnerLink(ctx context.Context, req *channelpb.CreateChannelPartnerLinkRequest, opts ...gax.CallOption) (*channelpb.ChannelPartnerLink, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetChannelPartnerLink() + jsonReq, err := m.Marshal(body) if err != nil { return nil, err } - return &TransferEntitlementsOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, resp), - }, nil -} - -func (c *cloudChannelGRPCClient) TransferEntitlementsToGoogle(ctx context.Context, req *channelpb.TransferEntitlementsToGoogleRequest, opts ...gax.CallOption) (*TransferEntitlementsToGoogleOperation, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx - } - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).TransferEntitlementsToGoogle[0:len((*c.CallOptions).TransferEntitlementsToGoogle):len((*c.CallOptions).TransferEntitlementsToGoogle)], opts...) - var resp *longrunningpb.Operation - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.cloudChannelClient.TransferEntitlementsToGoogle(ctx, req, settings.GRPC...) - return err - }, opts...) + baseUrl, err := url.Parse(c.endpoint) if err != nil { return nil, err } - return &TransferEntitlementsToGoogleOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, resp), - }, nil -} + baseUrl.Path += fmt.Sprintf("/v1/%v/channelPartnerLinks", req.GetParent()) -func (c *cloudChannelGRPCClient) ListChannelPartnerLinks(ctx context.Context, req *channelpb.ListChannelPartnerLinksRequest, opts ...gax.CallOption) *ChannelPartnerLinkIterator { + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).ListChannelPartnerLinks[0:len((*c.CallOptions).ListChannelPartnerLinks):len((*c.CallOptions).ListChannelPartnerLinks)], opts...) - it := &ChannelPartnerLinkIterator{} - req = proto.Clone(req).(*channelpb.ListChannelPartnerLinksRequest) - it.InternalFetch = func(pageSize int, pageToken string) ([]*channelpb.ChannelPartnerLink, string, error) { - resp := &channelpb.ListChannelPartnerLinksResponse{} - if pageToken != "" { - req.PageToken = pageToken - } - if pageSize > math.MaxInt32 { - req.PageSize = math.MaxInt32 - } else if pageSize != 0 { - req.PageSize = int32(pageSize) + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateChannelPartnerLink[0:len((*c.CallOptions).CreateChannelPartnerLink):len((*c.CallOptions).CreateChannelPartnerLink)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &channelpb.ChannelPartnerLink{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path } - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.cloudChannelClient.ListChannelPartnerLinks(ctx, req, settings.GRPC...) - return err - }, opts...) + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) if err != nil { - return nil, "", err + return err } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers - it.Response = resp - return resp.GetChannelPartnerLinks(), resp.GetNextPageToken(), nil - } - fetch := func(pageSize int, pageToken string) (string, error) { - items, nextPageToken, err := it.InternalFetch(pageSize, pageToken) + httpRsp, err := c.httpClient.Do(httpReq) if err != nil { - return "", err + return err } - it.items = append(it.items, items...) - return nextPageToken, nil - } + defer httpRsp.Body.Close() - it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf) - it.pageInfo.MaxSize = int(req.GetPageSize()) - it.pageInfo.Token = req.GetPageToken() + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } - return it -} + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } -func (c *cloudChannelGRPCClient) GetChannelPartnerLink(ctx context.Context, req *channelpb.GetChannelPartnerLinkRequest, opts ...gax.CallOption) (*channelpb.ChannelPartnerLink, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx - } - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).GetChannelPartnerLink[0:len((*c.CallOptions).GetChannelPartnerLink):len((*c.CallOptions).GetChannelPartnerLink)], opts...) - var resp *channelpb.ChannelPartnerLink - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.cloudChannelClient.GetChannelPartnerLink(ctx, req, settings.GRPC...) - return err + return nil }, opts...) - if err != nil { - return nil, err + if e != nil { + return nil, e } return resp, nil } -func (c *cloudChannelGRPCClient) CreateChannelPartnerLink(ctx context.Context, req *channelpb.CreateChannelPartnerLinkRequest, opts ...gax.CallOption) (*channelpb.ChannelPartnerLink, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx +// UpdateChannelPartnerLink updates a channel partner link. Distributors call this method to change a +// link’s status. For example, to suspend a partner link. +// You must be a distributor to call this method. +// +// Possible error codes: +// +// PERMISSION_DENIED: The reseller account making the request is different +// from the reseller account in the API request. +// +// INVALID_ARGUMENT: +// +// Required request parameters are missing or invalid. +// +// Link state cannot change from invited to active or suspended. +// +// Cannot send reseller_cloud_identity_id, invite_url, or name in update +// mask. +// +// NOT_FOUND: ChannelPartnerLink resource not found. +// +// INTERNAL: Any non-user error related to a technical issue in the +// backend. Contact Cloud Channel support. +// +// UNKNOWN: Any non-user error related to a technical issue in the backend. +// Contact Cloud Channel support. +// +// Return value: +// The updated ChannelPartnerLink resource. +func (c *cloudChannelRESTClient) UpdateChannelPartnerLink(ctx context.Context, req *channelpb.UpdateChannelPartnerLinkRequest, opts ...gax.CallOption) (*channelpb.ChannelPartnerLink, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err } - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).CreateChannelPartnerLink[0:len((*c.CallOptions).CreateChannelPartnerLink):len((*c.CallOptions).CreateChannelPartnerLink)], opts...) - var resp *channelpb.ChannelPartnerLink - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.cloudChannelClient.CreateChannelPartnerLink(ctx, req, settings.GRPC...) - return err - }, opts...) + baseUrl, err := url.Parse(c.endpoint) if err != nil { return nil, err } - return resp, nil -} + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) -func (c *cloudChannelGRPCClient) UpdateChannelPartnerLink(ctx context.Context, req *channelpb.UpdateChannelPartnerLinkRequest, opts ...gax.CallOption) (*channelpb.ChannelPartnerLink, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx - } + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) opts = append((*c.CallOptions).UpdateChannelPartnerLink[0:len((*c.CallOptions).UpdateChannelPartnerLink):len((*c.CallOptions).UpdateChannelPartnerLink)], opts...) - var resp *channelpb.ChannelPartnerLink - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.cloudChannelClient.UpdateChannelPartnerLink(ctx, req, settings.GRPC...) - return err + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &channelpb.ChannelPartnerLink{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil }, opts...) - if err != nil { - return nil, err + if e != nil { + return nil, e } return resp, nil } -func (c *cloudChannelGRPCClient) GetCustomerRepricingConfig(ctx context.Context, req *channelpb.GetCustomerRepricingConfigRequest, opts ...gax.CallOption) (*channelpb.CustomerRepricingConfig, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx +// GetCustomerRepricingConfig gets information about how a Reseller modifies their bill before sending +// it to a Customer. +// +// Possible Error Codes: +// +// PERMISSION_DENIED: If the account making the request and the account +// being queried are different. +// +// NOT_FOUND: The CustomerRepricingConfig was not found. +// +// INTERNAL: Any non-user error related to technical issues in the +// backend. In this case, contact Cloud Channel support. +// +// Return Value: +// If successful, the CustomerRepricingConfig resource, otherwise returns +// an error. +func (c *cloudChannelRESTClient) GetCustomerRepricingConfig(ctx context.Context, req *channelpb.GetCustomerRepricingConfigRequest, opts ...gax.CallOption) (*channelpb.CustomerRepricingConfig, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) opts = append((*c.CallOptions).GetCustomerRepricingConfig[0:len((*c.CallOptions).GetCustomerRepricingConfig):len((*c.CallOptions).GetCustomerRepricingConfig)], opts...) - var resp *channelpb.CustomerRepricingConfig - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.cloudChannelClient.GetCustomerRepricingConfig(ctx, req, settings.GRPC...) - return err + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &channelpb.CustomerRepricingConfig{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil }, opts...) - if err != nil { - return nil, err + if e != nil { + return nil, e } return resp, nil } -func (c *cloudChannelGRPCClient) ListCustomerRepricingConfigs(ctx context.Context, req *channelpb.ListCustomerRepricingConfigsRequest, opts ...gax.CallOption) *CustomerRepricingConfigIterator { - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) - - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).ListCustomerRepricingConfigs[0:len((*c.CallOptions).ListCustomerRepricingConfigs):len((*c.CallOptions).ListCustomerRepricingConfigs)], opts...) +// ListCustomerRepricingConfigs lists information about how a Reseller modifies their bill before sending +// it to a Customer. +// +// Possible Error Codes: +// +// PERMISSION_DENIED: If the account making the request and the account +// being queried are different. +// +// NOT_FOUND: The CustomerRepricingConfig specified does not exist or is +// not associated with the given account. +// +// INTERNAL: Any non-user error related to technical issues in the +// backend. In this case, contact Cloud Channel support. +// +// Return Value: +// If successful, the CustomerRepricingConfig resources. The +// data for each resource is displayed in the ascending order of: +// +// customer ID +// +// RepricingConfig.EntitlementGranularity.entitlement +// +// RepricingConfig.effective_invoice_month +// +// CustomerRepricingConfig.update_time +// +// If unsuccessful, returns an error. +func (c *cloudChannelRESTClient) ListCustomerRepricingConfigs(ctx context.Context, req *channelpb.ListCustomerRepricingConfigsRequest, opts ...gax.CallOption) *CustomerRepricingConfigIterator { it := &CustomerRepricingConfigIterator{} req = proto.Clone(req).(*channelpb.ListCustomerRepricingConfigsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} it.InternalFetch = func(pageSize int, pageToken string) ([]*channelpb.CustomerRepricingConfig, string, error) { resp := &channelpb.ListCustomerRepricingConfigsResponse{} if pageToken != "" { @@ -2755,18 +6373,66 @@ func (c *cloudChannelGRPCClient) ListCustomerRepricingConfigs(ctx context.Contex } else if pageSize != 0 { req.PageSize = int32(pageSize) } - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.cloudChannelClient.ListCustomerRepricingConfigs(ctx, req, settings.GRPC...) - return err - }, opts...) + baseUrl, err := url.Parse(c.endpoint) if err != nil { return nil, "", err } + baseUrl.Path += fmt.Sprintf("/v1/%v/customerRepricingConfigs", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } it.Response = resp return resp.GetCustomerRepricingConfigs(), resp.GetNextPageToken(), nil } + fetch := func(pageSize int, pageToken string) (string, error) { items, nextPageToken, err := it.InternalFetch(pageSize, pageToken) if err != nil { @@ -2783,97 +6449,367 @@ func (c *cloudChannelGRPCClient) ListCustomerRepricingConfigs(ctx context.Contex return it } -func (c *cloudChannelGRPCClient) CreateCustomerRepricingConfig(ctx context.Context, req *channelpb.CreateCustomerRepricingConfigRequest, opts ...gax.CallOption) (*channelpb.CustomerRepricingConfig, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx +// CreateCustomerRepricingConfig creates a CustomerRepricingConfig. Call this method to set modifications +// for a specific customer’s bill. You can only create configs if the +// RepricingConfig.effective_invoice_month is a +// future month. If needed, you can create a config for the current month, +// with some restrictions. +// +// When creating a config for a future month, make sure there are no existing +// configs for that +// RepricingConfig.effective_invoice_month. +// +// The following restrictions are for creating configs in the current month. +// +// This functionality is reserved for recovering from an erroneous config, +// and should not be used for regular business cases. +// +// The new config will not modify exports used with other configs. +// Changes to the config may be immediate, but may take up to 24 hours. +// +// There is a limit of ten configs for any +// RepricingConfig.EntitlementGranularity.entitlement +// or RepricingConfig.effective_invoice_month. +// +// The contained CustomerRepricingConfig.repricing_config vaule must be +// different from the value used in the current config for a +// RepricingConfig.EntitlementGranularity.entitlement. +// +// Possible Error Codes: +// +// PERMISSION_DENIED: If the account making the request and the account +// being queried are different. +// +// INVALID_ARGUMENT: Missing or invalid required parameters in the +// request. Also displays if the updated config is for the current month or +// past months. +// +// NOT_FOUND: The CustomerRepricingConfig specified does not exist or is +// not associated with the given account. +// +// INTERNAL: Any non-user error related to technical issues in the +// backend. In this case, contact Cloud Channel support. +// +// Return Value: +// If successful, the updated CustomerRepricingConfig resource, otherwise +// returns an error. +func (c *cloudChannelRESTClient) CreateCustomerRepricingConfig(ctx context.Context, req *channelpb.CreateCustomerRepricingConfigRequest, opts ...gax.CallOption) (*channelpb.CustomerRepricingConfig, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetCustomerRepricingConfig() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err } + baseUrl.Path += fmt.Sprintf("/v1/%v/customerRepricingConfigs", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) opts = append((*c.CallOptions).CreateCustomerRepricingConfig[0:len((*c.CallOptions).CreateCustomerRepricingConfig):len((*c.CallOptions).CreateCustomerRepricingConfig)], opts...) - var resp *channelpb.CustomerRepricingConfig - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.cloudChannelClient.CreateCustomerRepricingConfig(ctx, req, settings.GRPC...) - return err + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &channelpb.CustomerRepricingConfig{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil }, opts...) - if err != nil { - return nil, err + if e != nil { + return nil, e } return resp, nil } -func (c *cloudChannelGRPCClient) UpdateCustomerRepricingConfig(ctx context.Context, req *channelpb.UpdateCustomerRepricingConfigRequest, opts ...gax.CallOption) (*channelpb.CustomerRepricingConfig, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx +// UpdateCustomerRepricingConfig updates a CustomerRepricingConfig. Call this method to set modifications +// for a specific customer’s bill. This method overwrites the existing +// CustomerRepricingConfig. +// +// You can only update configs if the +// RepricingConfig.effective_invoice_month is a +// future month. To make changes to configs for the current month, use +// CreateCustomerRepricingConfig, taking note of its restrictions. You +// cannot update the RepricingConfig.effective_invoice_month. +// +// When updating a config in the future: +// +// This config must already exist. +// +// Possible Error Codes: +// +// PERMISSION_DENIED: If the account making the request and the account +// being queried are different. +// +// INVALID_ARGUMENT: Missing or invalid required parameters in the +// request. Also displays if the updated config is for the current month or +// past months. +// +// NOT_FOUND: The CustomerRepricingConfig specified does not exist or is +// not associated with the given account. +// +// INTERNAL: Any non-user error related to technical issues in the +// backend. In this case, contact Cloud Channel support. +// +// Return Value: +// If successful, the updated CustomerRepricingConfig resource, otherwise +// returns an error. +func (c *cloudChannelRESTClient) UpdateCustomerRepricingConfig(ctx context.Context, req *channelpb.UpdateCustomerRepricingConfigRequest, opts ...gax.CallOption) (*channelpb.CustomerRepricingConfig, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetCustomerRepricingConfig() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetCustomerRepricingConfig().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "customer_repricing_config.name", url.QueryEscape(req.GetCustomerRepricingConfig().GetName()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) opts = append((*c.CallOptions).UpdateCustomerRepricingConfig[0:len((*c.CallOptions).UpdateCustomerRepricingConfig):len((*c.CallOptions).UpdateCustomerRepricingConfig)], opts...) - var resp *channelpb.CustomerRepricingConfig - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.cloudChannelClient.UpdateCustomerRepricingConfig(ctx, req, settings.GRPC...) - return err + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &channelpb.CustomerRepricingConfig{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil }, opts...) - if err != nil { - return nil, err + if e != nil { + return nil, e } return resp, nil } -func (c *cloudChannelGRPCClient) DeleteCustomerRepricingConfig(ctx context.Context, req *channelpb.DeleteCustomerRepricingConfigRequest, opts ...gax.CallOption) error { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx +// DeleteCustomerRepricingConfig deletes the given CustomerRepricingConfig permanently. You can only +// delete configs if their RepricingConfig.effective_invoice_month is set +// to a date after the current month. +// +// Possible error codes: +// +// PERMISSION_DENIED: The account making the request does not own +// this customer. +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +// +// FAILED_PRECONDITION: The CustomerRepricingConfig is active or in the +// past. +// +// NOT_FOUND: No CustomerRepricingConfig found for the name in the +// request. +func (c *cloudChannelRESTClient) DeleteCustomerRepricingConfig(ctx context.Context, req *channelpb.DeleteCustomerRepricingConfigRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).DeleteCustomerRepricingConfig[0:len((*c.CallOptions).DeleteCustomerRepricingConfig):len((*c.CallOptions).DeleteCustomerRepricingConfig)], opts...) - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - _, err = c.cloudChannelClient.DeleteCustomerRepricingConfig(ctx, req, settings.GRPC...) - return err + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) }, opts...) - return err } -func (c *cloudChannelGRPCClient) GetChannelPartnerRepricingConfig(ctx context.Context, req *channelpb.GetChannelPartnerRepricingConfigRequest, opts ...gax.CallOption) (*channelpb.ChannelPartnerRepricingConfig, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx +// GetChannelPartnerRepricingConfig gets information about how a Distributor modifies their bill before sending +// it to a ChannelPartner. +// +// Possible Error Codes: +// +// PERMISSION_DENIED: If the account making the request and the account +// being queried are different. +// +// NOT_FOUND: The ChannelPartnerRepricingConfig was not found. +// +// INTERNAL: Any non-user error related to technical issues in the +// backend. In this case, contact Cloud Channel support. +// +// Return Value: +// If successful, the ChannelPartnerRepricingConfig resource, otherwise +// returns an error. +func (c *cloudChannelRESTClient) GetChannelPartnerRepricingConfig(ctx context.Context, req *channelpb.GetChannelPartnerRepricingConfigRequest, opts ...gax.CallOption) (*channelpb.ChannelPartnerRepricingConfig, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).GetChannelPartnerRepricingConfig[0:len((*c.CallOptions).GetChannelPartnerRepricingConfig):len((*c.CallOptions).GetChannelPartnerRepricingConfig)], opts...) - var resp *channelpb.ChannelPartnerRepricingConfig - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.cloudChannelClient.GetChannelPartnerRepricingConfig(ctx, req, settings.GRPC...) - return err + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetChannelPartnerRepricingConfig[0:len((*c.CallOptions).GetChannelPartnerRepricingConfig):len((*c.CallOptions).GetChannelPartnerRepricingConfig)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &channelpb.ChannelPartnerRepricingConfig{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil }, opts...) - if err != nil { - return nil, err + if e != nil { + return nil, e } return resp, nil } -func (c *cloudChannelGRPCClient) ListChannelPartnerRepricingConfigs(ctx context.Context, req *channelpb.ListChannelPartnerRepricingConfigsRequest, opts ...gax.CallOption) *ChannelPartnerRepricingConfigIterator { - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) - - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).ListChannelPartnerRepricingConfigs[0:len((*c.CallOptions).ListChannelPartnerRepricingConfigs):len((*c.CallOptions).ListChannelPartnerRepricingConfigs)], opts...) +// ListChannelPartnerRepricingConfigs lists information about how a Reseller modifies their bill before sending +// it to a ChannelPartner. +// +// Possible Error Codes: +// +// PERMISSION_DENIED: If the account making the request and the account +// being queried are different. +// +// NOT_FOUND: The ChannelPartnerRepricingConfig specified does not exist +// or is not associated with the given account. +// +// INTERNAL: Any non-user error related to technical issues in the +// backend. In this case, contact Cloud Channel support. +// +// Return Value: +// If successful, the ChannelPartnerRepricingConfig resources. +// The data for each resource is displayed in the ascending order of: +// +// channel partner ID +// +// RepricingConfig.effective_invoice_month +// +// ChannelPartnerRepricingConfig.update_time +// +// If unsuccessful, returns an error. +func (c *cloudChannelRESTClient) ListChannelPartnerRepricingConfigs(ctx context.Context, req *channelpb.ListChannelPartnerRepricingConfigsRequest, opts ...gax.CallOption) *ChannelPartnerRepricingConfigIterator { it := &ChannelPartnerRepricingConfigIterator{} req = proto.Clone(req).(*channelpb.ListChannelPartnerRepricingConfigsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} it.InternalFetch = func(pageSize int, pageToken string) ([]*channelpb.ChannelPartnerRepricingConfig, string, error) { resp := &channelpb.ListChannelPartnerRepricingConfigsResponse{} if pageToken != "" { @@ -2884,18 +6820,66 @@ func (c *cloudChannelGRPCClient) ListChannelPartnerRepricingConfigs(ctx context. } else if pageSize != 0 { req.PageSize = int32(pageSize) } - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.cloudChannelClient.ListChannelPartnerRepricingConfigs(ctx, req, settings.GRPC...) - return err - }, opts...) + baseUrl, err := url.Parse(c.endpoint) if err != nil { return nil, "", err } + baseUrl.Path += fmt.Sprintf("/v1/%v/channelPartnerRepricingConfigs", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } it.Response = resp return resp.GetChannelPartnerRepricingConfigs(), resp.GetNextPageToken(), nil } + fetch := func(pageSize int, pageToken string) (string, error) { items, nextPageToken, err := it.InternalFetch(pageSize, pageToken) if err != nil { @@ -2912,95 +6896,342 @@ func (c *cloudChannelGRPCClient) ListChannelPartnerRepricingConfigs(ctx context. return it } -func (c *cloudChannelGRPCClient) CreateChannelPartnerRepricingConfig(ctx context.Context, req *channelpb.CreateChannelPartnerRepricingConfigRequest, opts ...gax.CallOption) (*channelpb.ChannelPartnerRepricingConfig, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx +// CreateChannelPartnerRepricingConfig creates a ChannelPartnerRepricingConfig. Call this method to set +// modifications for a specific ChannelPartner’s bill. You can only create +// configs if the RepricingConfig.effective_invoice_month is a future +// month. If needed, you can create a config for the current month, with some +// restrictions. +// +// When creating a config for a future month, make sure there are no existing +// configs for that +// RepricingConfig.effective_invoice_month. +// +// The following restrictions are for creating configs in the current month. +// +// This functionality is reserved for recovering from an erroneous config, +// and should not be used for regular business cases. +// +// The new config will not modify exports used with other configs. +// Changes to the config may be immediate, but may take up to 24 hours. +// +// There is a limit of ten configs for any ChannelPartner or +// RepricingConfig.effective_invoice_month. +// +// The contained ChannelPartnerRepricingConfig.repricing_config vaule +// must be different from the value used in the current config for a +// ChannelPartner. +// +// Possible Error Codes: +// +// PERMISSION_DENIED: If the account making the request and the account +// being queried are different. +// +// INVALID_ARGUMENT: Missing or invalid required parameters in the +// request. Also displays if the updated config is for the current month or +// past months. +// +// NOT_FOUND: The ChannelPartnerRepricingConfig specified does not exist +// or is not associated with the given account. +// +// INTERNAL: Any non-user error related to technical issues in the +// backend. In this case, contact Cloud Channel support. +// +// Return Value: +// If successful, the updated ChannelPartnerRepricingConfig resource, +// otherwise returns an error. +func (c *cloudChannelRESTClient) CreateChannelPartnerRepricingConfig(ctx context.Context, req *channelpb.CreateChannelPartnerRepricingConfigRequest, opts ...gax.CallOption) (*channelpb.ChannelPartnerRepricingConfig, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetChannelPartnerRepricingConfig() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/channelPartnerRepricingConfigs", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) opts = append((*c.CallOptions).CreateChannelPartnerRepricingConfig[0:len((*c.CallOptions).CreateChannelPartnerRepricingConfig):len((*c.CallOptions).CreateChannelPartnerRepricingConfig)], opts...) - var resp *channelpb.ChannelPartnerRepricingConfig - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.cloudChannelClient.CreateChannelPartnerRepricingConfig(ctx, req, settings.GRPC...) - return err + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &channelpb.ChannelPartnerRepricingConfig{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil }, opts...) - if err != nil { - return nil, err + if e != nil { + return nil, e } return resp, nil } -func (c *cloudChannelGRPCClient) UpdateChannelPartnerRepricingConfig(ctx context.Context, req *channelpb.UpdateChannelPartnerRepricingConfigRequest, opts ...gax.CallOption) (*channelpb.ChannelPartnerRepricingConfig, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx +// UpdateChannelPartnerRepricingConfig updates a ChannelPartnerRepricingConfig. Call this method to set +// modifications for a specific ChannelPartner’s bill. This method overwrites +// the existing CustomerRepricingConfig. +// +// You can only update configs if the +// RepricingConfig.effective_invoice_month is a +// future month. To make changes to configs for the current month, use +// CreateChannelPartnerRepricingConfig, taking note of its restrictions. +// You cannot update the RepricingConfig.effective_invoice_month. +// +// When updating a config in the future: +// +// This config must already exist. +// +// Possible Error Codes: +// +// PERMISSION_DENIED: If the account making the request and the account +// being queried are different. +// +// INVALID_ARGUMENT: Missing or invalid required parameters in the +// request. Also displays if the updated config is for the current month or +// past months. +// +// NOT_FOUND: The ChannelPartnerRepricingConfig specified does not exist +// or is not associated with the given account. +// +// INTERNAL: Any non-user error related to technical issues in the +// backend. In this case, contact Cloud Channel support. +// +// Return Value: +// If successful, the updated ChannelPartnerRepricingConfig resource, +// otherwise returns an error. +func (c *cloudChannelRESTClient) UpdateChannelPartnerRepricingConfig(ctx context.Context, req *channelpb.UpdateChannelPartnerRepricingConfigRequest, opts ...gax.CallOption) (*channelpb.ChannelPartnerRepricingConfig, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetChannelPartnerRepricingConfig() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetChannelPartnerRepricingConfig().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "channel_partner_repricing_config.name", url.QueryEscape(req.GetChannelPartnerRepricingConfig().GetName()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) opts = append((*c.CallOptions).UpdateChannelPartnerRepricingConfig[0:len((*c.CallOptions).UpdateChannelPartnerRepricingConfig):len((*c.CallOptions).UpdateChannelPartnerRepricingConfig)], opts...) - var resp *channelpb.ChannelPartnerRepricingConfig - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.cloudChannelClient.UpdateChannelPartnerRepricingConfig(ctx, req, settings.GRPC...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &channelpb.ChannelPartnerRepricingConfig{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteChannelPartnerRepricingConfig deletes the given ChannelPartnerRepricingConfig permanently. You can +// only delete configs if their RepricingConfig.effective_invoice_month is +// set to a date after the current month. +// +// Possible error codes: +// +// PERMISSION_DENIED: The account making the request does not own +// this customer. +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +// +// FAILED_PRECONDITION: The ChannelPartnerRepricingConfig is active or +// in the past. +// +// NOT_FOUND: No ChannelPartnerRepricingConfig found for the name in the +// request. +func (c *cloudChannelRESTClient) DeleteChannelPartnerRepricingConfig(ctx context.Context, req *channelpb.DeleteChannelPartnerRepricingConfigRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) }, opts...) +} + +// LookupOffer returns the requested Offer resource. +// +// Possible error codes: +// +// PERMISSION_DENIED: The entitlement doesn’t belong to the reseller. +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +// +// NOT_FOUND: Entitlement or offer was not found. +// +// Return value: +// The Offer resource. +func (c *cloudChannelRESTClient) LookupOffer(ctx context.Context, req *channelpb.LookupOfferRequest, opts ...gax.CallOption) (*channelpb.Offer, error) { + baseUrl, err := url.Parse(c.endpoint) if err != nil { return nil, err } - return resp, nil -} + baseUrl.Path += fmt.Sprintf("/v1/%v:lookupOffer", req.GetEntitlement()) -func (c *cloudChannelGRPCClient) DeleteChannelPartnerRepricingConfig(ctx context.Context, req *channelpb.DeleteChannelPartnerRepricingConfigRequest, opts ...gax.CallOption) error { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx - } - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).DeleteChannelPartnerRepricingConfig[0:len((*c.CallOptions).DeleteChannelPartnerRepricingConfig):len((*c.CallOptions).DeleteChannelPartnerRepricingConfig)], opts...) - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - _, err = c.cloudChannelClient.DeleteChannelPartnerRepricingConfig(ctx, req, settings.GRPC...) - return err - }, opts...) - return err -} + baseUrl.RawQuery = params.Encode() -func (c *cloudChannelGRPCClient) LookupOffer(ctx context.Context, req *channelpb.LookupOfferRequest, opts ...gax.CallOption) (*channelpb.Offer, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx - } + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "entitlement", url.QueryEscape(req.GetEntitlement()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) opts = append((*c.CallOptions).LookupOffer[0:len((*c.CallOptions).LookupOffer):len((*c.CallOptions).LookupOffer)], opts...) - var resp *channelpb.Offer - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.cloudChannelClient.LookupOffer(ctx, req, settings.GRPC...) - return err + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &channelpb.Offer{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil }, opts...) - if err != nil { - return nil, err + if e != nil { + return nil, e } return resp, nil } -func (c *cloudChannelGRPCClient) ListProducts(ctx context.Context, req *channelpb.ListProductsRequest, opts ...gax.CallOption) *ProductIterator { - ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append((*c.CallOptions).ListProducts[0:len((*c.CallOptions).ListProducts):len((*c.CallOptions).ListProducts)], opts...) +// ListProducts lists the Products the reseller is authorized to sell. +// +// Possible error codes: +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +func (c *cloudChannelRESTClient) ListProducts(ctx context.Context, req *channelpb.ListProductsRequest, opts ...gax.CallOption) *ProductIterator { it := &ProductIterator{} req = proto.Clone(req).(*channelpb.ListProductsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} it.InternalFetch = func(pageSize int, pageToken string) ([]*channelpb.Product, string, error) { resp := &channelpb.ListProductsResponse{} if pageToken != "" { @@ -3011,18 +7242,67 @@ func (c *cloudChannelGRPCClient) ListProducts(ctx context.Context, req *channelp } else if pageSize != 0 { req.PageSize = int32(pageSize) } - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.cloudChannelClient.ListProducts(ctx, req, settings.GRPC...) - return err - }, opts...) + baseUrl, err := url.Parse(c.endpoint) if err != nil { return nil, "", err } + baseUrl.Path += fmt.Sprintf("/v1/products") + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("account", fmt.Sprintf("%v", req.GetAccount())) + if req.GetLanguageCode() != "" { + params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } it.Response = resp return resp.GetProducts(), resp.GetNextPageToken(), nil } + fetch := func(pageSize int, pageToken string) (string, error) { items, nextPageToken, err := it.InternalFetch(pageSize, pageToken) if err != nil { @@ -3039,13 +7319,15 @@ func (c *cloudChannelGRPCClient) ListProducts(ctx context.Context, req *channelp return it } -func (c *cloudChannelGRPCClient) ListSkus(ctx context.Context, req *channelpb.ListSkusRequest, opts ...gax.CallOption) *SkuIterator { - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) - - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).ListSkus[0:len((*c.CallOptions).ListSkus):len((*c.CallOptions).ListSkus)], opts...) +// ListSkus lists the SKUs for a product the reseller is authorized to sell. +// +// Possible error codes: +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +func (c *cloudChannelRESTClient) ListSkus(ctx context.Context, req *channelpb.ListSkusRequest, opts ...gax.CallOption) *SkuIterator { it := &SkuIterator{} req = proto.Clone(req).(*channelpb.ListSkusRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} it.InternalFetch = func(pageSize int, pageToken string) ([]*channelpb.Sku, string, error) { resp := &channelpb.ListSkusResponse{} if pageToken != "" { @@ -3056,18 +7338,67 @@ func (c *cloudChannelGRPCClient) ListSkus(ctx context.Context, req *channelpb.Li } else if pageSize != 0 { req.PageSize = int32(pageSize) } - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.cloudChannelClient.ListSkus(ctx, req, settings.GRPC...) - return err - }, opts...) + baseUrl, err := url.Parse(c.endpoint) if err != nil { return nil, "", err } + baseUrl.Path += fmt.Sprintf("/v1/%v/skus", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("account", fmt.Sprintf("%v", req.GetAccount())) + if req.GetLanguageCode() != "" { + params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } it.Response = resp return resp.GetSkus(), resp.GetNextPageToken(), nil } + fetch := func(pageSize int, pageToken string) (string, error) { items, nextPageToken, err := it.InternalFetch(pageSize, pageToken) if err != nil { @@ -3084,13 +7415,15 @@ func (c *cloudChannelGRPCClient) ListSkus(ctx context.Context, req *channelpb.Li return it } -func (c *cloudChannelGRPCClient) ListOffers(ctx context.Context, req *channelpb.ListOffersRequest, opts ...gax.CallOption) *OfferIterator { - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) - - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).ListOffers[0:len((*c.CallOptions).ListOffers):len((*c.CallOptions).ListOffers)], opts...) +// ListOffers lists the Offers the reseller can sell. +// +// Possible error codes: +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +func (c *cloudChannelRESTClient) ListOffers(ctx context.Context, req *channelpb.ListOffersRequest, opts ...gax.CallOption) *OfferIterator { it := &OfferIterator{} req = proto.Clone(req).(*channelpb.ListOffersRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} it.InternalFetch = func(pageSize int, pageToken string) ([]*channelpb.Offer, string, error) { resp := &channelpb.ListOffersResponse{} if pageToken != "" { @@ -3101,18 +7434,69 @@ func (c *cloudChannelGRPCClient) ListOffers(ctx context.Context, req *channelpb. } else if pageSize != 0 { req.PageSize = int32(pageSize) } - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.cloudChannelClient.ListOffers(ctx, req, settings.GRPC...) - return err - }, opts...) + baseUrl, err := url.Parse(c.endpoint) if err != nil { return nil, "", err } + baseUrl.Path += fmt.Sprintf("/v1/%v/offers", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetLanguageCode() != "" { + params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } it.Response = resp return resp.GetOffers(), resp.GetNextPageToken(), nil } + fetch := func(pageSize int, pageToken string) (string, error) { items, nextPageToken, err := it.InternalFetch(pageSize, pageToken) if err != nil { @@ -3129,13 +7513,21 @@ func (c *cloudChannelGRPCClient) ListOffers(ctx context.Context, req *channelpb. return it } -func (c *cloudChannelGRPCClient) ListPurchasableSkus(ctx context.Context, req *channelpb.ListPurchasableSkusRequest, opts ...gax.CallOption) *PurchasableSkuIterator { - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "customer", url.QueryEscape(req.GetCustomer()))) - - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).ListPurchasableSkus[0:len((*c.CallOptions).ListPurchasableSkus):len((*c.CallOptions).ListPurchasableSkus)], opts...) +// ListPurchasableSkus lists the following: +// +// SKUs that you can purchase for a customer +// +// SKUs that you can upgrade or downgrade for an entitlement. +// +// Possible error codes: +// +// PERMISSION_DENIED: The customer doesn’t belong to the reseller. +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +func (c *cloudChannelRESTClient) ListPurchasableSkus(ctx context.Context, req *channelpb.ListPurchasableSkusRequest, opts ...gax.CallOption) *PurchasableSkuIterator { it := &PurchasableSkuIterator{} req = proto.Clone(req).(*channelpb.ListPurchasableSkusRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} it.InternalFetch = func(pageSize int, pageToken string) ([]*channelpb.PurchasableSku, string, error) { resp := &channelpb.ListPurchasableSkusResponse{} if pageToken != "" { @@ -3146,18 +7538,69 @@ func (c *cloudChannelGRPCClient) ListPurchasableSkus(ctx context.Context, req *c } else if pageSize != 0 { req.PageSize = int32(pageSize) } - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.cloudChannelClient.ListPurchasableSkus(ctx, req, settings.GRPC...) - return err - }, opts...) + baseUrl, err := url.Parse(c.endpoint) if err != nil { return nil, "", err } + baseUrl.Path += fmt.Sprintf("/v1/%v:listPurchasableSkus", req.GetCustomer()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("changeOfferPurchase.changeType", fmt.Sprintf("%v", req.GetChangeOfferPurchase().GetChangeType())) + params.Add("changeOfferPurchase.entitlement", fmt.Sprintf("%v", req.GetChangeOfferPurchase().GetEntitlement())) + params.Add("createEntitlementPurchase.product", fmt.Sprintf("%v", req.GetCreateEntitlementPurchase().GetProduct())) + if req.GetLanguageCode() != "" { + params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } it.Response = resp return resp.GetPurchasableSkus(), resp.GetNextPageToken(), nil } + fetch := func(pageSize int, pageToken string) (string, error) { items, nextPageToken, err := it.InternalFetch(pageSize, pageToken) if err != nil { @@ -3174,13 +7617,21 @@ func (c *cloudChannelGRPCClient) ListPurchasableSkus(ctx context.Context, req *c return it } -func (c *cloudChannelGRPCClient) ListPurchasableOffers(ctx context.Context, req *channelpb.ListPurchasableOffersRequest, opts ...gax.CallOption) *PurchasableOfferIterator { - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "customer", url.QueryEscape(req.GetCustomer()))) - - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).ListPurchasableOffers[0:len((*c.CallOptions).ListPurchasableOffers):len((*c.CallOptions).ListPurchasableOffers)], opts...) +// ListPurchasableOffers lists the following: +// +// Offers that you can purchase for a customer. +// +// Offers that you can change for an entitlement. +// +// Possible error codes: +// +// PERMISSION_DENIED: The customer doesn’t belong to the reseller +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +func (c *cloudChannelRESTClient) ListPurchasableOffers(ctx context.Context, req *channelpb.ListPurchasableOffersRequest, opts ...gax.CallOption) *PurchasableOfferIterator { it := &PurchasableOfferIterator{} req = proto.Clone(req).(*channelpb.ListPurchasableOffersRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} it.InternalFetch = func(pageSize int, pageToken string) ([]*channelpb.PurchasableOffer, string, error) { resp := &channelpb.ListPurchasableOffersResponse{} if pageToken != "" { @@ -3191,18 +7642,71 @@ func (c *cloudChannelGRPCClient) ListPurchasableOffers(ctx context.Context, req } else if pageSize != 0 { req.PageSize = int32(pageSize) } - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.cloudChannelClient.ListPurchasableOffers(ctx, req, settings.GRPC...) - return err - }, opts...) + baseUrl, err := url.Parse(c.endpoint) if err != nil { return nil, "", err } + baseUrl.Path += fmt.Sprintf("/v1/%v:listPurchasableOffers", req.GetCustomer()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("changeOfferPurchase.entitlement", fmt.Sprintf("%v", req.GetChangeOfferPurchase().GetEntitlement())) + if req.GetChangeOfferPurchase().GetNewSku() != "" { + params.Add("changeOfferPurchase.newSku", fmt.Sprintf("%v", req.GetChangeOfferPurchase().GetNewSku())) + } + params.Add("createEntitlementPurchase.sku", fmt.Sprintf("%v", req.GetCreateEntitlementPurchase().GetSku())) + if req.GetLanguageCode() != "" { + params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } it.Response = resp return resp.GetPurchasableOffers(), resp.GetNextPageToken(), nil } + fetch := func(pageSize int, pageToken string) (string, error) { items, nextPageToken, err := it.InternalFetch(pageSize, pageToken) if err != nil { @@ -3219,57 +7723,202 @@ func (c *cloudChannelGRPCClient) ListPurchasableOffers(ctx context.Context, req return it } -func (c *cloudChannelGRPCClient) RegisterSubscriber(ctx context.Context, req *channelpb.RegisterSubscriberRequest, opts ...gax.CallOption) (*channelpb.RegisterSubscriberResponse, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx +// RegisterSubscriber registers a service account with subscriber privileges on the Cloud Pub/Sub +// topic for this Channel Services account. After you create a +// subscriber, you get the events through SubscriberEvent +// +// Possible error codes: +// +// PERMISSION_DENIED: The reseller account making the request and the +// provided reseller account are different, or the impersonated user +// is not a super admin. +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +// +// INTERNAL: Any non-user error related to a technical issue in the +// backend. Contact Cloud Channel support. +// +// UNKNOWN: Any non-user error related to a technical issue in the backend. +// Contact Cloud Channel support. +// +// Return value: +// The topic name with the registered service email address. +func (c *cloudChannelRESTClient) RegisterSubscriber(ctx context.Context, req *channelpb.RegisterSubscriberRequest, opts ...gax.CallOption) (*channelpb.RegisterSubscriberResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:register", req.GetAccount()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "account", url.QueryEscape(req.GetAccount()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).RegisterSubscriber[0:len((*c.CallOptions).RegisterSubscriber):len((*c.CallOptions).RegisterSubscriber)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &channelpb.RegisterSubscriberResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UnregisterSubscriber unregisters a service account with subscriber privileges on the Cloud +// Pub/Sub topic created for this Channel Services account. If there are no +// service accounts left with subscriber privileges, this deletes the topic. +// You can call ListSubscribers to check for these accounts. +// +// Possible error codes: +// +// PERMISSION_DENIED: The reseller account making the request and the +// provided reseller account are different, or the impersonated user +// is not a super admin. +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +// +// NOT_FOUND: The topic resource doesn’t exist. +// +// INTERNAL: Any non-user error related to a technical issue in the +// backend. Contact Cloud Channel support. +// +// UNKNOWN: Any non-user error related to a technical issue in the backend. +// Contact Cloud Channel support. +// +// Return value: +// The topic name that unregistered the service email address. +// Returns a success response if the service email address wasn’t registered +// with the topic. +func (c *cloudChannelRESTClient) UnregisterSubscriber(ctx context.Context, req *channelpb.UnregisterSubscriberRequest, opts ...gax.CallOption) (*channelpb.UnregisterSubscriberResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err } - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "account", url.QueryEscape(req.GetAccount()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).RegisterSubscriber[0:len((*c.CallOptions).RegisterSubscriber):len((*c.CallOptions).RegisterSubscriber)], opts...) - var resp *channelpb.RegisterSubscriberResponse - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.cloudChannelClient.RegisterSubscriber(ctx, req, settings.GRPC...) - return err - }, opts...) + baseUrl, err := url.Parse(c.endpoint) if err != nil { return nil, err } - return resp, nil -} + baseUrl.Path += fmt.Sprintf("/v1/%v:unregister", req.GetAccount()) -func (c *cloudChannelGRPCClient) UnregisterSubscriber(ctx context.Context, req *channelpb.UnregisterSubscriberRequest, opts ...gax.CallOption) (*channelpb.UnregisterSubscriberResponse, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx - } + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "account", url.QueryEscape(req.GetAccount()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) opts = append((*c.CallOptions).UnregisterSubscriber[0:len((*c.CallOptions).UnregisterSubscriber):len((*c.CallOptions).UnregisterSubscriber)], opts...) - var resp *channelpb.UnregisterSubscriberResponse - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.cloudChannelClient.UnregisterSubscriber(ctx, req, settings.GRPC...) - return err + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &channelpb.UnregisterSubscriberResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil }, opts...) - if err != nil { - return nil, err + if e != nil { + return nil, e } return resp, nil } -func (c *cloudChannelGRPCClient) ListSubscribers(ctx context.Context, req *channelpb.ListSubscribersRequest, opts ...gax.CallOption) *StringIterator { - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "account", url.QueryEscape(req.GetAccount()))) - - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).ListSubscribers[0:len((*c.CallOptions).ListSubscribers):len((*c.CallOptions).ListSubscribers)], opts...) +// ListSubscribers lists service accounts with subscriber privileges on the Cloud Pub/Sub +// topic created for this Channel Services account. +// +// Possible error codes: +// +// PERMISSION_DENIED: The reseller account making the request and the +// provided reseller account are different, or the impersonated user +// is not a super admin. +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +// +// NOT_FOUND: The topic resource doesn’t exist. +// +// INTERNAL: Any non-user error related to a technical issue in the +// backend. Contact Cloud Channel support. +// +// UNKNOWN: Any non-user error related to a technical issue in the backend. +// Contact Cloud Channel support. +// +// Return value: +// A list of service email addresses. +func (c *cloudChannelRESTClient) ListSubscribers(ctx context.Context, req *channelpb.ListSubscribersRequest, opts ...gax.CallOption) *StringIterator { it := &StringIterator{} req = proto.Clone(req).(*channelpb.ListSubscribersRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} it.InternalFetch = func(pageSize int, pageToken string) ([]string, string, error) { resp := &channelpb.ListSubscribersResponse{} if pageToken != "" { @@ -3280,18 +7929,63 @@ func (c *cloudChannelGRPCClient) ListSubscribers(ctx context.Context, req *chann } else if pageSize != 0 { req.PageSize = int32(pageSize) } - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.cloudChannelClient.ListSubscribers(ctx, req, settings.GRPC...) - return err - }, opts...) + baseUrl, err := url.Parse(c.endpoint) if err != nil { return nil, "", err } + baseUrl.Path += fmt.Sprintf("/v1/%v:listSubscribers", req.GetAccount()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } it.Response = resp return resp.GetServiceAccounts(), resp.GetNextPageToken(), nil } + fetch := func(pageSize int, pageToken string) (string, error) { items, nextPageToken, err := it.InternalFetch(pageSize, pageToken) if err != nil { @@ -3308,56 +8002,155 @@ func (c *cloudChannelGRPCClient) ListSubscribers(ctx context.Context, req *chann return it } -func (c *cloudChannelGRPCClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *cloudChannelRESTClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return err + } - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - 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...) + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) }, opts...) - return err } -func (c *cloudChannelGRPCClient) DeleteOperation(ctx context.Context, req *longrunningpb.DeleteOperationRequest, opts ...gax.CallOption) error { +// DeleteOperation is a utility method from google.longrunning.Operations. +func (c *cloudChannelRESTClient) DeleteOperation(ctx context.Context, req *longrunningpb.DeleteOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - 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 + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) }, opts...) - return err } -func (c *cloudChannelGRPCClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { +// GetOperation is a utility method from google.longrunning.Operations. +func (c *cloudChannelRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) 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 + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil }, opts...) - if err != nil { - return nil, err + if e != nil { + return nil, e } return resp, nil } -func (c *cloudChannelGRPCClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) - - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).ListOperations[0:len((*c.CallOptions).ListOperations):len((*c.CallOptions).ListOperations)], opts...) +// ListOperations is a utility method from google.longrunning.Operations. +func (c *cloudChannelRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { it := &OperationIterator{} req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { resp := &longrunningpb.ListOperationsResponse{} if pageToken != "" { @@ -3368,18 +8161,66 @@ func (c *cloudChannelGRPCClient) ListOperations(ctx context.Context, req *longru } else if pageSize != 0 { 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...) + baseUrl, err := url.Parse(c.endpoint) if err != nil { return nil, "", err } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } it.Response = resp return resp.GetOperations(), resp.GetNextPageToken(), nil } + fetch := func(pageSize int, pageToken string) (string, error) { items, nextPageToken, err := it.InternalFetch(pageSize, pageToken) if err != nil { @@ -3398,7 +8239,8 @@ func (c *cloudChannelGRPCClient) ListOperations(ctx context.Context, req *longru // ActivateEntitlementOperation manages a long-running operation from ActivateEntitlement. type ActivateEntitlementOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // ActivateEntitlementOperation returns a new ActivateEntitlementOperation from a given name. @@ -3409,10 +8251,21 @@ func (c *cloudChannelGRPCClient) ActivateEntitlementOperation(name string) *Acti } } +// ActivateEntitlementOperation returns a new ActivateEntitlementOperation from a given name. +// The name must be that of a previously created ActivateEntitlementOperation, possibly from a different process. +func (c *cloudChannelRESTClient) ActivateEntitlementOperation(name string) *ActivateEntitlementOperation { + override := fmt.Sprintf("/v1/%s", name) + return &ActivateEntitlementOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *ActivateEntitlementOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*channelpb.Entitlement, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp channelpb.Entitlement if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -3430,6 +8283,7 @@ func (op *ActivateEntitlementOperation) Wait(ctx context.Context, opts ...gax.Ca // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *ActivateEntitlementOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*channelpb.Entitlement, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp channelpb.Entitlement if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -3467,7 +8321,8 @@ func (op *ActivateEntitlementOperation) Name() string { // CancelEntitlementOperation manages a long-running operation from CancelEntitlement. type CancelEntitlementOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CancelEntitlementOperation returns a new CancelEntitlementOperation from a given name. @@ -3478,10 +8333,21 @@ func (c *cloudChannelGRPCClient) CancelEntitlementOperation(name string) *Cancel } } +// CancelEntitlementOperation returns a new CancelEntitlementOperation from a given name. +// The name must be that of a previously created CancelEntitlementOperation, possibly from a different process. +func (c *cloudChannelRESTClient) CancelEntitlementOperation(name string) *CancelEntitlementOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CancelEntitlementOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CancelEntitlementOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -3495,6 +8361,7 @@ func (op *CancelEntitlementOperation) Wait(ctx context.Context, opts ...gax.Call // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CancelEntitlementOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -3525,7 +8392,8 @@ func (op *CancelEntitlementOperation) Name() string { // ChangeOfferOperation manages a long-running operation from ChangeOffer. type ChangeOfferOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // ChangeOfferOperation returns a new ChangeOfferOperation from a given name. @@ -3536,10 +8404,21 @@ func (c *cloudChannelGRPCClient) ChangeOfferOperation(name string) *ChangeOfferO } } +// ChangeOfferOperation returns a new ChangeOfferOperation from a given name. +// The name must be that of a previously created ChangeOfferOperation, possibly from a different process. +func (c *cloudChannelRESTClient) ChangeOfferOperation(name string) *ChangeOfferOperation { + override := fmt.Sprintf("/v1/%s", name) + return &ChangeOfferOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *ChangeOfferOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*channelpb.Entitlement, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp channelpb.Entitlement if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -3557,6 +8436,7 @@ func (op *ChangeOfferOperation) Wait(ctx context.Context, opts ...gax.CallOption // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *ChangeOfferOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*channelpb.Entitlement, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp channelpb.Entitlement if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -3594,7 +8474,8 @@ func (op *ChangeOfferOperation) Name() string { // ChangeParametersOperation manages a long-running operation from ChangeParameters. type ChangeParametersOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // ChangeParametersOperation returns a new ChangeParametersOperation from a given name. @@ -3605,10 +8486,21 @@ func (c *cloudChannelGRPCClient) ChangeParametersOperation(name string) *ChangeP } } +// ChangeParametersOperation returns a new ChangeParametersOperation from a given name. +// The name must be that of a previously created ChangeParametersOperation, possibly from a different process. +func (c *cloudChannelRESTClient) ChangeParametersOperation(name string) *ChangeParametersOperation { + override := fmt.Sprintf("/v1/%s", name) + return &ChangeParametersOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *ChangeParametersOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*channelpb.Entitlement, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp channelpb.Entitlement if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -3626,6 +8518,7 @@ func (op *ChangeParametersOperation) Wait(ctx context.Context, opts ...gax.CallO // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *ChangeParametersOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*channelpb.Entitlement, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp channelpb.Entitlement if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -3663,7 +8556,8 @@ func (op *ChangeParametersOperation) Name() string { // ChangeRenewalSettingsOperation manages a long-running operation from ChangeRenewalSettings. type ChangeRenewalSettingsOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // ChangeRenewalSettingsOperation returns a new ChangeRenewalSettingsOperation from a given name. @@ -3674,10 +8568,21 @@ func (c *cloudChannelGRPCClient) ChangeRenewalSettingsOperation(name string) *Ch } } +// ChangeRenewalSettingsOperation returns a new ChangeRenewalSettingsOperation from a given name. +// The name must be that of a previously created ChangeRenewalSettingsOperation, possibly from a different process. +func (c *cloudChannelRESTClient) ChangeRenewalSettingsOperation(name string) *ChangeRenewalSettingsOperation { + override := fmt.Sprintf("/v1/%s", name) + return &ChangeRenewalSettingsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *ChangeRenewalSettingsOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*channelpb.Entitlement, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp channelpb.Entitlement if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -3695,6 +8600,7 @@ func (op *ChangeRenewalSettingsOperation) Wait(ctx context.Context, opts ...gax. // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *ChangeRenewalSettingsOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*channelpb.Entitlement, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp channelpb.Entitlement if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -3732,7 +8638,8 @@ func (op *ChangeRenewalSettingsOperation) Name() string { // CreateEntitlementOperation manages a long-running operation from CreateEntitlement. type CreateEntitlementOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateEntitlementOperation returns a new CreateEntitlementOperation from a given name. @@ -3743,10 +8650,21 @@ func (c *cloudChannelGRPCClient) CreateEntitlementOperation(name string) *Create } } +// CreateEntitlementOperation returns a new CreateEntitlementOperation from a given name. +// The name must be that of a previously created CreateEntitlementOperation, possibly from a different process. +func (c *cloudChannelRESTClient) CreateEntitlementOperation(name string) *CreateEntitlementOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateEntitlementOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateEntitlementOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*channelpb.Entitlement, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp channelpb.Entitlement if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -3764,6 +8682,7 @@ func (op *CreateEntitlementOperation) Wait(ctx context.Context, opts ...gax.Call // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateEntitlementOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*channelpb.Entitlement, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp channelpb.Entitlement if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -3801,7 +8720,8 @@ func (op *CreateEntitlementOperation) Name() string { // ProvisionCloudIdentityOperation manages a long-running operation from ProvisionCloudIdentity. type ProvisionCloudIdentityOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // ProvisionCloudIdentityOperation returns a new ProvisionCloudIdentityOperation from a given name. @@ -3812,10 +8732,21 @@ func (c *cloudChannelGRPCClient) ProvisionCloudIdentityOperation(name string) *P } } +// ProvisionCloudIdentityOperation returns a new ProvisionCloudIdentityOperation from a given name. +// The name must be that of a previously created ProvisionCloudIdentityOperation, possibly from a different process. +func (c *cloudChannelRESTClient) ProvisionCloudIdentityOperation(name string) *ProvisionCloudIdentityOperation { + override := fmt.Sprintf("/v1/%s", name) + return &ProvisionCloudIdentityOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *ProvisionCloudIdentityOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*channelpb.Customer, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp channelpb.Customer if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -3833,6 +8764,7 @@ func (op *ProvisionCloudIdentityOperation) Wait(ctx context.Context, opts ...gax // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *ProvisionCloudIdentityOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*channelpb.Customer, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp channelpb.Customer if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -3870,7 +8802,8 @@ func (op *ProvisionCloudIdentityOperation) Name() string { // StartPaidServiceOperation manages a long-running operation from StartPaidService. type StartPaidServiceOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // StartPaidServiceOperation returns a new StartPaidServiceOperation from a given name. @@ -3881,10 +8814,21 @@ func (c *cloudChannelGRPCClient) StartPaidServiceOperation(name string) *StartPa } } +// StartPaidServiceOperation returns a new StartPaidServiceOperation from a given name. +// The name must be that of a previously created StartPaidServiceOperation, possibly from a different process. +func (c *cloudChannelRESTClient) StartPaidServiceOperation(name string) *StartPaidServiceOperation { + override := fmt.Sprintf("/v1/%s", name) + return &StartPaidServiceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *StartPaidServiceOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*channelpb.Entitlement, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp channelpb.Entitlement if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -3902,6 +8846,7 @@ func (op *StartPaidServiceOperation) Wait(ctx context.Context, opts ...gax.CallO // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *StartPaidServiceOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*channelpb.Entitlement, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp channelpb.Entitlement if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -3939,7 +8884,8 @@ func (op *StartPaidServiceOperation) Name() string { // SuspendEntitlementOperation manages a long-running operation from SuspendEntitlement. type SuspendEntitlementOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // SuspendEntitlementOperation returns a new SuspendEntitlementOperation from a given name. @@ -3950,10 +8896,21 @@ func (c *cloudChannelGRPCClient) SuspendEntitlementOperation(name string) *Suspe } } +// SuspendEntitlementOperation returns a new SuspendEntitlementOperation from a given name. +// The name must be that of a previously created SuspendEntitlementOperation, possibly from a different process. +func (c *cloudChannelRESTClient) SuspendEntitlementOperation(name string) *SuspendEntitlementOperation { + override := fmt.Sprintf("/v1/%s", name) + return &SuspendEntitlementOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *SuspendEntitlementOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*channelpb.Entitlement, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp channelpb.Entitlement if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -3971,6 +8928,7 @@ func (op *SuspendEntitlementOperation) Wait(ctx context.Context, opts ...gax.Cal // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *SuspendEntitlementOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*channelpb.Entitlement, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp channelpb.Entitlement if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -4008,7 +8966,8 @@ func (op *SuspendEntitlementOperation) Name() string { // TransferEntitlementsOperation manages a long-running operation from TransferEntitlements. type TransferEntitlementsOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // TransferEntitlementsOperation returns a new TransferEntitlementsOperation from a given name. @@ -4019,10 +8978,21 @@ func (c *cloudChannelGRPCClient) TransferEntitlementsOperation(name string) *Tra } } +// TransferEntitlementsOperation returns a new TransferEntitlementsOperation from a given name. +// The name must be that of a previously created TransferEntitlementsOperation, possibly from a different process. +func (c *cloudChannelRESTClient) TransferEntitlementsOperation(name string) *TransferEntitlementsOperation { + override := fmt.Sprintf("/v1/%s", name) + return &TransferEntitlementsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *TransferEntitlementsOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*channelpb.TransferEntitlementsResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp channelpb.TransferEntitlementsResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -4040,6 +9010,7 @@ func (op *TransferEntitlementsOperation) Wait(ctx context.Context, opts ...gax.C // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *TransferEntitlementsOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*channelpb.TransferEntitlementsResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp channelpb.TransferEntitlementsResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -4077,7 +9048,8 @@ func (op *TransferEntitlementsOperation) Name() string { // TransferEntitlementsToGoogleOperation manages a long-running operation from TransferEntitlementsToGoogle. type TransferEntitlementsToGoogleOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // TransferEntitlementsToGoogleOperation returns a new TransferEntitlementsToGoogleOperation from a given name. @@ -4088,10 +9060,21 @@ func (c *cloudChannelGRPCClient) TransferEntitlementsToGoogleOperation(name stri } } +// TransferEntitlementsToGoogleOperation returns a new TransferEntitlementsToGoogleOperation from a given name. +// The name must be that of a previously created TransferEntitlementsToGoogleOperation, possibly from a different process. +func (c *cloudChannelRESTClient) TransferEntitlementsToGoogleOperation(name string) *TransferEntitlementsToGoogleOperation { + override := fmt.Sprintf("/v1/%s", name) + return &TransferEntitlementsToGoogleOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *TransferEntitlementsToGoogleOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -4105,6 +9088,7 @@ func (op *TransferEntitlementsToGoogleOperation) Wait(ctx context.Context, opts // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *TransferEntitlementsToGoogleOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } diff --git a/channel/apiv1/cloud_channel_client_example_test.go b/channel/apiv1/cloud_channel_client_example_test.go index c69fe9e819fb..90bde2e3fe66 100644 --- a/channel/apiv1/cloud_channel_client_example_test.go +++ b/channel/apiv1/cloud_channel_client_example_test.go @@ -42,6 +42,23 @@ func ExampleNewCloudChannelClient() { _ = c } +func ExampleNewCloudChannelRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := channel.NewCloudChannelRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleCloudChannelClient_ListCustomers() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/channel/apiv1/cloud_channel_reports_client.go b/channel/apiv1/cloud_channel_reports_client.go index d35fe6da2e87..ffc03ac466de 100644 --- a/channel/apiv1/cloud_channel_reports_client.go +++ b/channel/apiv1/cloud_channel_reports_client.go @@ -17,9 +17,12 @@ package channel import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,13 +30,16 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -74,6 +80,18 @@ func defaultCloudChannelReportsCallOptions() *CloudChannelReportsCallOptions { } } +func defaultCloudChannelReportsRESTCallOptions() *CloudChannelReportsCallOptions { + return &CloudChannelReportsCallOptions{ + RunReportJob: []gax.CallOption{}, + FetchReportResults: []gax.CallOption{}, + ListReports: []gax.CallOption{}, + CancelOperation: []gax.CallOption{}, + DeleteOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalCloudChannelReportsClient is an interface that defines the methods available from Cloud Channel API. type internalCloudChannelReportsClient interface { Close() error @@ -304,6 +322,92 @@ func (c *cloudChannelReportsGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type cloudChannelReportsRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing CloudChannelReportsClient + CallOptions **CloudChannelReportsCallOptions +} + +// NewCloudChannelReportsRESTClient creates a new cloud channel reports service rest client. +// +// CloudChannelReportsService lets Google Cloud resellers and +// distributors retrieve and combine a variety of data in Cloud Channel for +// multiple products (Google Cloud Platform (GCP), Google Voice, and +// Google Workspace.) +func NewCloudChannelReportsRESTClient(ctx context.Context, opts ...option.ClientOption) (*CloudChannelReportsClient, error) { + clientOpts := append(defaultCloudChannelReportsRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultCloudChannelReportsRESTCallOptions() + c := &cloudChannelReportsRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &CloudChannelReportsClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultCloudChannelReportsRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://cloudchannel.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://cloudchannel.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://cloudchannel.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *cloudChannelReportsRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *cloudChannelReportsRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *cloudChannelReportsRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *cloudChannelReportsGRPCClient) RunReportJob(ctx context.Context, req *channelpb.RunReportJobRequest, opts ...gax.CallOption) (*RunReportJobOperation, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -501,9 +605,520 @@ func (c *cloudChannelReportsGRPCClient) ListOperations(ctx context.Context, req return it } +// RunReportJob begins generation of data for a given report. The report +// identifier is a UID (for example, 613bf59q). +// +// Possible error codes: +// +// PERMISSION_DENIED: The user doesn’t have access to this report. +// +// INVALID_ARGUMENT: Required request parameters are missing +// or invalid. +// +// NOT_FOUND: The report identifier was not found. +// +// INTERNAL: Any non-user error related to a technical issue +// in the backend. Contact Cloud Channel support. +// +// UNKNOWN: Any non-user error related to a technical issue +// in the backend. Contact Cloud Channel support. +// +// Return value: +// The ID of a long-running operation. +// +// To get the results of the operation, call the GetOperation method of +// CloudChannelOperationsService. The Operation metadata contains an +// instance of OperationMetadata. +// +// To get the results of report generation, call +// CloudChannelReportsService.FetchReportResults with the +// RunReportJobResponse.report_job. +func (c *cloudChannelReportsRESTClient) RunReportJob(ctx context.Context, req *channelpb.RunReportJobRequest, opts ...gax.CallOption) (*RunReportJobOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:run", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &RunReportJobOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// FetchReportResults retrieves data generated by CloudChannelReportsService.RunReportJob. +func (c *cloudChannelReportsRESTClient) FetchReportResults(ctx context.Context, req *channelpb.FetchReportResultsRequest, opts ...gax.CallOption) *RowIterator { + it := &RowIterator{} + req = proto.Clone(req).(*channelpb.FetchReportResultsRequest) + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*channelpb.Row, string, error) { + resp := &channelpb.FetchReportResultsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, "", err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:fetchReportResults", req.GetReportJob()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetRows(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// ListReports lists the reports that RunReportJob can run. These reports include an ID, +// a description, and the list of columns that will be in the result. +func (c *cloudChannelReportsRESTClient) ListReports(ctx context.Context, req *channelpb.ListReportsRequest, opts ...gax.CallOption) *ReportIterator { + it := &ReportIterator{} + req = proto.Clone(req).(*channelpb.ListReportsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*channelpb.Report, string, error) { + resp := &channelpb.ListReportsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/reports", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetLanguageCode() != "" { + params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetReports(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *cloudChannelReportsRESTClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// DeleteOperation is a utility method from google.longrunning.Operations. +func (c *cloudChannelReportsRESTClient) DeleteOperation(ctx context.Context, req *longrunningpb.DeleteOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *cloudChannelReportsRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *cloudChannelReportsRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + // RunReportJobOperation manages a long-running operation from RunReportJob. type RunReportJobOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // RunReportJobOperation returns a new RunReportJobOperation from a given name. @@ -514,10 +1129,21 @@ func (c *cloudChannelReportsGRPCClient) RunReportJobOperation(name string) *RunR } } +// RunReportJobOperation returns a new RunReportJobOperation from a given name. +// The name must be that of a previously created RunReportJobOperation, possibly from a different process. +func (c *cloudChannelReportsRESTClient) RunReportJobOperation(name string) *RunReportJobOperation { + override := fmt.Sprintf("/v1/%s", name) + return &RunReportJobOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *RunReportJobOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*channelpb.RunReportJobResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp channelpb.RunReportJobResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -535,6 +1161,7 @@ func (op *RunReportJobOperation) Wait(ctx context.Context, opts ...gax.CallOptio // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *RunReportJobOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*channelpb.RunReportJobResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp channelpb.RunReportJobResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/channel/apiv1/cloud_channel_reports_client_example_test.go b/channel/apiv1/cloud_channel_reports_client_example_test.go index 653671ae7f3a..b4c2208ebcb1 100644 --- a/channel/apiv1/cloud_channel_reports_client_example_test.go +++ b/channel/apiv1/cloud_channel_reports_client_example_test.go @@ -42,6 +42,23 @@ func ExampleNewCloudChannelReportsClient() { _ = c } +func ExampleNewCloudChannelReportsRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := channel.NewCloudChannelReportsRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleCloudChannelReportsClient_RunReportJob() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/channel/apiv1/doc.go b/channel/apiv1/doc.go index 078903b08d6e..6ee576a6f2f3 100644 --- a/channel/apiv1/doc.go +++ b/channel/apiv1/doc.go @@ -87,6 +87,8 @@ package channel // import "cloud.google.com/go/channel/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -176,3 +178,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/channel/apiv1/gapic_metadata.json b/channel/apiv1/gapic_metadata.json index 51f96b868f3b..988007cf7967 100644 --- a/channel/apiv1/gapic_metadata.json +++ b/channel/apiv1/gapic_metadata.json @@ -46,6 +46,46 @@ ] } } + }, + "rest": { + "libraryClient": "CloudChannelReportsClient", + "rpcs": { + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "DeleteOperation": { + "methods": [ + "DeleteOperation" + ] + }, + "FetchReportResults": { + "methods": [ + "FetchReportResults" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "ListReports": { + "methods": [ + "ListReports" + ] + }, + "RunReportJob": { + "methods": [ + "RunReportJob" + ] + } + } } } }, @@ -300,6 +340,256 @@ ] } } + }, + "rest": { + "libraryClient": "CloudChannelClient", + "rpcs": { + "ActivateEntitlement": { + "methods": [ + "ActivateEntitlement" + ] + }, + "CancelEntitlement": { + "methods": [ + "CancelEntitlement" + ] + }, + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "ChangeOffer": { + "methods": [ + "ChangeOffer" + ] + }, + "ChangeParameters": { + "methods": [ + "ChangeParameters" + ] + }, + "ChangeRenewalSettings": { + "methods": [ + "ChangeRenewalSettings" + ] + }, + "CheckCloudIdentityAccountsExist": { + "methods": [ + "CheckCloudIdentityAccountsExist" + ] + }, + "CreateChannelPartnerLink": { + "methods": [ + "CreateChannelPartnerLink" + ] + }, + "CreateChannelPartnerRepricingConfig": { + "methods": [ + "CreateChannelPartnerRepricingConfig" + ] + }, + "CreateCustomer": { + "methods": [ + "CreateCustomer" + ] + }, + "CreateCustomerRepricingConfig": { + "methods": [ + "CreateCustomerRepricingConfig" + ] + }, + "CreateEntitlement": { + "methods": [ + "CreateEntitlement" + ] + }, + "DeleteChannelPartnerRepricingConfig": { + "methods": [ + "DeleteChannelPartnerRepricingConfig" + ] + }, + "DeleteCustomer": { + "methods": [ + "DeleteCustomer" + ] + }, + "DeleteCustomerRepricingConfig": { + "methods": [ + "DeleteCustomerRepricingConfig" + ] + }, + "DeleteOperation": { + "methods": [ + "DeleteOperation" + ] + }, + "GetChannelPartnerLink": { + "methods": [ + "GetChannelPartnerLink" + ] + }, + "GetChannelPartnerRepricingConfig": { + "methods": [ + "GetChannelPartnerRepricingConfig" + ] + }, + "GetCustomer": { + "methods": [ + "GetCustomer" + ] + }, + "GetCustomerRepricingConfig": { + "methods": [ + "GetCustomerRepricingConfig" + ] + }, + "GetEntitlement": { + "methods": [ + "GetEntitlement" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ImportCustomer": { + "methods": [ + "ImportCustomer" + ] + }, + "ListChannelPartnerLinks": { + "methods": [ + "ListChannelPartnerLinks" + ] + }, + "ListChannelPartnerRepricingConfigs": { + "methods": [ + "ListChannelPartnerRepricingConfigs" + ] + }, + "ListCustomerRepricingConfigs": { + "methods": [ + "ListCustomerRepricingConfigs" + ] + }, + "ListCustomers": { + "methods": [ + "ListCustomers" + ] + }, + "ListEntitlements": { + "methods": [ + "ListEntitlements" + ] + }, + "ListOffers": { + "methods": [ + "ListOffers" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "ListProducts": { + "methods": [ + "ListProducts" + ] + }, + "ListPurchasableOffers": { + "methods": [ + "ListPurchasableOffers" + ] + }, + "ListPurchasableSkus": { + "methods": [ + "ListPurchasableSkus" + ] + }, + "ListSkus": { + "methods": [ + "ListSkus" + ] + }, + "ListSubscribers": { + "methods": [ + "ListSubscribers" + ] + }, + "ListTransferableOffers": { + "methods": [ + "ListTransferableOffers" + ] + }, + "ListTransferableSkus": { + "methods": [ + "ListTransferableSkus" + ] + }, + "LookupOffer": { + "methods": [ + "LookupOffer" + ] + }, + "ProvisionCloudIdentity": { + "methods": [ + "ProvisionCloudIdentity" + ] + }, + "RegisterSubscriber": { + "methods": [ + "RegisterSubscriber" + ] + }, + "StartPaidService": { + "methods": [ + "StartPaidService" + ] + }, + "SuspendEntitlement": { + "methods": [ + "SuspendEntitlement" + ] + }, + "TransferEntitlements": { + "methods": [ + "TransferEntitlements" + ] + }, + "TransferEntitlementsToGoogle": { + "methods": [ + "TransferEntitlementsToGoogle" + ] + }, + "UnregisterSubscriber": { + "methods": [ + "UnregisterSubscriber" + ] + }, + "UpdateChannelPartnerLink": { + "methods": [ + "UpdateChannelPartnerLink" + ] + }, + "UpdateChannelPartnerRepricingConfig": { + "methods": [ + "UpdateChannelPartnerRepricingConfig" + ] + }, + "UpdateCustomer": { + "methods": [ + "UpdateCustomer" + ] + }, + "UpdateCustomerRepricingConfig": { + "methods": [ + "UpdateCustomerRepricingConfig" + ] + } + } } } } diff --git a/cloudbuild/apiv1/v2/cloud_build_client.go b/cloudbuild/apiv1/v2/cloud_build_client.go index 41c41ed15325..af5e1451c679 100644 --- a/cloudbuild/apiv1/v2/cloud_build_client.go +++ b/cloudbuild/apiv1/v2/cloud_build_client.go @@ -17,9 +17,12 @@ package cloudbuild import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,14 +30,17 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -174,6 +180,99 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + CreateBuild: []gax.CallOption{}, + GetBuild: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + ListBuilds: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + CancelBuild: []gax.CallOption{}, + RetryBuild: []gax.CallOption{}, + ApproveBuild: []gax.CallOption{}, + CreateBuildTrigger: []gax.CallOption{}, + GetBuildTrigger: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + ListBuildTriggers: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + DeleteBuildTrigger: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + UpdateBuildTrigger: []gax.CallOption{}, + RunBuildTrigger: []gax.CallOption{}, + ReceiveTriggerWebhook: []gax.CallOption{}, + CreateWorkerPool: []gax.CallOption{}, + GetWorkerPool: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + DeleteWorkerPool: []gax.CallOption{}, + UpdateWorkerPool: []gax.CallOption{}, + ListWorkerPools: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + } +} + // internalClient is an interface that defines the methods available from Cloud Build API. type internalClient interface { Close() error @@ -543,6 +642,96 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new cloud build rest client. +// +// Creates and manages builds on Google Cloud Platform. +// +// The main concept used by this API is a Build, which describes the location +// of the source to build, how to build the source, and where to store the +// built artifacts, if any. +// +// A user can list previously-requested builds or get builds by their ID to +// determine the status of the build. +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://cloudbuild.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://cloudbuild.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://cloudbuild.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) CreateBuild(ctx context.Context, req *cloudbuildpb.CreateBuildRequest, opts ...gax.CallOption) (*CreateBuildOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) @@ -1008,132 +1197,1479 @@ func (c *gRPCClient) ListWorkerPools(ctx context.Context, req *cloudbuildpb.List return it } -// ApproveBuildOperation manages a long-running operation from ApproveBuild. -type ApproveBuildOperation struct { - lro *longrunning.Operation -} - -// ApproveBuildOperation returns a new ApproveBuildOperation from a given name. -// The name must be that of a previously created ApproveBuildOperation, possibly from a different process. -func (c *gRPCClient) ApproveBuildOperation(name string) *ApproveBuildOperation { - return &ApproveBuildOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} - -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// CreateBuild starts a build with the specified configuration. // -// See documentation of Poll for error-handling information. -func (op *ApproveBuildOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*cloudbuildpb.Build, error) { - var resp cloudbuildpb.Build - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { +// This method returns a long-running Operation, which includes the build +// ID. Pass the build ID to GetBuild to determine the build status (such as +// SUCCESS or FAILURE). +func (c *restClient) CreateBuild(ctx context.Context, req *cloudbuildpb.CreateBuildRequest, opts ...gax.CallOption) (*CreateBuildOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetBuild() + jsonReq, err := m.Marshal(body) + if err != nil { return nil, err } - return &resp, nil -} -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *ApproveBuildOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*cloudbuildpb.Build, error) { - var resp cloudbuildpb.Build - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - if !op.Done() { - return nil, nil - } - return &resp, nil -} + baseUrl.Path += fmt.Sprintf("/v1/projects/%v/builds", req.GetProjectId()) -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *ApproveBuildOperation) Metadata() (*cloudbuildpb.BuildOperationMetadata, error) { - var meta cloudbuildpb.BuildOperationMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { - return nil, err + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetParent() != "" { + params.Add("parent", fmt.Sprintf("%v", req.GetParent())) } - return &meta, nil -} -// Done reports whether the long-running operation has completed. -func (op *ApproveBuildOperation) Done() bool { - return op.lro.Done() -} + baseUrl.RawQuery = params.Encode() -// 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 *ApproveBuildOperation) Name() string { - return op.lro.Name() -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "parent", url.QueryEscape(req.GetParent()))) -// CreateBuildOperation manages a long-running operation from CreateBuild. -type CreateBuildOperation struct { - lro *longrunning.Operation -} + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers -// CreateBuildOperation returns a new CreateBuildOperation from a given name. -// The name must be that of a previously created CreateBuildOperation, possibly from a different process. -func (c *gRPCClient) CreateBuildOperation(name string) *CreateBuildOperation { - return &CreateBuildOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *CreateBuildOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*cloudbuildpb.Build, error) { - var resp cloudbuildpb.Build - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { - return nil, err + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e } - return &resp, nil + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateBuildOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil } -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// GetBuild returns information about a previously requested build. // -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *CreateBuildOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*cloudbuildpb.Build, error) { - var resp cloudbuildpb.Build - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { +// The Build that is returned includes its status (such as SUCCESS, +// FAILURE, or WORKING), and timing information. +func (c *restClient) GetBuild(ctx context.Context, req *cloudbuildpb.GetBuildRequest, opts ...gax.CallOption) (*cloudbuildpb.Build, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - if !op.Done() { - return nil, nil - } - return &resp, nil -} + baseUrl.Path += fmt.Sprintf("/v1/projects/%v/builds/%v", req.GetProjectId(), req.GetId()) -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *CreateBuildOperation) Metadata() (*cloudbuildpb.BuildOperationMetadata, error) { - var meta cloudbuildpb.BuildOperationMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { - return nil, err + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetName() != "" { + params.Add("name", fmt.Sprintf("%v", req.GetName())) } - return &meta, nil -} + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "id", url.QueryEscape(req.GetId()), "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetBuild[0:len((*c.CallOptions).GetBuild):len((*c.CallOptions).GetBuild)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cloudbuildpb.Build{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListBuilds lists previously requested builds. +// +// Previously requested builds may still be in-progress, or may have finished +// successfully or unsuccessfully. +func (c *restClient) ListBuilds(ctx context.Context, req *cloudbuildpb.ListBuildsRequest, opts ...gax.CallOption) *BuildIterator { + it := &BuildIterator{} + req = proto.Clone(req).(*cloudbuildpb.ListBuildsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*cloudbuildpb.Build, string, error) { + resp := &cloudbuildpb.ListBuildsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/projects/%v/builds", req.GetProjectId()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + if req.GetParent() != "" { + params.Add("parent", fmt.Sprintf("%v", req.GetParent())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetBuilds(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CancelBuild cancels a build in progress. +func (c *restClient) CancelBuild(ctx context.Context, req *cloudbuildpb.CancelBuildRequest, opts ...gax.CallOption) (*cloudbuildpb.Build, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/projects/%v/builds/%v:cancel", req.GetProjectId(), req.GetId()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "id", url.QueryEscape(req.GetId()), "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CancelBuild[0:len((*c.CallOptions).CancelBuild):len((*c.CallOptions).CancelBuild)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cloudbuildpb.Build{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// RetryBuild creates a new build based on the specified build. +// +// This method creates a new build using the original build request, which may +// or may not result in an identical build. +// +// For triggered builds: +// +// Triggered builds resolve to a precise revision; therefore a retry of a +// triggered build will result in a build that uses the same revision. +// +// For non-triggered builds that specify RepoSource: +// +// If the original build built from the tip of a branch, the retried build +// will build from the tip of that branch, which may not be the same revision +// as the original build. +// +// If the original build specified a commit sha or revision ID, the retried +// build will use the identical source. +// +// For builds that specify StorageSource: +// +// If the original build pulled source from Google Cloud Storage without +// specifying the generation of the object, the new build will use the current +// object, which may be different from the original build source. +// +// If the original build pulled source from Cloud Storage and specified the +// generation of the object, the new build will attempt to use the same +// object, which may or may not be available depending on the bucket’s +// lifecycle management settings. +func (c *restClient) RetryBuild(ctx context.Context, req *cloudbuildpb.RetryBuildRequest, opts ...gax.CallOption) (*RetryBuildOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/projects/%v/builds/%v:retry", req.GetProjectId(), req.GetId()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "id", url.QueryEscape(req.GetId()), "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &RetryBuildOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ApproveBuild approves or rejects a pending build. +// +// If approved, the returned LRO will be analogous to the LRO returned from +// a CreateBuild call. +// +// If rejected, the returned LRO will be immediately done. +func (c *restClient) ApproveBuild(ctx context.Context, req *cloudbuildpb.ApproveBuildRequest, opts ...gax.CallOption) (*ApproveBuildOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:approve", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &ApproveBuildOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// CreateBuildTrigger creates a new BuildTrigger. +// +// This API is experimental. +func (c *restClient) CreateBuildTrigger(ctx context.Context, req *cloudbuildpb.CreateBuildTriggerRequest, opts ...gax.CallOption) (*cloudbuildpb.BuildTrigger, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetTrigger() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/projects/%v/triggers", req.GetProjectId()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetParent() != "" { + params.Add("parent", fmt.Sprintf("%v", req.GetParent())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateBuildTrigger[0:len((*c.CallOptions).CreateBuildTrigger):len((*c.CallOptions).CreateBuildTrigger)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cloudbuildpb.BuildTrigger{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetBuildTrigger returns information about a BuildTrigger. +// +// This API is experimental. +func (c *restClient) GetBuildTrigger(ctx context.Context, req *cloudbuildpb.GetBuildTriggerRequest, opts ...gax.CallOption) (*cloudbuildpb.BuildTrigger, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/projects/%v/triggers/%v", req.GetProjectId(), req.GetTriggerId()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetName() != "" { + params.Add("name", fmt.Sprintf("%v", req.GetName())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "trigger_id", url.QueryEscape(req.GetTriggerId()), "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetBuildTrigger[0:len((*c.CallOptions).GetBuildTrigger):len((*c.CallOptions).GetBuildTrigger)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cloudbuildpb.BuildTrigger{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListBuildTriggers lists existing BuildTriggers. +// +// This API is experimental. +func (c *restClient) ListBuildTriggers(ctx context.Context, req *cloudbuildpb.ListBuildTriggersRequest, opts ...gax.CallOption) *BuildTriggerIterator { + it := &BuildTriggerIterator{} + req = proto.Clone(req).(*cloudbuildpb.ListBuildTriggersRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*cloudbuildpb.BuildTrigger, string, error) { + resp := &cloudbuildpb.ListBuildTriggersResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/projects/%v/triggers", req.GetProjectId()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + if req.GetParent() != "" { + params.Add("parent", fmt.Sprintf("%v", req.GetParent())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetTriggers(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// DeleteBuildTrigger deletes a BuildTrigger by its project ID and trigger ID. +// +// This API is experimental. +func (c *restClient) DeleteBuildTrigger(ctx context.Context, req *cloudbuildpb.DeleteBuildTriggerRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/projects/%v/triggers/%v", req.GetProjectId(), req.GetTriggerId()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetName() != "" { + params.Add("name", fmt.Sprintf("%v", req.GetName())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "trigger_id", url.QueryEscape(req.GetTriggerId()), "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// UpdateBuildTrigger updates a BuildTrigger by its project ID and trigger ID. +// +// This API is experimental. +func (c *restClient) UpdateBuildTrigger(ctx context.Context, req *cloudbuildpb.UpdateBuildTriggerRequest, opts ...gax.CallOption) (*cloudbuildpb.BuildTrigger, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetTrigger() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/projects/%v/triggers/%v", req.GetProjectId(), req.GetTriggerId()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "trigger_id", url.QueryEscape(req.GetTriggerId()), "trigger.resource_name", url.QueryEscape(req.GetTrigger().GetResourceName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateBuildTrigger[0:len((*c.CallOptions).UpdateBuildTrigger):len((*c.CallOptions).UpdateBuildTrigger)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cloudbuildpb.BuildTrigger{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// RunBuildTrigger runs a BuildTrigger at a particular source revision. +func (c *restClient) RunBuildTrigger(ctx context.Context, req *cloudbuildpb.RunBuildTriggerRequest, opts ...gax.CallOption) (*RunBuildTriggerOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetSource() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/projects/%v/triggers/%v:run", req.GetProjectId(), req.GetTriggerId()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetName() != "" { + params.Add("name", fmt.Sprintf("%v", req.GetName())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "trigger_id", url.QueryEscape(req.GetTriggerId()), "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &RunBuildTriggerOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ReceiveTriggerWebhook receiveTriggerWebhook [Experimental] is called when the API receives a +// webhook request targeted at a specific trigger. +func (c *restClient) ReceiveTriggerWebhook(ctx context.Context, req *cloudbuildpb.ReceiveTriggerWebhookRequest, opts ...gax.CallOption) (*cloudbuildpb.ReceiveTriggerWebhookResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetBody() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/projects/%v/triggers/%v:webhook", req.GetProjectId(), req.GetTrigger()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetName() != "" { + params.Add("name", fmt.Sprintf("%v", req.GetName())) + } + if req.GetSecret() != "" { + params.Add("secret", fmt.Sprintf("%v", req.GetSecret())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "trigger", url.QueryEscape(req.GetTrigger()), "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).ReceiveTriggerWebhook[0:len((*c.CallOptions).ReceiveTriggerWebhook):len((*c.CallOptions).ReceiveTriggerWebhook)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cloudbuildpb.ReceiveTriggerWebhookResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateWorkerPool creates a WorkerPool. +func (c *restClient) CreateWorkerPool(ctx context.Context, req *cloudbuildpb.CreateWorkerPoolRequest, opts ...gax.CallOption) (*CreateWorkerPoolOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetWorkerPool() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/workerPools", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + params.Add("workerPoolId", fmt.Sprintf("%v", req.GetWorkerPoolId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateWorkerPoolOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetWorkerPool returns details of a WorkerPool. +func (c *restClient) GetWorkerPool(ctx context.Context, req *cloudbuildpb.GetWorkerPoolRequest, opts ...gax.CallOption) (*cloudbuildpb.WorkerPool, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetWorkerPool[0:len((*c.CallOptions).GetWorkerPool):len((*c.CallOptions).GetWorkerPool)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cloudbuildpb.WorkerPool{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteWorkerPool deletes a WorkerPool. +func (c *restClient) DeleteWorkerPool(ctx context.Context, req *cloudbuildpb.DeleteWorkerPoolRequest, opts ...gax.CallOption) (*DeleteWorkerPoolOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetAllowMissing() { + params.Add("allowMissing", fmt.Sprintf("%v", req.GetAllowMissing())) + } + if req.GetEtag() != "" { + params.Add("etag", fmt.Sprintf("%v", req.GetEtag())) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteWorkerPoolOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateWorkerPool updates a WorkerPool. +func (c *restClient) UpdateWorkerPool(ctx context.Context, req *cloudbuildpb.UpdateWorkerPoolRequest, opts ...gax.CallOption) (*UpdateWorkerPoolOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetWorkerPool() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetWorkerPool().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "worker_pool.name", url.QueryEscape(req.GetWorkerPool().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateWorkerPoolOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListWorkerPools lists WorkerPools. +func (c *restClient) ListWorkerPools(ctx context.Context, req *cloudbuildpb.ListWorkerPoolsRequest, opts ...gax.CallOption) *WorkerPoolIterator { + it := &WorkerPoolIterator{} + req = proto.Clone(req).(*cloudbuildpb.ListWorkerPoolsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*cloudbuildpb.WorkerPool, string, error) { + resp := &cloudbuildpb.ListWorkerPoolsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/workerPools", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetWorkerPools(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// ApproveBuildOperation manages a long-running operation from ApproveBuild. +type ApproveBuildOperation struct { + lro *longrunning.Operation + pollPath string +} + +// ApproveBuildOperation returns a new ApproveBuildOperation from a given name. +// The name must be that of a previously created ApproveBuildOperation, possibly from a different process. +func (c *gRPCClient) ApproveBuildOperation(name string) *ApproveBuildOperation { + return &ApproveBuildOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// ApproveBuildOperation returns a new ApproveBuildOperation from a given name. +// The name must be that of a previously created ApproveBuildOperation, possibly from a different process. +func (c *restClient) ApproveBuildOperation(name string) *ApproveBuildOperation { + override := fmt.Sprintf("/v1/%s", name) + return &ApproveBuildOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *ApproveBuildOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*cloudbuildpb.Build, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp cloudbuildpb.Build + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *ApproveBuildOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*cloudbuildpb.Build, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp cloudbuildpb.Build + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *ApproveBuildOperation) Metadata() (*cloudbuildpb.BuildOperationMetadata, error) { + var meta cloudbuildpb.BuildOperationMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *ApproveBuildOperation) Done() bool { + return op.lro.Done() +} + +// 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 *ApproveBuildOperation) Name() string { + return op.lro.Name() +} + +// CreateBuildOperation manages a long-running operation from CreateBuild. +type CreateBuildOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateBuildOperation returns a new CreateBuildOperation from a given name. +// The name must be that of a previously created CreateBuildOperation, possibly from a different process. +func (c *gRPCClient) CreateBuildOperation(name string) *CreateBuildOperation { + return &CreateBuildOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateBuildOperation returns a new CreateBuildOperation from a given name. +// The name must be that of a previously created CreateBuildOperation, possibly from a different process. +func (c *restClient) CreateBuildOperation(name string) *CreateBuildOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateBuildOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CreateBuildOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*cloudbuildpb.Build, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp cloudbuildpb.Build + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *CreateBuildOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*cloudbuildpb.Build, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp cloudbuildpb.Build + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *CreateBuildOperation) Metadata() (*cloudbuildpb.BuildOperationMetadata, error) { + var meta cloudbuildpb.BuildOperationMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} // Done reports whether the long-running operation has completed. func (op *CreateBuildOperation) Done() bool { @@ -1148,7 +2684,8 @@ func (op *CreateBuildOperation) Name() string { // CreateWorkerPoolOperation manages a long-running operation from CreateWorkerPool. type CreateWorkerPoolOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateWorkerPoolOperation returns a new CreateWorkerPoolOperation from a given name. @@ -1159,10 +2696,21 @@ func (c *gRPCClient) CreateWorkerPoolOperation(name string) *CreateWorkerPoolOpe } } +// CreateWorkerPoolOperation returns a new CreateWorkerPoolOperation from a given name. +// The name must be that of a previously created CreateWorkerPoolOperation, possibly from a different process. +func (c *restClient) CreateWorkerPoolOperation(name string) *CreateWorkerPoolOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateWorkerPoolOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateWorkerPoolOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*cloudbuildpb.WorkerPool, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp cloudbuildpb.WorkerPool if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1180,6 +2728,7 @@ func (op *CreateWorkerPoolOperation) Wait(ctx context.Context, opts ...gax.CallO // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateWorkerPoolOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*cloudbuildpb.WorkerPool, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp cloudbuildpb.WorkerPool if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1217,7 +2766,8 @@ func (op *CreateWorkerPoolOperation) Name() string { // DeleteWorkerPoolOperation manages a long-running operation from DeleteWorkerPool. type DeleteWorkerPoolOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteWorkerPoolOperation returns a new DeleteWorkerPoolOperation from a given name. @@ -1228,10 +2778,21 @@ func (c *gRPCClient) DeleteWorkerPoolOperation(name string) *DeleteWorkerPoolOpe } } +// DeleteWorkerPoolOperation returns a new DeleteWorkerPoolOperation from a given name. +// The name must be that of a previously created DeleteWorkerPoolOperation, possibly from a different process. +func (c *restClient) DeleteWorkerPoolOperation(name string) *DeleteWorkerPoolOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteWorkerPoolOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteWorkerPoolOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -1245,6 +2806,7 @@ func (op *DeleteWorkerPoolOperation) Wait(ctx context.Context, opts ...gax.CallO // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteWorkerPoolOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -1275,7 +2837,8 @@ func (op *DeleteWorkerPoolOperation) Name() string { // RetryBuildOperation manages a long-running operation from RetryBuild. type RetryBuildOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // RetryBuildOperation returns a new RetryBuildOperation from a given name. @@ -1286,10 +2849,21 @@ func (c *gRPCClient) RetryBuildOperation(name string) *RetryBuildOperation { } } +// RetryBuildOperation returns a new RetryBuildOperation from a given name. +// The name must be that of a previously created RetryBuildOperation, possibly from a different process. +func (c *restClient) RetryBuildOperation(name string) *RetryBuildOperation { + override := fmt.Sprintf("/v1/%s", name) + return &RetryBuildOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *RetryBuildOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*cloudbuildpb.Build, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp cloudbuildpb.Build if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1307,6 +2881,7 @@ func (op *RetryBuildOperation) Wait(ctx context.Context, opts ...gax.CallOption) // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *RetryBuildOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*cloudbuildpb.Build, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp cloudbuildpb.Build if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1344,7 +2919,8 @@ func (op *RetryBuildOperation) Name() string { // RunBuildTriggerOperation manages a long-running operation from RunBuildTrigger. type RunBuildTriggerOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // RunBuildTriggerOperation returns a new RunBuildTriggerOperation from a given name. @@ -1355,10 +2931,21 @@ func (c *gRPCClient) RunBuildTriggerOperation(name string) *RunBuildTriggerOpera } } +// RunBuildTriggerOperation returns a new RunBuildTriggerOperation from a given name. +// The name must be that of a previously created RunBuildTriggerOperation, possibly from a different process. +func (c *restClient) RunBuildTriggerOperation(name string) *RunBuildTriggerOperation { + override := fmt.Sprintf("/v1/%s", name) + return &RunBuildTriggerOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *RunBuildTriggerOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*cloudbuildpb.Build, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp cloudbuildpb.Build if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1376,6 +2963,7 @@ func (op *RunBuildTriggerOperation) Wait(ctx context.Context, opts ...gax.CallOp // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *RunBuildTriggerOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*cloudbuildpb.Build, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp cloudbuildpb.Build if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1413,7 +3001,8 @@ func (op *RunBuildTriggerOperation) Name() string { // UpdateWorkerPoolOperation manages a long-running operation from UpdateWorkerPool. type UpdateWorkerPoolOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateWorkerPoolOperation returns a new UpdateWorkerPoolOperation from a given name. @@ -1424,10 +3013,21 @@ func (c *gRPCClient) UpdateWorkerPoolOperation(name string) *UpdateWorkerPoolOpe } } +// UpdateWorkerPoolOperation returns a new UpdateWorkerPoolOperation from a given name. +// The name must be that of a previously created UpdateWorkerPoolOperation, possibly from a different process. +func (c *restClient) UpdateWorkerPoolOperation(name string) *UpdateWorkerPoolOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateWorkerPoolOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateWorkerPoolOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*cloudbuildpb.WorkerPool, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp cloudbuildpb.WorkerPool if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1445,6 +3045,7 @@ func (op *UpdateWorkerPoolOperation) Wait(ctx context.Context, opts ...gax.CallO // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateWorkerPoolOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*cloudbuildpb.WorkerPool, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp cloudbuildpb.WorkerPool if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/cloudbuild/apiv1/v2/cloud_build_client_example_test.go b/cloudbuild/apiv1/v2/cloud_build_client_example_test.go index 327c8a08cf4a..737fc2037026 100644 --- a/cloudbuild/apiv1/v2/cloud_build_client_example_test.go +++ b/cloudbuild/apiv1/v2/cloud_build_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := cloudbuild.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_CreateBuild() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/cloudbuild/apiv1/v2/cloudbuildpb/cloudbuild.pb.go b/cloudbuild/apiv1/v2/cloudbuildpb/cloudbuild.pb.go index eff7548d6acb..43d52aaa72ae 100644 --- a/cloudbuild/apiv1/v2/cloudbuildpb/cloudbuild.pb.go +++ b/cloudbuild/apiv1/v2/cloudbuildpb/cloudbuild.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/devtools/cloudbuild/v1/cloudbuild.proto package cloudbuildpb @@ -1229,7 +1229,6 @@ type RepoSource struct { // one of these ways. // // Types that are assignable to Revision: - // // *RepoSource_BranchName // *RepoSource_TagName // *RepoSource_CommitSha @@ -1456,7 +1455,6 @@ type Source struct { // Location of source. // // Types that are assignable to Source: - // // *Source_StorageSource // *Source_RepoSource // *Source_StorageSourceManifest @@ -2370,6 +2368,7 @@ type Build struct { // IAM service account whose credentials will be used at build runtime. // Must be of the format `projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}`. // ACCOUNT can be email address or uniqueId of the service account. + // ServiceAccount string `protobuf:"bytes,42,opt,name=service_account,json=serviceAccount,proto3" json:"service_account,omitempty"` // Secrets and secret environment variables. AvailableSecrets *Secrets `protobuf:"bytes,47,opt,name=available_secrets,json=availableSecrets,proto3" json:"available_secrets,omitempty"` @@ -3950,7 +3949,6 @@ type BuildTrigger struct { // Template describing the Build request to make when the trigger is matched. // // Types that are assignable to BuildTemplate: - // // *BuildTrigger_Autodetect // *BuildTrigger_Build // *BuildTrigger_Filename @@ -4221,7 +4219,6 @@ type GitHubEventsConfig struct { // Currently supported event types: push, pull_request. // // Types that are assignable to Event: - // // *GitHubEventsConfig_PullRequest // *GitHubEventsConfig_Push Event isGitHubEventsConfig_Event `protobuf_oneof:"event"` @@ -4410,7 +4407,6 @@ type WebhookConfig struct { // Auth method specifies how the webhook authenticates with GCP. // // Types that are assignable to AuthMethod: - // // *WebhookConfig_Secret AuthMethod isWebhookConfig_AuthMethod `protobuf_oneof:"auth_method"` // Potential issues with the underlying Pub/Sub subscription configuration. @@ -4493,7 +4489,6 @@ type PullRequestFilter struct { // A target ref is the git reference where the pull request will be applied. // // Types that are assignable to GitRef: - // // *PullRequestFilter_Branch GitRef isPullRequestFilter_GitRef `protobuf_oneof:"git_ref"` // Configure builds to run whether a repository owner or collaborator need to @@ -4587,7 +4582,6 @@ type PushFilter struct { // A modified refs are the refs modified by a git push operation. // // Types that are assignable to GitRef: - // // *PushFilter_Branch // *PushFilter_Tag GitRef isPushFilter_GitRef `protobuf_oneof:"git_ref"` @@ -5454,7 +5448,6 @@ type WorkerPool struct { // Private Pool configuration for the `WorkerPool`. // // Types that are assignable to Config: - // // *WorkerPool_PrivatePoolV1Config Config isWorkerPool_Config `protobuf_oneof:"config"` // Output only. Checksum computed by the server. May be sent on update and diff --git a/cloudbuild/apiv1/v2/doc.go b/cloudbuild/apiv1/v2/doc.go index c728c0996b39..22a2e35392af 100644 --- a/cloudbuild/apiv1/v2/doc.go +++ b/cloudbuild/apiv1/v2/doc.go @@ -85,6 +85,8 @@ package cloudbuild // import "cloud.google.com/go/cloudbuild/apiv1/v2" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -173,3 +175,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/cloudbuild/apiv1/v2/gapic_metadata.json b/cloudbuild/apiv1/v2/gapic_metadata.json index 0efc4527f61d..86453582a644 100644 --- a/cloudbuild/apiv1/v2/gapic_metadata.json +++ b/cloudbuild/apiv1/v2/gapic_metadata.json @@ -101,6 +101,101 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "ApproveBuild": { + "methods": [ + "ApproveBuild" + ] + }, + "CancelBuild": { + "methods": [ + "CancelBuild" + ] + }, + "CreateBuild": { + "methods": [ + "CreateBuild" + ] + }, + "CreateBuildTrigger": { + "methods": [ + "CreateBuildTrigger" + ] + }, + "CreateWorkerPool": { + "methods": [ + "CreateWorkerPool" + ] + }, + "DeleteBuildTrigger": { + "methods": [ + "DeleteBuildTrigger" + ] + }, + "DeleteWorkerPool": { + "methods": [ + "DeleteWorkerPool" + ] + }, + "GetBuild": { + "methods": [ + "GetBuild" + ] + }, + "GetBuildTrigger": { + "methods": [ + "GetBuildTrigger" + ] + }, + "GetWorkerPool": { + "methods": [ + "GetWorkerPool" + ] + }, + "ListBuildTriggers": { + "methods": [ + "ListBuildTriggers" + ] + }, + "ListBuilds": { + "methods": [ + "ListBuilds" + ] + }, + "ListWorkerPools": { + "methods": [ + "ListWorkerPools" + ] + }, + "ReceiveTriggerWebhook": { + "methods": [ + "ReceiveTriggerWebhook" + ] + }, + "RetryBuild": { + "methods": [ + "RetryBuild" + ] + }, + "RunBuildTrigger": { + "methods": [ + "RunBuildTrigger" + ] + }, + "UpdateBuildTrigger": { + "methods": [ + "UpdateBuildTrigger" + ] + }, + "UpdateWorkerPool": { + "methods": [ + "UpdateWorkerPool" + ] + } + } } } } diff --git a/clouddms/apiv1/clouddmspb/clouddms.pb.go b/clouddms/apiv1/clouddmspb/clouddms.pb.go index 66dd38665610..9c711000cf1b 100644 --- a/clouddms/apiv1/clouddmspb/clouddms.pb.go +++ b/clouddms/apiv1/clouddmspb/clouddms.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/clouddms/v1/clouddms.proto package clouddmspb @@ -802,7 +802,6 @@ type GenerateSshScriptRequest struct { // The VM configuration // // Types that are assignable to VmConfig: - // // *GenerateSshScriptRequest_VmCreationConfig // *GenerateSshScriptRequest_VmSelectionConfig VmConfig isGenerateSshScriptRequest_VmConfig `protobuf_oneof:"vm_config"` diff --git a/clouddms/apiv1/clouddmspb/clouddms_resources.pb.go b/clouddms/apiv1/clouddmspb/clouddms_resources.pb.go index 617b67aa15c1..d8ef9ebe8332 100644 --- a/clouddms/apiv1/clouddmspb/clouddms_resources.pb.go +++ b/clouddms/apiv1/clouddmspb/clouddms_resources.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/clouddms/v1/clouddms_resources.proto package clouddmspb @@ -1189,7 +1189,6 @@ type SqlAclEntry struct { // The access control entry entry expiration. // // Types that are assignable to Expiration: - // // *SqlAclEntry_ExpireTime // *SqlAclEntry_Ttl Expiration isSqlAclEntry_Expiration `protobuf_oneof:"expiration"` @@ -1846,7 +1845,6 @@ type MigrationJob struct { // The connectivity method. // // Types that are assignable to Connectivity: - // // *MigrationJob_ReverseSshConnectivity // *MigrationJob_VpcPeeringConnectivity // *MigrationJob_StaticIpConnectivity @@ -2092,7 +2090,6 @@ type ConnectionProfile struct { // The connection profile definition. // // Types that are assignable to ConnectionProfile: - // // *ConnectionProfile_Mysql // *ConnectionProfile_Postgresql // *ConnectionProfile_Cloudsql diff --git a/clouddms/apiv1/data_migration_client.go b/clouddms/apiv1/data_migration_client.go index 19bc68f6606f..87ad1e932e0f 100644 --- a/clouddms/apiv1/data_migration_client.go +++ b/clouddms/apiv1/data_migration_client.go @@ -17,9 +17,12 @@ package clouddms import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,13 +30,16 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -94,6 +100,28 @@ func defaultDataMigrationCallOptions() *DataMigrationCallOptions { } } +func defaultDataMigrationRESTCallOptions() *DataMigrationCallOptions { + return &DataMigrationCallOptions{ + ListMigrationJobs: []gax.CallOption{}, + GetMigrationJob: []gax.CallOption{}, + CreateMigrationJob: []gax.CallOption{}, + UpdateMigrationJob: []gax.CallOption{}, + DeleteMigrationJob: []gax.CallOption{}, + StartMigrationJob: []gax.CallOption{}, + StopMigrationJob: []gax.CallOption{}, + ResumeMigrationJob: []gax.CallOption{}, + PromoteMigrationJob: []gax.CallOption{}, + VerifyMigrationJob: []gax.CallOption{}, + RestartMigrationJob: []gax.CallOption{}, + GenerateSshScript: []gax.CallOption{}, + ListConnectionProfiles: []gax.CallOption{}, + GetConnectionProfile: []gax.CallOption{}, + CreateConnectionProfile: []gax.CallOption{}, + UpdateConnectionProfile: []gax.CallOption{}, + DeleteConnectionProfile: []gax.CallOption{}, + } +} + // internalDataMigrationClient is an interface that defines the methods available from Database Migration API. type internalDataMigrationClient interface { Close() error @@ -432,6 +460,89 @@ func (c *dataMigrationGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type dataMigrationRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing DataMigrationClient + CallOptions **DataMigrationCallOptions +} + +// NewDataMigrationRESTClient creates a new data migration service rest client. +// +// Database Migration service +func NewDataMigrationRESTClient(ctx context.Context, opts ...option.ClientOption) (*DataMigrationClient, error) { + clientOpts := append(defaultDataMigrationRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultDataMigrationRESTCallOptions() + c := &dataMigrationRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &DataMigrationClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultDataMigrationRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://datamigration.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://datamigration.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://datamigration.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *dataMigrationRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *dataMigrationRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *dataMigrationRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *dataMigrationGRPCClient) ListMigrationJobs(ctx context.Context, req *clouddmspb.ListMigrationJobsRequest, opts ...gax.CallOption) *MigrationJobIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -876,161 +987,1423 @@ func (c *dataMigrationGRPCClient) DeleteConnectionProfile(ctx context.Context, r }, nil } -// CreateConnectionProfileOperation manages a long-running operation from CreateConnectionProfile. -type CreateConnectionProfileOperation struct { - lro *longrunning.Operation -} +// ListMigrationJobs lists migration jobs in a given project and location. +func (c *dataMigrationRESTClient) ListMigrationJobs(ctx context.Context, req *clouddmspb.ListMigrationJobsRequest, opts ...gax.CallOption) *MigrationJobIterator { + it := &MigrationJobIterator{} + req = proto.Clone(req).(*clouddmspb.ListMigrationJobsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*clouddmspb.MigrationJob, string, error) { + resp := &clouddmspb.ListMigrationJobsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/migrationJobs", req.GetParent()) -// CreateConnectionProfileOperation returns a new CreateConnectionProfileOperation from a given name. -// The name must be that of a previously created CreateConnectionProfileOperation, possibly from a different process. -func (c *dataMigrationGRPCClient) CreateConnectionProfileOperation(name string) *CreateConnectionProfileOperation { - return &CreateConnectionProfileOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *CreateConnectionProfileOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*clouddmspb.ConnectionProfile, error) { - var resp clouddmspb.ConnectionProfile - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { - return nil, err + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetMigrationJobs(), resp.GetNextPageToken(), nil } - return &resp, nil -} -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *CreateConnectionProfileOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*clouddmspb.ConnectionProfile, error) { - var resp clouddmspb.ConnectionProfile - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { - return nil, err - } - if !op.Done() { - return nil, 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 } - return &resp, nil + + it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it } -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *CreateConnectionProfileOperation) Metadata() (*clouddmspb.OperationMetadata, error) { - var meta clouddmspb.OperationMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { +// GetMigrationJob gets details of a single migration job. +func (c *dataMigrationRESTClient) GetMigrationJob(ctx context.Context, req *clouddmspb.GetMigrationJobRequest, opts ...gax.CallOption) (*clouddmspb.MigrationJob, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - return &meta, nil -} + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) -// Done reports whether the long-running operation has completed. -func (op *CreateConnectionProfileOperation) Done() bool { - return op.lro.Done() -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") -// 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 *CreateConnectionProfileOperation) Name() string { - return op.lro.Name() -} + baseUrl.RawQuery = params.Encode() -// CreateMigrationJobOperation manages a long-running operation from CreateMigrationJob. -type CreateMigrationJobOperation struct { - lro *longrunning.Operation -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) -// CreateMigrationJobOperation returns a new CreateMigrationJobOperation from a given name. -// The name must be that of a previously created CreateMigrationJobOperation, possibly from a different process. -func (c *dataMigrationGRPCClient) CreateMigrationJobOperation(name string) *CreateMigrationJobOperation { - return &CreateMigrationJobOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetMigrationJob[0:len((*c.CallOptions).GetMigrationJob):len((*c.CallOptions).GetMigrationJob)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &clouddmspb.MigrationJob{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e } + return resp, nil } -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *CreateMigrationJobOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*clouddmspb.MigrationJob, error) { - var resp clouddmspb.MigrationJob - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { +// CreateMigrationJob creates a new migration job in a given project and location. +func (c *dataMigrationRESTClient) CreateMigrationJob(ctx context.Context, req *clouddmspb.CreateMigrationJobRequest, opts ...gax.CallOption) (*CreateMigrationJobOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetMigrationJob() + jsonReq, err := m.Marshal(body) + if err != nil { return nil, err } - return &resp, nil -} -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *CreateMigrationJobOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*clouddmspb.MigrationJob, error) { - var resp clouddmspb.MigrationJob - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - if !op.Done() { - return nil, nil - } - return &resp, nil -} + baseUrl.Path += fmt.Sprintf("/v1/%v/migrationJobs", req.GetParent()) -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *CreateMigrationJobOperation) Metadata() (*clouddmspb.OperationMetadata, error) { - var meta clouddmspb.OperationMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { - return nil, err + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("migrationJobId", fmt.Sprintf("%v", req.GetMigrationJobId())) + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } - return &meta, nil -} -// Done reports whether the long-running operation has completed. -func (op *CreateMigrationJobOperation) Done() bool { - return op.lro.Done() -} + baseUrl.RawQuery = params.Encode() -// 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 *CreateMigrationJobOperation) Name() string { - return op.lro.Name() -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) -// DeleteConnectionProfileOperation manages a long-running operation from DeleteConnectionProfile. -type DeleteConnectionProfileOperation struct { - lro *longrunning.Operation -} + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers -// DeleteConnectionProfileOperation returns a new DeleteConnectionProfileOperation from a given name. -// The name must be that of a previously created DeleteConnectionProfileOperation, possibly from a different process. + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateMigrationJobOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateMigrationJob updates the parameters of a single migration job. +func (c *dataMigrationRESTClient) UpdateMigrationJob(ctx context.Context, req *clouddmspb.UpdateMigrationJobRequest, opts ...gax.CallOption) (*UpdateMigrationJobOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetMigrationJob() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetMigrationJob().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "migration_job.name", url.QueryEscape(req.GetMigrationJob().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateMigrationJobOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteMigrationJob deletes a single migration job. +func (c *dataMigrationRESTClient) DeleteMigrationJob(ctx context.Context, req *clouddmspb.DeleteMigrationJobRequest, opts ...gax.CallOption) (*DeleteMigrationJobOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetForce() { + params.Add("force", fmt.Sprintf("%v", req.GetForce())) + } + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteMigrationJobOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// StartMigrationJob start an already created migration job. +func (c *dataMigrationRESTClient) StartMigrationJob(ctx context.Context, req *clouddmspb.StartMigrationJobRequest, opts ...gax.CallOption) (*StartMigrationJobOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:start", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &StartMigrationJobOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// StopMigrationJob stops a running migration job. +func (c *dataMigrationRESTClient) StopMigrationJob(ctx context.Context, req *clouddmspb.StopMigrationJobRequest, opts ...gax.CallOption) (*StopMigrationJobOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:stop", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &StopMigrationJobOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ResumeMigrationJob resume a migration job that is currently stopped and is resumable (was +// stopped during CDC phase). +func (c *dataMigrationRESTClient) ResumeMigrationJob(ctx context.Context, req *clouddmspb.ResumeMigrationJobRequest, opts ...gax.CallOption) (*ResumeMigrationJobOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:resume", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &ResumeMigrationJobOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// PromoteMigrationJob promote a migration job, stopping replication to the destination and +// promoting the destination to be a standalone database. +func (c *dataMigrationRESTClient) PromoteMigrationJob(ctx context.Context, req *clouddmspb.PromoteMigrationJobRequest, opts ...gax.CallOption) (*PromoteMigrationJobOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:promote", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &PromoteMigrationJobOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// VerifyMigrationJob verify a migration job, making sure the destination can reach the source +// and that all configuration and prerequisites are met. +func (c *dataMigrationRESTClient) VerifyMigrationJob(ctx context.Context, req *clouddmspb.VerifyMigrationJobRequest, opts ...gax.CallOption) (*VerifyMigrationJobOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:verify", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &VerifyMigrationJobOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// RestartMigrationJob restart a stopped or failed migration job, resetting the destination +// instance to its original state and starting the migration process from +// scratch. +func (c *dataMigrationRESTClient) RestartMigrationJob(ctx context.Context, req *clouddmspb.RestartMigrationJobRequest, opts ...gax.CallOption) (*RestartMigrationJobOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:restart", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &RestartMigrationJobOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GenerateSshScript generate a SSH configuration script to configure the reverse SSH +// connectivity. +func (c *dataMigrationRESTClient) GenerateSshScript(ctx context.Context, req *clouddmspb.GenerateSshScriptRequest, opts ...gax.CallOption) (*clouddmspb.SshScript, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:generateSshScript", req.GetMigrationJob()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "migration_job", url.QueryEscape(req.GetMigrationJob()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GenerateSshScript[0:len((*c.CallOptions).GenerateSshScript):len((*c.CallOptions).GenerateSshScript)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &clouddmspb.SshScript{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListConnectionProfiles retrieve a list of all connection profiles in a given project and location. +func (c *dataMigrationRESTClient) ListConnectionProfiles(ctx context.Context, req *clouddmspb.ListConnectionProfilesRequest, opts ...gax.CallOption) *ConnectionProfileIterator { + it := &ConnectionProfileIterator{} + req = proto.Clone(req).(*clouddmspb.ListConnectionProfilesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*clouddmspb.ConnectionProfile, string, error) { + resp := &clouddmspb.ListConnectionProfilesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/connectionProfiles", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetConnectionProfiles(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetConnectionProfile gets details of a single connection profile. +func (c *dataMigrationRESTClient) GetConnectionProfile(ctx context.Context, req *clouddmspb.GetConnectionProfileRequest, opts ...gax.CallOption) (*clouddmspb.ConnectionProfile, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetConnectionProfile[0:len((*c.CallOptions).GetConnectionProfile):len((*c.CallOptions).GetConnectionProfile)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &clouddmspb.ConnectionProfile{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateConnectionProfile creates a new connection profile in a given project and location. +func (c *dataMigrationRESTClient) CreateConnectionProfile(ctx context.Context, req *clouddmspb.CreateConnectionProfileRequest, opts ...gax.CallOption) (*CreateConnectionProfileOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetConnectionProfile() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/connectionProfiles", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("connectionProfileId", fmt.Sprintf("%v", req.GetConnectionProfileId())) + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateConnectionProfileOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateConnectionProfile update the configuration of a single connection profile. +func (c *dataMigrationRESTClient) UpdateConnectionProfile(ctx context.Context, req *clouddmspb.UpdateConnectionProfileRequest, opts ...gax.CallOption) (*UpdateConnectionProfileOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetConnectionProfile() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetConnectionProfile().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "connection_profile.name", url.QueryEscape(req.GetConnectionProfile().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateConnectionProfileOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteConnectionProfile deletes a single Database Migration Service connection profile. +// A connection profile can only be deleted if it is not in use by any +// active migration jobs. +func (c *dataMigrationRESTClient) DeleteConnectionProfile(ctx context.Context, req *clouddmspb.DeleteConnectionProfileRequest, opts ...gax.CallOption) (*DeleteConnectionProfileOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetForce() { + params.Add("force", fmt.Sprintf("%v", req.GetForce())) + } + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteConnectionProfileOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// CreateConnectionProfileOperation manages a long-running operation from CreateConnectionProfile. +type CreateConnectionProfileOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateConnectionProfileOperation returns a new CreateConnectionProfileOperation from a given name. +// The name must be that of a previously created CreateConnectionProfileOperation, possibly from a different process. +func (c *dataMigrationGRPCClient) CreateConnectionProfileOperation(name string) *CreateConnectionProfileOperation { + return &CreateConnectionProfileOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateConnectionProfileOperation returns a new CreateConnectionProfileOperation from a given name. +// The name must be that of a previously created CreateConnectionProfileOperation, possibly from a different process. +func (c *dataMigrationRESTClient) CreateConnectionProfileOperation(name string) *CreateConnectionProfileOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateConnectionProfileOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CreateConnectionProfileOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*clouddmspb.ConnectionProfile, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp clouddmspb.ConnectionProfile + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *CreateConnectionProfileOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*clouddmspb.ConnectionProfile, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp clouddmspb.ConnectionProfile + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *CreateConnectionProfileOperation) Metadata() (*clouddmspb.OperationMetadata, error) { + var meta clouddmspb.OperationMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *CreateConnectionProfileOperation) Done() bool { + return op.lro.Done() +} + +// 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 *CreateConnectionProfileOperation) Name() string { + return op.lro.Name() +} + +// CreateMigrationJobOperation manages a long-running operation from CreateMigrationJob. +type CreateMigrationJobOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateMigrationJobOperation returns a new CreateMigrationJobOperation from a given name. +// The name must be that of a previously created CreateMigrationJobOperation, possibly from a different process. +func (c *dataMigrationGRPCClient) CreateMigrationJobOperation(name string) *CreateMigrationJobOperation { + return &CreateMigrationJobOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateMigrationJobOperation returns a new CreateMigrationJobOperation from a given name. +// The name must be that of a previously created CreateMigrationJobOperation, possibly from a different process. +func (c *dataMigrationRESTClient) CreateMigrationJobOperation(name string) *CreateMigrationJobOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateMigrationJobOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CreateMigrationJobOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*clouddmspb.MigrationJob, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp clouddmspb.MigrationJob + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *CreateMigrationJobOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*clouddmspb.MigrationJob, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp clouddmspb.MigrationJob + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *CreateMigrationJobOperation) Metadata() (*clouddmspb.OperationMetadata, error) { + var meta clouddmspb.OperationMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *CreateMigrationJobOperation) Done() bool { + return op.lro.Done() +} + +// 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 *CreateMigrationJobOperation) Name() string { + return op.lro.Name() +} + +// DeleteConnectionProfileOperation manages a long-running operation from DeleteConnectionProfile. +type DeleteConnectionProfileOperation struct { + lro *longrunning.Operation + pollPath string +} + +// DeleteConnectionProfileOperation returns a new DeleteConnectionProfileOperation from a given name. +// The name must be that of a previously created DeleteConnectionProfileOperation, possibly from a different process. func (c *dataMigrationGRPCClient) DeleteConnectionProfileOperation(name string) *DeleteConnectionProfileOperation { return &DeleteConnectionProfileOperation{ lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } +// DeleteConnectionProfileOperation returns a new DeleteConnectionProfileOperation from a given name. +// The name must be that of a previously created DeleteConnectionProfileOperation, possibly from a different process. +func (c *dataMigrationRESTClient) DeleteConnectionProfileOperation(name string) *DeleteConnectionProfileOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteConnectionProfileOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteConnectionProfileOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -1044,6 +2417,7 @@ func (op *DeleteConnectionProfileOperation) Wait(ctx context.Context, opts ...ga // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteConnectionProfileOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -1074,7 +2448,8 @@ func (op *DeleteConnectionProfileOperation) Name() string { // DeleteMigrationJobOperation manages a long-running operation from DeleteMigrationJob. type DeleteMigrationJobOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteMigrationJobOperation returns a new DeleteMigrationJobOperation from a given name. @@ -1085,10 +2460,21 @@ func (c *dataMigrationGRPCClient) DeleteMigrationJobOperation(name string) *Dele } } +// DeleteMigrationJobOperation returns a new DeleteMigrationJobOperation from a given name. +// The name must be that of a previously created DeleteMigrationJobOperation, possibly from a different process. +func (c *dataMigrationRESTClient) DeleteMigrationJobOperation(name string) *DeleteMigrationJobOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteMigrationJobOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteMigrationJobOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -1102,6 +2488,7 @@ func (op *DeleteMigrationJobOperation) Wait(ctx context.Context, opts ...gax.Cal // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteMigrationJobOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -1132,7 +2519,8 @@ func (op *DeleteMigrationJobOperation) Name() string { // PromoteMigrationJobOperation manages a long-running operation from PromoteMigrationJob. type PromoteMigrationJobOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // PromoteMigrationJobOperation returns a new PromoteMigrationJobOperation from a given name. @@ -1143,10 +2531,21 @@ func (c *dataMigrationGRPCClient) PromoteMigrationJobOperation(name string) *Pro } } +// PromoteMigrationJobOperation returns a new PromoteMigrationJobOperation from a given name. +// The name must be that of a previously created PromoteMigrationJobOperation, possibly from a different process. +func (c *dataMigrationRESTClient) PromoteMigrationJobOperation(name string) *PromoteMigrationJobOperation { + override := fmt.Sprintf("/v1/%s", name) + return &PromoteMigrationJobOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *PromoteMigrationJobOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*clouddmspb.MigrationJob, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp clouddmspb.MigrationJob if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1164,6 +2563,7 @@ func (op *PromoteMigrationJobOperation) Wait(ctx context.Context, opts ...gax.Ca // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *PromoteMigrationJobOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*clouddmspb.MigrationJob, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp clouddmspb.MigrationJob if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1201,7 +2601,8 @@ func (op *PromoteMigrationJobOperation) Name() string { // RestartMigrationJobOperation manages a long-running operation from RestartMigrationJob. type RestartMigrationJobOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // RestartMigrationJobOperation returns a new RestartMigrationJobOperation from a given name. @@ -1212,10 +2613,21 @@ func (c *dataMigrationGRPCClient) RestartMigrationJobOperation(name string) *Res } } +// RestartMigrationJobOperation returns a new RestartMigrationJobOperation from a given name. +// The name must be that of a previously created RestartMigrationJobOperation, possibly from a different process. +func (c *dataMigrationRESTClient) RestartMigrationJobOperation(name string) *RestartMigrationJobOperation { + override := fmt.Sprintf("/v1/%s", name) + return &RestartMigrationJobOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *RestartMigrationJobOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*clouddmspb.MigrationJob, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp clouddmspb.MigrationJob if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1233,6 +2645,7 @@ func (op *RestartMigrationJobOperation) Wait(ctx context.Context, opts ...gax.Ca // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *RestartMigrationJobOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*clouddmspb.MigrationJob, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp clouddmspb.MigrationJob if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1270,7 +2683,8 @@ func (op *RestartMigrationJobOperation) Name() string { // ResumeMigrationJobOperation manages a long-running operation from ResumeMigrationJob. type ResumeMigrationJobOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // ResumeMigrationJobOperation returns a new ResumeMigrationJobOperation from a given name. @@ -1281,10 +2695,21 @@ func (c *dataMigrationGRPCClient) ResumeMigrationJobOperation(name string) *Resu } } +// ResumeMigrationJobOperation returns a new ResumeMigrationJobOperation from a given name. +// The name must be that of a previously created ResumeMigrationJobOperation, possibly from a different process. +func (c *dataMigrationRESTClient) ResumeMigrationJobOperation(name string) *ResumeMigrationJobOperation { + override := fmt.Sprintf("/v1/%s", name) + return &ResumeMigrationJobOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *ResumeMigrationJobOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*clouddmspb.MigrationJob, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp clouddmspb.MigrationJob if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1302,6 +2727,7 @@ func (op *ResumeMigrationJobOperation) Wait(ctx context.Context, opts ...gax.Cal // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *ResumeMigrationJobOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*clouddmspb.MigrationJob, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp clouddmspb.MigrationJob if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1339,7 +2765,8 @@ func (op *ResumeMigrationJobOperation) Name() string { // StartMigrationJobOperation manages a long-running operation from StartMigrationJob. type StartMigrationJobOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // StartMigrationJobOperation returns a new StartMigrationJobOperation from a given name. @@ -1350,10 +2777,21 @@ func (c *dataMigrationGRPCClient) StartMigrationJobOperation(name string) *Start } } +// StartMigrationJobOperation returns a new StartMigrationJobOperation from a given name. +// The name must be that of a previously created StartMigrationJobOperation, possibly from a different process. +func (c *dataMigrationRESTClient) StartMigrationJobOperation(name string) *StartMigrationJobOperation { + override := fmt.Sprintf("/v1/%s", name) + return &StartMigrationJobOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *StartMigrationJobOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*clouddmspb.MigrationJob, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp clouddmspb.MigrationJob if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1371,6 +2809,7 @@ func (op *StartMigrationJobOperation) Wait(ctx context.Context, opts ...gax.Call // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *StartMigrationJobOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*clouddmspb.MigrationJob, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp clouddmspb.MigrationJob if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1408,7 +2847,8 @@ func (op *StartMigrationJobOperation) Name() string { // StopMigrationJobOperation manages a long-running operation from StopMigrationJob. type StopMigrationJobOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // StopMigrationJobOperation returns a new StopMigrationJobOperation from a given name. @@ -1419,10 +2859,21 @@ func (c *dataMigrationGRPCClient) StopMigrationJobOperation(name string) *StopMi } } +// StopMigrationJobOperation returns a new StopMigrationJobOperation from a given name. +// The name must be that of a previously created StopMigrationJobOperation, possibly from a different process. +func (c *dataMigrationRESTClient) StopMigrationJobOperation(name string) *StopMigrationJobOperation { + override := fmt.Sprintf("/v1/%s", name) + return &StopMigrationJobOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *StopMigrationJobOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*clouddmspb.MigrationJob, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp clouddmspb.MigrationJob if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1440,6 +2891,7 @@ func (op *StopMigrationJobOperation) Wait(ctx context.Context, opts ...gax.CallO // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *StopMigrationJobOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*clouddmspb.MigrationJob, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp clouddmspb.MigrationJob if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1477,7 +2929,8 @@ func (op *StopMigrationJobOperation) Name() string { // UpdateConnectionProfileOperation manages a long-running operation from UpdateConnectionProfile. type UpdateConnectionProfileOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateConnectionProfileOperation returns a new UpdateConnectionProfileOperation from a given name. @@ -1488,10 +2941,21 @@ func (c *dataMigrationGRPCClient) UpdateConnectionProfileOperation(name string) } } +// UpdateConnectionProfileOperation returns a new UpdateConnectionProfileOperation from a given name. +// The name must be that of a previously created UpdateConnectionProfileOperation, possibly from a different process. +func (c *dataMigrationRESTClient) UpdateConnectionProfileOperation(name string) *UpdateConnectionProfileOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateConnectionProfileOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateConnectionProfileOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*clouddmspb.ConnectionProfile, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp clouddmspb.ConnectionProfile if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1509,6 +2973,7 @@ func (op *UpdateConnectionProfileOperation) Wait(ctx context.Context, opts ...ga // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateConnectionProfileOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*clouddmspb.ConnectionProfile, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp clouddmspb.ConnectionProfile if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1546,7 +3011,8 @@ func (op *UpdateConnectionProfileOperation) Name() string { // UpdateMigrationJobOperation manages a long-running operation from UpdateMigrationJob. type UpdateMigrationJobOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateMigrationJobOperation returns a new UpdateMigrationJobOperation from a given name. @@ -1557,10 +3023,21 @@ func (c *dataMigrationGRPCClient) UpdateMigrationJobOperation(name string) *Upda } } +// UpdateMigrationJobOperation returns a new UpdateMigrationJobOperation from a given name. +// The name must be that of a previously created UpdateMigrationJobOperation, possibly from a different process. +func (c *dataMigrationRESTClient) UpdateMigrationJobOperation(name string) *UpdateMigrationJobOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateMigrationJobOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateMigrationJobOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*clouddmspb.MigrationJob, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp clouddmspb.MigrationJob if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1578,6 +3055,7 @@ func (op *UpdateMigrationJobOperation) Wait(ctx context.Context, opts ...gax.Cal // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateMigrationJobOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*clouddmspb.MigrationJob, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp clouddmspb.MigrationJob if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1615,7 +3093,8 @@ func (op *UpdateMigrationJobOperation) Name() string { // VerifyMigrationJobOperation manages a long-running operation from VerifyMigrationJob. type VerifyMigrationJobOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // VerifyMigrationJobOperation returns a new VerifyMigrationJobOperation from a given name. @@ -1626,10 +3105,21 @@ func (c *dataMigrationGRPCClient) VerifyMigrationJobOperation(name string) *Veri } } +// VerifyMigrationJobOperation returns a new VerifyMigrationJobOperation from a given name. +// The name must be that of a previously created VerifyMigrationJobOperation, possibly from a different process. +func (c *dataMigrationRESTClient) VerifyMigrationJobOperation(name string) *VerifyMigrationJobOperation { + override := fmt.Sprintf("/v1/%s", name) + return &VerifyMigrationJobOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *VerifyMigrationJobOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*clouddmspb.MigrationJob, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp clouddmspb.MigrationJob if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1647,6 +3137,7 @@ func (op *VerifyMigrationJobOperation) Wait(ctx context.Context, opts ...gax.Cal // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *VerifyMigrationJobOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*clouddmspb.MigrationJob, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp clouddmspb.MigrationJob if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/clouddms/apiv1/data_migration_client_example_test.go b/clouddms/apiv1/data_migration_client_example_test.go index f1215535299c..65a6f3171ee1 100644 --- a/clouddms/apiv1/data_migration_client_example_test.go +++ b/clouddms/apiv1/data_migration_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewDataMigrationClient() { _ = c } +func ExampleNewDataMigrationRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := clouddms.NewDataMigrationRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleDataMigrationClient_ListMigrationJobs() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/clouddms/apiv1/doc.go b/clouddms/apiv1/doc.go index 457ab4f36602..9ea697cf565d 100644 --- a/clouddms/apiv1/doc.go +++ b/clouddms/apiv1/doc.go @@ -87,6 +87,8 @@ package clouddms // import "cloud.google.com/go/clouddms/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -175,3 +177,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/clouddms/apiv1/gapic_metadata.json b/clouddms/apiv1/gapic_metadata.json index b6b1c33804f2..e2d6edb48648 100644 --- a/clouddms/apiv1/gapic_metadata.json +++ b/clouddms/apiv1/gapic_metadata.json @@ -96,6 +96,96 @@ ] } } + }, + "rest": { + "libraryClient": "DataMigrationClient", + "rpcs": { + "CreateConnectionProfile": { + "methods": [ + "CreateConnectionProfile" + ] + }, + "CreateMigrationJob": { + "methods": [ + "CreateMigrationJob" + ] + }, + "DeleteConnectionProfile": { + "methods": [ + "DeleteConnectionProfile" + ] + }, + "DeleteMigrationJob": { + "methods": [ + "DeleteMigrationJob" + ] + }, + "GenerateSshScript": { + "methods": [ + "GenerateSshScript" + ] + }, + "GetConnectionProfile": { + "methods": [ + "GetConnectionProfile" + ] + }, + "GetMigrationJob": { + "methods": [ + "GetMigrationJob" + ] + }, + "ListConnectionProfiles": { + "methods": [ + "ListConnectionProfiles" + ] + }, + "ListMigrationJobs": { + "methods": [ + "ListMigrationJobs" + ] + }, + "PromoteMigrationJob": { + "methods": [ + "PromoteMigrationJob" + ] + }, + "RestartMigrationJob": { + "methods": [ + "RestartMigrationJob" + ] + }, + "ResumeMigrationJob": { + "methods": [ + "ResumeMigrationJob" + ] + }, + "StartMigrationJob": { + "methods": [ + "StartMigrationJob" + ] + }, + "StopMigrationJob": { + "methods": [ + "StopMigrationJob" + ] + }, + "UpdateConnectionProfile": { + "methods": [ + "UpdateConnectionProfile" + ] + }, + "UpdateMigrationJob": { + "methods": [ + "UpdateMigrationJob" + ] + }, + "VerifyMigrationJob": { + "methods": [ + "VerifyMigrationJob" + ] + } + } } } } diff --git a/cloudtasks/apiv2/cloud_tasks_client.go b/cloudtasks/apiv2/cloud_tasks_client.go index 6b8b6ba5874a..19ce575d0329 100644 --- a/cloudtasks/apiv2/cloud_tasks_client.go +++ b/cloudtasks/apiv2/cloud_tasks_client.go @@ -17,22 +17,28 @@ package cloudtasks import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" cloudtaskspb "cloud.google.com/go/cloudtasks/apiv2/cloudtaskspb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" iampb "google.golang.org/genproto/googleapis/iam/v1" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -179,6 +185,107 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + ListQueues: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + GetQueue: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + CreateQueue: []gax.CallOption{}, + UpdateQueue: []gax.CallOption{}, + DeleteQueue: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + PurgeQueue: []gax.CallOption{}, + PauseQueue: []gax.CallOption{}, + ResumeQueue: []gax.CallOption{}, + GetIamPolicy: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + SetIamPolicy: []gax.CallOption{}, + TestIamPermissions: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + ListTasks: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + GetTask: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + CreateTask: []gax.CallOption{}, + DeleteTask: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + RunTask: []gax.CallOption{}, + } +} + // internalClient is an interface that defines the methods available from Cloud Tasks API. type internalClient interface { Close() error @@ -525,6 +632,75 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new cloud tasks rest client. +// +// Cloud Tasks allows developers to manage the execution of background +// work in their applications. +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://cloudtasks.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://cloudtasks.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://cloudtasks.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) ListQueues(ctx context.Context, req *cloudtaskspb.ListQueuesRequest, opts ...gax.CallOption) *QueueIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -915,6 +1091,1161 @@ func (c *gRPCClient) RunTask(ctx context.Context, req *cloudtaskspb.RunTaskReque return resp, nil } +// ListQueues lists queues. +// +// Queues are returned in lexicographical order. +func (c *restClient) ListQueues(ctx context.Context, req *cloudtaskspb.ListQueuesRequest, opts ...gax.CallOption) *QueueIterator { + it := &QueueIterator{} + req = proto.Clone(req).(*cloudtaskspb.ListQueuesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*cloudtaskspb.Queue, string, error) { + resp := &cloudtaskspb.ListQueuesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/queues", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetQueues(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetQueue gets a queue. +func (c *restClient) GetQueue(ctx context.Context, req *cloudtaskspb.GetQueueRequest, opts ...gax.CallOption) (*cloudtaskspb.Queue, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetQueue[0:len((*c.CallOptions).GetQueue):len((*c.CallOptions).GetQueue)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cloudtaskspb.Queue{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateQueue creates a queue. +// +// Queues created with this method allow tasks to live for a maximum of 31 +// days. After a task is 31 days old, the task will be deleted regardless of whether +// it was dispatched or not. +// +// WARNING: Using this method may have unintended side effects if you are +// using an App Engine queue.yaml or queue.xml file to manage your queues. +// Read +// Overview of Queue Management and +// queue.yaml (at https://cloud.google.com/tasks/docs/queue-yaml) before using +// this method. +func (c *restClient) CreateQueue(ctx context.Context, req *cloudtaskspb.CreateQueueRequest, opts ...gax.CallOption) (*cloudtaskspb.Queue, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetQueue() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/queues", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateQueue[0:len((*c.CallOptions).CreateQueue):len((*c.CallOptions).CreateQueue)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cloudtaskspb.Queue{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateQueue updates a queue. +// +// This method creates the queue if it does not exist and updates +// the queue if it does exist. +// +// Queues created with this method allow tasks to live for a maximum of 31 +// days. After a task is 31 days old, the task will be deleted regardless of whether +// it was dispatched or not. +// +// WARNING: Using this method may have unintended side effects if you are +// using an App Engine queue.yaml or queue.xml file to manage your queues. +// Read +// Overview of Queue Management and +// queue.yaml (at https://cloud.google.com/tasks/docs/queue-yaml) before using +// this method. +func (c *restClient) UpdateQueue(ctx context.Context, req *cloudtaskspb.UpdateQueueRequest, opts ...gax.CallOption) (*cloudtaskspb.Queue, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetQueue() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetQueue().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "queue.name", url.QueryEscape(req.GetQueue().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateQueue[0:len((*c.CallOptions).UpdateQueue):len((*c.CallOptions).UpdateQueue)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cloudtaskspb.Queue{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteQueue deletes a queue. +// +// This command will delete the queue even if it has tasks in it. +// +// Note: If you delete a queue, a queue with the same name can’t be created +// for 7 days. +// +// WARNING: Using this method may have unintended side effects if you are +// using an App Engine queue.yaml or queue.xml file to manage your queues. +// Read +// Overview of Queue Management and +// queue.yaml (at https://cloud.google.com/tasks/docs/queue-yaml) before using +// this method. +func (c *restClient) DeleteQueue(ctx context.Context, req *cloudtaskspb.DeleteQueueRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// PurgeQueue purges a queue by deleting all of its tasks. +// +// All tasks created before this method is called are permanently deleted. +// +// Purge operations can take up to one minute to take effect. Tasks +// might be dispatched before the purge takes effect. A purge is irreversible. +func (c *restClient) PurgeQueue(ctx context.Context, req *cloudtaskspb.PurgeQueueRequest, opts ...gax.CallOption) (*cloudtaskspb.Queue, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:purge", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).PurgeQueue[0:len((*c.CallOptions).PurgeQueue):len((*c.CallOptions).PurgeQueue)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cloudtaskspb.Queue{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// PauseQueue pauses the queue. +// +// If a queue is paused then the system will stop dispatching tasks +// until the queue is resumed via +// ResumeQueue. Tasks can still be added +// when the queue is paused. A queue is paused if its +// state is PAUSED. +func (c *restClient) PauseQueue(ctx context.Context, req *cloudtaskspb.PauseQueueRequest, opts ...gax.CallOption) (*cloudtaskspb.Queue, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:pause", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).PauseQueue[0:len((*c.CallOptions).PauseQueue):len((*c.CallOptions).PauseQueue)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cloudtaskspb.Queue{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ResumeQueue resume a queue. +// +// This method resumes a queue after it has been +// PAUSED or +// DISABLED. The state of a queue is stored +// in the queue’s state; after calling this method it +// will be set to RUNNING. +// +// WARNING: Resuming many high-QPS queues at the same time can +// lead to target overloading. If you are resuming high-QPS +// queues, follow the 500/50/5 pattern described in +// Managing Cloud Tasks Scaling +// Risks (at https://cloud.google.com/tasks/docs/manage-cloud-task-scaling). +func (c *restClient) ResumeQueue(ctx context.Context, req *cloudtaskspb.ResumeQueueRequest, opts ...gax.CallOption) (*cloudtaskspb.Queue, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:resume", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).ResumeQueue[0:len((*c.CallOptions).ResumeQueue):len((*c.CallOptions).ResumeQueue)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cloudtaskspb.Queue{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetIamPolicy gets the access control policy for a Queue. +// Returns an empty policy if the resource exists and does not have a policy +// set. +// +// Authorization requires the following +// Google IAM (at https://cloud.google.com/iam) permission on the specified +// resource parent: +// +// cloudtasks.queues.getIamPolicy +func (c *restClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:getIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SetIamPolicy sets the access control policy for a Queue. Replaces any existing +// policy. +// +// Note: The Cloud Console does not check queue-level IAM permissions yet. +// Project-level permissions are required to use the Cloud Console. +// +// Authorization requires the following +// Google IAM (at https://cloud.google.com/iam) permission on the specified +// resource parent: +// +// cloudtasks.queues.setIamPolicy +func (c *restClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:setIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// TestIamPermissions returns permissions that a caller has on a Queue. +// If the resource does not exist, this will return an empty set of +// permissions, not a NOT_FOUND error. +// +// Note: This operation is designed to be used for building permission-aware +// UIs and command-line tools, not for authorization checking. This operation +// may “fail open” without warning. +func (c *restClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:testIamPermissions", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.TestIamPermissionsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListTasks lists the tasks in a queue. +// +// By default, only the BASIC view is retrieved +// due to performance considerations; +// response_view controls the +// subset of information which is returned. +// +// The tasks may be returned in any order. The ordering may change at any +// time. +func (c *restClient) ListTasks(ctx context.Context, req *cloudtaskspb.ListTasksRequest, opts ...gax.CallOption) *TaskIterator { + it := &TaskIterator{} + req = proto.Clone(req).(*cloudtaskspb.ListTasksRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*cloudtaskspb.Task, string, error) { + resp := &cloudtaskspb.ListTasksResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/tasks", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + if req.GetResponseView() != 0 { + params.Add("responseView", fmt.Sprintf("%v", req.GetResponseView())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetTasks(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetTask gets a task. +func (c *restClient) GetTask(ctx context.Context, req *cloudtaskspb.GetTaskRequest, opts ...gax.CallOption) (*cloudtaskspb.Task, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetResponseView() != 0 { + params.Add("responseView", fmt.Sprintf("%v", req.GetResponseView())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetTask[0:len((*c.CallOptions).GetTask):len((*c.CallOptions).GetTask)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cloudtaskspb.Task{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateTask creates a task and adds it to a queue. +// +// Tasks cannot be updated after creation; there is no UpdateTask command. +// +// The maximum task size is 100KB. +func (c *restClient) CreateTask(ctx context.Context, req *cloudtaskspb.CreateTaskRequest, opts ...gax.CallOption) (*cloudtaskspb.Task, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/tasks", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateTask[0:len((*c.CallOptions).CreateTask):len((*c.CallOptions).CreateTask)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cloudtaskspb.Task{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteTask deletes a task. +// +// A task can be deleted if it is scheduled or dispatched. A task +// cannot be deleted if it has executed successfully or permanently +// failed. +func (c *restClient) DeleteTask(ctx context.Context, req *cloudtaskspb.DeleteTaskRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// RunTask forces a task to run now. +// +// When this method is called, Cloud Tasks will dispatch the task, even if +// the task is already running, the queue has reached its RateLimits or +// is PAUSED. +// +// This command is meant to be used for manual debugging. For +// example, RunTask can be used to retry a failed +// task after a fix has been made or to manually force a task to be +// dispatched now. +// +// The dispatched task is returned. That is, the task that is returned +// contains the status after the task is dispatched but +// before the task is received by its target. +// +// If Cloud Tasks receives a successful response from the task’s +// target, then the task will be deleted; otherwise the task’s +// schedule_time will be reset to the time that +// RunTask was called plus the retry delay specified +// in the queue’s RetryConfig. +// +// RunTask returns +// NOT_FOUND when it is called on a +// task that has already succeeded or permanently failed. +func (c *restClient) RunTask(ctx context.Context, req *cloudtaskspb.RunTaskRequest, opts ...gax.CallOption) (*cloudtaskspb.Task, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:run", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).RunTask[0:len((*c.CallOptions).RunTask):len((*c.CallOptions).RunTask)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cloudtaskspb.Task{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + // QueueIterator manages a stream of *cloudtaskspb.Queue. type QueueIterator struct { items []*cloudtaskspb.Queue diff --git a/cloudtasks/apiv2/cloud_tasks_client_example_test.go b/cloudtasks/apiv2/cloud_tasks_client_example_test.go index 80ed329e66c7..f3bdb97dcf65 100644 --- a/cloudtasks/apiv2/cloud_tasks_client_example_test.go +++ b/cloudtasks/apiv2/cloud_tasks_client_example_test.go @@ -42,6 +42,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := cloudtasks.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_ListQueues() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/cloudtasks/apiv2/cloudtaskspb/cloudtasks.pb.go b/cloudtasks/apiv2/cloudtaskspb/cloudtasks.pb.go index 3f46ecc94f0e..ba5431eaa734 100644 --- a/cloudtasks/apiv2/cloudtaskspb/cloudtasks.pb.go +++ b/cloudtasks/apiv2/cloudtaskspb/cloudtasks.pb.go @@ -15,8 +15,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/tasks/v2/cloudtasks.proto package cloudtaskspb diff --git a/cloudtasks/apiv2/cloudtaskspb/queue.pb.go b/cloudtasks/apiv2/cloudtaskspb/queue.pb.go index ac86a0c30b2d..28002cb4b9de 100644 --- a/cloudtasks/apiv2/cloudtaskspb/queue.pb.go +++ b/cloudtasks/apiv2/cloudtaskspb/queue.pb.go @@ -15,8 +15,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/tasks/v2/queue.proto package cloudtaskspb @@ -134,17 +134,17 @@ type Queue struct { // The queue name must have the following format: // `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID` // - // - `PROJECT_ID` can contain letters ([A-Za-z]), numbers ([0-9]), - // hyphens (-), colons (:), or periods (.). - // For more information, see - // [Identifying - // projects](https://cloud.google.com/resource-manager/docs/creating-managing-projects#identifying_projects) - // - `LOCATION_ID` is the canonical ID for the queue's location. - // The list of available locations can be obtained by calling - // [ListLocations][google.cloud.location.Locations.ListLocations]. - // For more information, see https://cloud.google.com/about/locations/. - // - `QUEUE_ID` can contain letters ([A-Za-z]), numbers ([0-9]), or - // hyphens (-). The maximum length is 100 characters. + // * `PROJECT_ID` can contain letters ([A-Za-z]), numbers ([0-9]), + // hyphens (-), colons (:), or periods (.). + // For more information, see + // [Identifying + // projects](https://cloud.google.com/resource-manager/docs/creating-managing-projects#identifying_projects) + // * `LOCATION_ID` is the canonical ID for the queue's location. + // The list of available locations can be obtained by calling + // [ListLocations][google.cloud.location.Locations.ListLocations]. + // For more information, see https://cloud.google.com/about/locations/. + // * `QUEUE_ID` can contain letters ([A-Za-z]), numbers ([0-9]), or + // hyphens (-). The maximum length is 100 characters. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Overrides for // [task-level app_engine_routing][google.cloud.tasks.v2.AppEngineHttpRequest.app_engine_routing]. @@ -163,35 +163,35 @@ type Queue struct { // related because they both control task attempts. However they control task // attempts in different ways: // - // - [rate_limits][google.cloud.tasks.v2.Queue.rate_limits] controls the total rate of - // dispatches from a queue (i.e. all traffic dispatched from the - // queue, regardless of whether the dispatch is from a first - // attempt or a retry). - // - [retry_config][google.cloud.tasks.v2.Queue.retry_config] controls what happens to - // particular a task after its first attempt fails. That is, - // [retry_config][google.cloud.tasks.v2.Queue.retry_config] controls task retries (the - // second attempt, third attempt, etc). + // * [rate_limits][google.cloud.tasks.v2.Queue.rate_limits] controls the total rate of + // dispatches from a queue (i.e. all traffic dispatched from the + // queue, regardless of whether the dispatch is from a first + // attempt or a retry). + // * [retry_config][google.cloud.tasks.v2.Queue.retry_config] controls what happens to + // particular a task after its first attempt fails. That is, + // [retry_config][google.cloud.tasks.v2.Queue.retry_config] controls task retries (the + // second attempt, third attempt, etc). // // The queue's actual dispatch rate is the result of: // - // - Number of tasks in the queue - // - User-specified throttling: [rate_limits][google.cloud.tasks.v2.Queue.rate_limits], - // [retry_config][google.cloud.tasks.v2.Queue.retry_config], and the - // [queue's state][google.cloud.tasks.v2.Queue.state]. - // - System throttling due to `429` (Too Many Requests) or `503` (Service - // Unavailable) responses from the worker, high error rates, or to smooth - // sudden large traffic spikes. + // * Number of tasks in the queue + // * User-specified throttling: [rate_limits][google.cloud.tasks.v2.Queue.rate_limits], + // [retry_config][google.cloud.tasks.v2.Queue.retry_config], and the + // [queue's state][google.cloud.tasks.v2.Queue.state]. + // * System throttling due to `429` (Too Many Requests) or `503` (Service + // Unavailable) responses from the worker, high error rates, or to smooth + // sudden large traffic spikes. RateLimits *RateLimits `protobuf:"bytes,3,opt,name=rate_limits,json=rateLimits,proto3" json:"rate_limits,omitempty"` // Settings that determine the retry behavior. // - // - For tasks created using Cloud Tasks: the queue-level retry settings - // apply to all tasks in the queue that were created using Cloud Tasks. - // Retry settings cannot be set on individual tasks. - // - For tasks created using the App Engine SDK: the queue-level retry - // settings apply to all tasks in the queue which do not have retry settings - // explicitly set on the task and were created by the App Engine SDK. See - // [App Engine - // documentation](https://cloud.google.com/appengine/docs/standard/python/taskqueue/push/retrying-tasks). + // * For tasks created using Cloud Tasks: the queue-level retry settings + // apply to all tasks in the queue that were created using Cloud Tasks. + // Retry settings cannot be set on individual tasks. + // * For tasks created using the App Engine SDK: the queue-level retry + // settings apply to all tasks in the queue which do not have retry settings + // explicitly set on the task and were created by the App Engine SDK. See + // [App Engine + // documentation](https://cloud.google.com/appengine/docs/standard/python/taskqueue/push/retrying-tasks). RetryConfig *RetryConfig `protobuf:"bytes,4,opt,name=retry_config,json=retryConfig,proto3" json:"retry_config,omitempty"` // Output only. The state of the queue. // @@ -319,6 +319,7 @@ type RateLimits struct { // // * The maximum allowed value is 500. // + // // This field has the same meaning as // [rate in // queue.yaml/xml](https://cloud.google.com/appengine/docs/standard/python/config/queueref#rate). @@ -355,6 +356,7 @@ type RateLimits struct { // regardless of whether // [max_dispatches_per_second][google.cloud.tasks.v2.RateLimits.max_dispatches_per_second] // is updated. + // MaxBurstSize int32 `protobuf:"varint,2,opt,name=max_burst_size,json=maxBurstSize,proto3" json:"max_burst_size,omitempty"` // The maximum number of concurrent tasks that Cloud Tasks allows // to be dispatched for this queue. After this threshold has been @@ -364,8 +366,10 @@ type RateLimits struct { // If unspecified when the queue is created, Cloud Tasks will pick the // default. // + // // The maximum allowed value is 5,000. // + // // This field has the same meaning as // [max_concurrent_requests in // queue.yaml/xml](https://cloud.google.com/appengine/docs/standard/python/config/queueref#max_concurrent_requests). @@ -460,6 +464,7 @@ type RetryConfig struct { // If unspecified when the queue is created, Cloud Tasks will pick the // default. // + // // `max_retry_duration` will be truncated to the nearest second. // // This field has the same meaning as @@ -475,6 +480,7 @@ type RetryConfig struct { // If unspecified when the queue is created, Cloud Tasks will pick the // default. // + // // `min_backoff` will be truncated to the nearest second. // // This field has the same meaning as @@ -490,6 +496,7 @@ type RetryConfig struct { // If unspecified when the queue is created, Cloud Tasks will pick the // default. // + // // `max_backoff` will be truncated to the nearest second. // // This field has the same meaning as @@ -518,6 +525,7 @@ type RetryConfig struct { // If unspecified when the queue is created, Cloud Tasks will pick the // default. // + // // This field has the same meaning as // [max_doublings in // queue.yaml/xml](https://cloud.google.com/appengine/docs/standard/python/config/queueref#retry_parameters). diff --git a/cloudtasks/apiv2/cloudtaskspb/target.pb.go b/cloudtasks/apiv2/cloudtaskspb/target.pb.go index 5a013529f435..472b84b55499 100644 --- a/cloudtasks/apiv2/cloudtaskspb/target.pb.go +++ b/cloudtasks/apiv2/cloudtaskspb/target.pb.go @@ -15,8 +15,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/tasks/v2/target.proto package cloudtaskspb @@ -166,19 +166,18 @@ type HttpRequest struct { // // A partial list of headers that will be ignored or replaced is: // - // - Host: This will be computed by Cloud Tasks and derived from - // [HttpRequest.url][google.cloud.tasks.v2.HttpRequest.url]. - // - Content-Length: This will be computed by Cloud Tasks. - // - User-Agent: This will be set to `"Google-Cloud-Tasks"`. - // - `X-Google-*`: Google use only. - // - `X-AppEngine-*`: Google use only. + // * Host: This will be computed by Cloud Tasks and derived from + // [HttpRequest.url][google.cloud.tasks.v2.HttpRequest.url]. + // * Content-Length: This will be computed by Cloud Tasks. + // * User-Agent: This will be set to `"Google-Cloud-Tasks"`. + // * `X-Google-*`: Google use only. + // * `X-AppEngine-*`: Google use only. // // `Content-Type` won't be set by Cloud Tasks. You can explicitly set // `Content-Type` to a media type when the - // - // [task is created][google.cloud.tasks.v2beta3.CloudTasks.CreateTask]. - // For example, `Content-Type` can be set to `"application/octet-stream"` or - // `"application/json"`. + // [task is created][google.cloud.tasks.v2beta3.CloudTasks.CreateTask]. + // For example, `Content-Type` can be set to `"application/octet-stream"` or + // `"application/json"`. // // Headers which can have multiple values (according to RFC2616) can be // specified using comma-separated values. @@ -197,7 +196,6 @@ type HttpRequest struct { // field will be overridden. // // Types that are assignable to AuthorizationHeader: - // // *HttpRequest_OauthToken // *HttpRequest_OidcToken AuthorizationHeader isHttpRequest_AuthorizationHeader `protobuf_oneof:"authorization_header"` @@ -393,10 +391,10 @@ type AppEngineHttpRequest struct { HttpMethod HttpMethod `protobuf:"varint,1,opt,name=http_method,json=httpMethod,proto3,enum=google.cloud.tasks.v2.HttpMethod" json:"http_method,omitempty"` // Task-level setting for App Engine routing. // - // - If [app_engine_routing_override is set on the - // queue][Queue.app_engine_routing_override], this value is used for all - // tasks in the queue, no matter what the setting is for the [task-level - // app_engine_routing][AppEngineHttpRequest.app_engine_routing]. + // * If [app_engine_routing_override is set on the + // queue][Queue.app_engine_routing_override], this value is used for all + // tasks in the queue, no matter what the setting is for the [task-level + // app_engine_routing][AppEngineHttpRequest.app_engine_routing]. AppEngineRouting *AppEngineRouting `protobuf:"bytes,2,opt,name=app_engine_routing,json=appEngineRouting,proto3" json:"app_engine_routing,omitempty"` // The relative URI. // @@ -414,22 +412,22 @@ type AppEngineHttpRequest struct { // // Cloud Tasks sets some headers to default values: // - // - `User-Agent`: By default, this header is - // `"AppEngine-Google; (+http://code.google.com/appengine)"`. - // This header can be modified, but Cloud Tasks will append - // `"AppEngine-Google; (+http://code.google.com/appengine)"` to the - // modified `User-Agent`. + // * `User-Agent`: By default, this header is + // `"AppEngine-Google; (+http://code.google.com/appengine)"`. + // This header can be modified, but Cloud Tasks will append + // `"AppEngine-Google; (+http://code.google.com/appengine)"` to the + // modified `User-Agent`. // // If the task has a [body][google.cloud.tasks.v2.AppEngineHttpRequest.body], Cloud // Tasks sets the following headers: // - // - `Content-Type`: By default, the `Content-Type` header is set to - // `"application/octet-stream"`. The default can be overridden by explicitly - // setting `Content-Type` to a particular media type when the - // [task is created][google.cloud.tasks.v2.CloudTasks.CreateTask]. - // For example, `Content-Type` can be set to `"application/json"`. - // - `Content-Length`: This is computed by Cloud Tasks. This value is - // output only. It cannot be changed. + // * `Content-Type`: By default, the `Content-Type` header is set to + // `"application/octet-stream"`. The default can be overridden by explicitly + // setting `Content-Type` to a particular media type when the + // [task is created][google.cloud.tasks.v2.CloudTasks.CreateTask]. + // For example, `Content-Type` can be set to `"application/json"`. + // * `Content-Length`: This is computed by Cloud Tasks. This value is + // output only. It cannot be changed. // // The headers below cannot be set or overridden: // diff --git a/cloudtasks/apiv2/cloudtaskspb/task.pb.go b/cloudtasks/apiv2/cloudtaskspb/task.pb.go index 7cc4e80e7e4f..f5afadd290e2 100644 --- a/cloudtasks/apiv2/cloudtaskspb/task.pb.go +++ b/cloudtasks/apiv2/cloudtaskspb/task.pb.go @@ -15,8 +15,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/tasks/v2/task.proto package cloudtaskspb @@ -123,24 +123,23 @@ type Task struct { // The task name must have the following format: // `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID` // - // - `PROJECT_ID` can contain letters ([A-Za-z]), numbers ([0-9]), - // hyphens (-), colons (:), or periods (.). - // For more information, see - // [Identifying - // projects](https://cloud.google.com/resource-manager/docs/creating-managing-projects#identifying_projects) - // - `LOCATION_ID` is the canonical ID for the task's location. - // The list of available locations can be obtained by calling - // [ListLocations][google.cloud.location.Locations.ListLocations]. - // For more information, see https://cloud.google.com/about/locations/. - // - `QUEUE_ID` can contain letters ([A-Za-z]), numbers ([0-9]), or - // hyphens (-). The maximum length is 100 characters. - // - `TASK_ID` can contain only letters ([A-Za-z]), numbers ([0-9]), - // hyphens (-), or underscores (_). The maximum length is 500 characters. + // * `PROJECT_ID` can contain letters ([A-Za-z]), numbers ([0-9]), + // hyphens (-), colons (:), or periods (.). + // For more information, see + // [Identifying + // projects](https://cloud.google.com/resource-manager/docs/creating-managing-projects#identifying_projects) + // * `LOCATION_ID` is the canonical ID for the task's location. + // The list of available locations can be obtained by calling + // [ListLocations][google.cloud.location.Locations.ListLocations]. + // For more information, see https://cloud.google.com/about/locations/. + // * `QUEUE_ID` can contain letters ([A-Za-z]), numbers ([0-9]), or + // hyphens (-). The maximum length is 100 characters. + // * `TASK_ID` can contain only letters ([A-Za-z]), numbers ([0-9]), + // hyphens (-), or underscores (_). The maximum length is 500 characters. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Required. The message to send to the worker. // // Types that are assignable to MessageType: - // // *Task_AppEngineHttpRequest // *Task_HttpRequest MessageType isTask_MessageType `protobuf_oneof:"message_type"` @@ -164,22 +163,22 @@ type Task struct { // // The default and maximum values depend on the type of request: // - // - For [HTTP tasks][google.cloud.tasks.v2.HttpRequest], the default is 10 minutes. The deadline - // must be in the interval [15 seconds, 30 minutes]. + // * For [HTTP tasks][google.cloud.tasks.v2.HttpRequest], the default is 10 minutes. The deadline + // must be in the interval [15 seconds, 30 minutes]. // - // - For [App Engine tasks][google.cloud.tasks.v2.AppEngineHttpRequest], 0 indicates that the - // request has the default deadline. The default deadline depends on the - // [scaling - // type](https://cloud.google.com/appengine/docs/standard/go/how-instances-are-managed#instance_scaling) - // of the service: 10 minutes for standard apps with automatic scaling, 24 - // hours for standard apps with manual and basic scaling, and 60 minutes for - // flex apps. If the request deadline is set, it must be in the interval [15 - // seconds, 24 hours 15 seconds]. Regardless of the task's - // `dispatch_deadline`, the app handler will not run for longer than than - // the service's timeout. We recommend setting the `dispatch_deadline` to - // at most a few seconds more than the app handler's timeout. For more - // information see - // [Timeouts](https://cloud.google.com/tasks/docs/creating-appengine-handlers#timeouts). + // * For [App Engine tasks][google.cloud.tasks.v2.AppEngineHttpRequest], 0 indicates that the + // request has the default deadline. The default deadline depends on the + // [scaling + // type](https://cloud.google.com/appengine/docs/standard/go/how-instances-are-managed#instance_scaling) + // of the service: 10 minutes for standard apps with automatic scaling, 24 + // hours for standard apps with manual and basic scaling, and 60 minutes for + // flex apps. If the request deadline is set, it must be in the interval [15 + // seconds, 24 hours 15 seconds]. Regardless of the task's + // `dispatch_deadline`, the app handler will not run for longer than than + // the service's timeout. We recommend setting the `dispatch_deadline` to + // at most a few seconds more than the app handler's timeout. For more + // information see + // [Timeouts](https://cloud.google.com/tasks/docs/creating-appengine-handlers#timeouts). // // `dispatch_deadline` will be truncated to the nearest millisecond. The // deadline is an approximate deadline. diff --git a/cloudtasks/apiv2/doc.go b/cloudtasks/apiv2/doc.go index dfb04f4322e1..bf41868230e1 100644 --- a/cloudtasks/apiv2/doc.go +++ b/cloudtasks/apiv2/doc.go @@ -86,6 +86,8 @@ package cloudtasks // import "cloud.google.com/go/cloudtasks/apiv2" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -174,3 +176,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/cloudtasks/apiv2/gapic_metadata.json b/cloudtasks/apiv2/gapic_metadata.json index ade36c0dc6fe..dfabbe4280cd 100644 --- a/cloudtasks/apiv2/gapic_metadata.json +++ b/cloudtasks/apiv2/gapic_metadata.json @@ -91,6 +91,91 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "CreateQueue": { + "methods": [ + "CreateQueue" + ] + }, + "CreateTask": { + "methods": [ + "CreateTask" + ] + }, + "DeleteQueue": { + "methods": [ + "DeleteQueue" + ] + }, + "DeleteTask": { + "methods": [ + "DeleteTask" + ] + }, + "GetIamPolicy": { + "methods": [ + "GetIamPolicy" + ] + }, + "GetQueue": { + "methods": [ + "GetQueue" + ] + }, + "GetTask": { + "methods": [ + "GetTask" + ] + }, + "ListQueues": { + "methods": [ + "ListQueues" + ] + }, + "ListTasks": { + "methods": [ + "ListTasks" + ] + }, + "PauseQueue": { + "methods": [ + "PauseQueue" + ] + }, + "PurgeQueue": { + "methods": [ + "PurgeQueue" + ] + }, + "ResumeQueue": { + "methods": [ + "ResumeQueue" + ] + }, + "RunTask": { + "methods": [ + "RunTask" + ] + }, + "SetIamPolicy": { + "methods": [ + "SetIamPolicy" + ] + }, + "TestIamPermissions": { + "methods": [ + "TestIamPermissions" + ] + }, + "UpdateQueue": { + "methods": [ + "UpdateQueue" + ] + } + } } } } diff --git a/cloudtasks/apiv2beta2/cloud_tasks_client.go b/cloudtasks/apiv2beta2/cloud_tasks_client.go index 5a4f9021ff8f..92e52bb11d80 100644 --- a/cloudtasks/apiv2beta2/cloud_tasks_client.go +++ b/cloudtasks/apiv2beta2/cloud_tasks_client.go @@ -1283,6 +1283,7 @@ func (c *restClient) ListQueues(ctx context.Context, req *cloudtaskspb.ListQueue baseUrl.Path += fmt.Sprintf("/v2beta2/%v/queues", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1367,6 +1368,7 @@ func (c *restClient) GetQueue(ctx context.Context, req *cloudtaskspb.GetQueueReq baseUrl.Path += fmt.Sprintf("/v2beta2/%v", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetReadMask() != nil { readMask, err := protojson.Marshal(req.GetReadMask()) if err != nil { @@ -1448,6 +1450,11 @@ func (c *restClient) CreateQueue(ctx context.Context, req *cloudtaskspb.CreateQu } baseUrl.Path += fmt.Sprintf("/v2beta2/%v/queues", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1523,6 +1530,7 @@ func (c *restClient) UpdateQueue(ctx context.Context, req *cloudtaskspb.UpdateQu baseUrl.Path += fmt.Sprintf("/v2beta2/%v", req.GetQueue().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -1598,6 +1606,11 @@ func (c *restClient) DeleteQueue(ctx context.Context, req *cloudtaskspb.DeleteQu } baseUrl.Path += fmt.Sprintf("/v2beta2/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1644,6 +1657,11 @@ func (c *restClient) PurgeQueue(ctx context.Context, req *cloudtaskspb.PurgeQueu } baseUrl.Path += fmt.Sprintf("/v2beta2/%v:purge", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1709,6 +1727,11 @@ func (c *restClient) PauseQueue(ctx context.Context, req *cloudtaskspb.PauseQueu } baseUrl.Path += fmt.Sprintf("/v2beta2/%v:pause", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1780,6 +1803,11 @@ func (c *restClient) ResumeQueue(ctx context.Context, req *cloudtaskspb.ResumeQu } baseUrl.Path += fmt.Sprintf("/v2beta2/%v:resume", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1847,6 +1875,11 @@ func (c *restClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRe } baseUrl.Path += fmt.Sprintf("/v2beta2/%v:getIamPolicy", req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) @@ -1916,6 +1949,11 @@ func (c *restClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRe } baseUrl.Path += fmt.Sprintf("/v2beta2/%v:setIamPolicy", req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) @@ -1981,6 +2019,11 @@ func (c *restClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamP } baseUrl.Path += fmt.Sprintf("/v2beta2/%v:testIamPermissions", req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) @@ -2056,6 +2099,7 @@ func (c *restClient) ListTasks(ctx context.Context, req *cloudtaskspb.ListTasksR baseUrl.Path += fmt.Sprintf("/v2beta2/%v/tasks", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -2133,6 +2177,7 @@ func (c *restClient) GetTask(ctx context.Context, req *cloudtaskspb.GetTaskReque baseUrl.Path += fmt.Sprintf("/v2beta2/%v", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetResponseView() != 0 { params.Add("responseView", fmt.Sprintf("%v", req.GetResponseView())) } @@ -2205,6 +2250,11 @@ func (c *restClient) CreateTask(ctx context.Context, req *cloudtaskspb.CreateTas } baseUrl.Path += fmt.Sprintf("/v2beta2/%v/tasks", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -2262,6 +2312,11 @@ func (c *restClient) DeleteTask(ctx context.Context, req *cloudtaskspb.DeleteTas } baseUrl.Path += fmt.Sprintf("/v2beta2/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2324,6 +2379,11 @@ func (c *restClient) LeaseTasks(ctx context.Context, req *cloudtaskspb.LeaseTask } baseUrl.Path += fmt.Sprintf("/v2beta2/%v/tasks:lease", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -2395,6 +2455,11 @@ func (c *restClient) AcknowledgeTask(ctx context.Context, req *cloudtaskspb.Ackn } baseUrl.Path += fmt.Sprintf("/v2beta2/%v:acknowledge", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2440,6 +2505,11 @@ func (c *restClient) RenewLease(ctx context.Context, req *cloudtaskspb.RenewLeas } baseUrl.Path += fmt.Sprintf("/v2beta2/%v:renewLease", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2504,6 +2574,11 @@ func (c *restClient) CancelLease(ctx context.Context, req *cloudtaskspb.CancelLe } baseUrl.Path += fmt.Sprintf("/v2beta2/%v:cancelLease", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2589,6 +2664,11 @@ func (c *restClient) RunTask(ctx context.Context, req *cloudtaskspb.RunTaskReque } baseUrl.Path += fmt.Sprintf("/v2beta2/%v:run", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) diff --git a/cloudtasks/apiv2beta2/cloudtaskspb/cloudtasks.pb.go b/cloudtasks/apiv2beta2/cloudtaskspb/cloudtasks.pb.go index 9589048a57ea..19da2f7acf9f 100644 --- a/cloudtasks/apiv2beta2/cloudtaskspb/cloudtasks.pb.go +++ b/cloudtasks/apiv2beta2/cloudtaskspb/cloudtasks.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/tasks/v2beta2/cloudtasks.proto package cloudtaskspb @@ -1046,6 +1046,7 @@ type LeaseTasksRequest struct { // returned to another [LeaseTasks][google.cloud.tasks.v2beta2.CloudTasks.LeaseTasks] call // before its [schedule_time][google.cloud.tasks.v2beta2.Task.schedule_time]. // + // // After the worker has successfully finished the work associated // with the task, the worker must call via // [AcknowledgeTask][google.cloud.tasks.v2beta2.CloudTasks.AcknowledgeTask] before the @@ -1299,6 +1300,7 @@ type RenewLeaseRequest struct { ScheduleTime *timestamppb.Timestamp `protobuf:"bytes,2,opt,name=schedule_time,json=scheduleTime,proto3" json:"schedule_time,omitempty"` // Required. The desired new lease duration, starting from now. // + // // The maximum lease duration is 1 week. // `lease_duration` will be truncated to the nearest second. LeaseDuration *durationpb.Duration `protobuf:"bytes,3,opt,name=lease_duration,json=leaseDuration,proto3" json:"lease_duration,omitempty"` @@ -2520,9 +2522,9 @@ type CloudTasksClient interface { // // Tasks cannot be updated after creation; there is no UpdateTask command. // - // - For [App Engine queues][google.cloud.tasks.v2beta2.AppEngineHttpTarget], the maximum task size is - // 100KB. - // - For [pull queues][google.cloud.tasks.v2beta2.PullTarget], the maximum task size is 1MB. + // * For [App Engine queues][google.cloud.tasks.v2beta2.AppEngineHttpTarget], the maximum task size is + // 100KB. + // * For [pull queues][google.cloud.tasks.v2beta2.PullTarget], the maximum task size is 1MB. CreateTask(ctx context.Context, in *CreateTaskRequest, opts ...grpc.CallOption) (*Task, error) // Deletes a task. // @@ -2924,9 +2926,9 @@ type CloudTasksServer interface { // // Tasks cannot be updated after creation; there is no UpdateTask command. // - // - For [App Engine queues][google.cloud.tasks.v2beta2.AppEngineHttpTarget], the maximum task size is - // 100KB. - // - For [pull queues][google.cloud.tasks.v2beta2.PullTarget], the maximum task size is 1MB. + // * For [App Engine queues][google.cloud.tasks.v2beta2.AppEngineHttpTarget], the maximum task size is + // 100KB. + // * For [pull queues][google.cloud.tasks.v2beta2.PullTarget], the maximum task size is 1MB. CreateTask(context.Context, *CreateTaskRequest) (*Task, error) // Deletes a task. // diff --git a/cloudtasks/apiv2beta2/cloudtaskspb/old_target.pb.go b/cloudtasks/apiv2beta2/cloudtaskspb/old_target.pb.go index 9fdbff8b8d18..efadc3d25178 100644 --- a/cloudtasks/apiv2beta2/cloudtaskspb/old_target.pb.go +++ b/cloudtasks/apiv2beta2/cloudtaskspb/old_target.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/tasks/v2beta2/old_target.proto package cloudtaskspb diff --git a/cloudtasks/apiv2beta2/cloudtaskspb/queue.pb.go b/cloudtasks/apiv2beta2/cloudtaskspb/queue.pb.go index 14537a156aae..fcd2b6af3b0e 100644 --- a/cloudtasks/apiv2beta2/cloudtaskspb/queue.pb.go +++ b/cloudtasks/apiv2beta2/cloudtaskspb/queue.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/tasks/v2beta2/queue.proto package cloudtaskspb @@ -137,17 +137,17 @@ type Queue struct { // The queue name must have the following format: // `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID` // - // - `PROJECT_ID` can contain letters ([A-Za-z]), numbers ([0-9]), - // hyphens (-), colons (:), or periods (.). - // For more information, see - // [Identifying - // projects](https://cloud.google.com/resource-manager/docs/creating-managing-projects#identifying_projects) - // - `LOCATION_ID` is the canonical ID for the queue's location. - // The list of available locations can be obtained by calling - // [ListLocations][google.cloud.location.Locations.ListLocations]. - // For more information, see https://cloud.google.com/about/locations/. - // - `QUEUE_ID` can contain letters ([A-Za-z]), numbers ([0-9]), or - // hyphens (-). The maximum length is 100 characters. + // * `PROJECT_ID` can contain letters ([A-Za-z]), numbers ([0-9]), + // hyphens (-), colons (:), or periods (.). + // For more information, see + // [Identifying + // projects](https://cloud.google.com/resource-manager/docs/creating-managing-projects#identifying_projects) + // * `LOCATION_ID` is the canonical ID for the queue's location. + // The list of available locations can be obtained by calling + // [ListLocations][google.cloud.location.Locations.ListLocations]. + // For more information, see https://cloud.google.com/about/locations/. + // * `QUEUE_ID` can contain letters ([A-Za-z]), numbers ([0-9]), or + // hyphens (-). The maximum length is 100 characters. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Caller-specified and required in [CreateQueue][google.cloud.tasks.v2beta2.CloudTasks.CreateQueue][], // after which the queue config type becomes output only, though fields within @@ -158,7 +158,6 @@ type Queue struct { // The target applies to all tasks in the queue. // // Types that are assignable to TargetType: - // // *Queue_AppEngineHttpTarget // *Queue_PullTarget TargetType isQueue_TargetType `protobuf_oneof:"target_type"` @@ -169,25 +168,25 @@ type Queue struct { // control task attempts however they control how tasks are // attempted in different ways: // - // - [rate_limits][google.cloud.tasks.v2beta2.Queue.rate_limits] controls the total rate of - // dispatches from a queue (i.e. all traffic dispatched from the - // queue, regardless of whether the dispatch is from a first - // attempt or a retry). - // - [retry_config][google.cloud.tasks.v2beta2.Queue.retry_config] controls what happens to - // particular a task after its first attempt fails. That is, - // [retry_config][google.cloud.tasks.v2beta2.Queue.retry_config] controls task retries (the - // second attempt, third attempt, etc). + // * [rate_limits][google.cloud.tasks.v2beta2.Queue.rate_limits] controls the total rate of + // dispatches from a queue (i.e. all traffic dispatched from the + // queue, regardless of whether the dispatch is from a first + // attempt or a retry). + // * [retry_config][google.cloud.tasks.v2beta2.Queue.retry_config] controls what happens to + // particular a task after its first attempt fails. That is, + // [retry_config][google.cloud.tasks.v2beta2.Queue.retry_config] controls task retries (the + // second attempt, third attempt, etc). RateLimits *RateLimits `protobuf:"bytes,5,opt,name=rate_limits,json=rateLimits,proto3" json:"rate_limits,omitempty"` // Settings that determine the retry behavior. // - // - For tasks created using Cloud Tasks: the queue-level retry settings - // apply to all tasks in the queue that were created using Cloud Tasks. - // Retry settings cannot be set on individual tasks. - // - For tasks created using the App Engine SDK: the queue-level retry - // settings apply to all tasks in the queue which do not have retry settings - // explicitly set on the task and were created by the App Engine SDK. See - // [App Engine - // documentation](https://cloud.google.com/appengine/docs/standard/python/taskqueue/push/retrying-tasks). + // * For tasks created using Cloud Tasks: the queue-level retry settings + // apply to all tasks in the queue that were created using Cloud Tasks. + // Retry settings cannot be set on individual tasks. + // * For tasks created using the App Engine SDK: the queue-level retry + // settings apply to all tasks in the queue which do not have retry settings + // explicitly set on the task and were created by the App Engine SDK. See + // [App Engine + // documentation](https://cloud.google.com/appengine/docs/standard/python/taskqueue/push/retrying-tasks). RetryConfig *RetryConfig `protobuf:"bytes,6,opt,name=retry_config,json=retryConfig,proto3" json:"retry_config,omitempty"` // Output only. The state of the queue. // @@ -387,11 +386,12 @@ type RateLimits struct { // If unspecified when the queue is created, Cloud Tasks will pick the // default. // - // - For [App Engine queues][google.cloud.tasks.v2beta2.AppEngineHttpTarget], the maximum allowed value - // is 500. - // - This field is output only for [pull queues][google.cloud.tasks.v2beta2.PullTarget]. In addition to the - // `max_tasks_dispatched_per_second` limit, a maximum of 10 QPS of - // [LeaseTasks][google.cloud.tasks.v2beta2.CloudTasks.LeaseTasks] requests are allowed per pull queue. + // * For [App Engine queues][google.cloud.tasks.v2beta2.AppEngineHttpTarget], the maximum allowed value + // is 500. + // * This field is output only for [pull queues][google.cloud.tasks.v2beta2.PullTarget]. In addition to the + // `max_tasks_dispatched_per_second` limit, a maximum of 10 QPS of + // [LeaseTasks][google.cloud.tasks.v2beta2.CloudTasks.LeaseTasks] requests are allowed per pull queue. + // // // This field has the same meaning as // [rate in @@ -429,6 +429,7 @@ type RateLimits struct { // `max_burst_size` value will get updated if // [UpdateQueue][google.cloud.tasks.v2beta2.CloudTasks.UpdateQueue] is updating // [max_dispatches_per_second][RateLimits.max_dispatches_per_second]. + // MaxBurstSize int32 `protobuf:"varint,2,opt,name=max_burst_size,json=maxBurstSize,proto3" json:"max_burst_size,omitempty"` // The maximum number of concurrent tasks that Cloud Tasks allows // to be dispatched for this queue. After this threshold has been @@ -438,12 +439,14 @@ type RateLimits struct { // If unspecified when the queue is created, Cloud Tasks will pick the // default. // + // // The maximum allowed value is 5,000. // // This field is output only for // [pull queues][google.cloud.tasks.v2beta2.PullTarget] and always -1, which indicates no limit. No other // queue types can have `max_concurrent_tasks` set to -1. // + // // This field has the same meaning as // [max_concurrent_requests in // queue.yaml/xml](https://cloud.google.com/appengine/docs/standard/python/config/queueref#max_concurrent_requests). @@ -516,12 +519,13 @@ type RetryConfig struct { // If unspecified when the queue is created, Cloud Tasks will pick the // default. // + // + // // This field has the same meaning as // [task_retry_limit in // queue.yaml/xml](https://cloud.google.com/appengine/docs/standard/python/config/queueref#retry_parameters). // // Types that are assignable to NumAttempts: - // // *RetryConfig_MaxAttempts // *RetryConfig_UnlimitedAttempts NumAttempts isRetryConfig_NumAttempts `protobuf_oneof:"num_attempts"` @@ -539,6 +543,7 @@ type RetryConfig struct { // // This field is output only for [pull queues][google.cloud.tasks.v2beta2.PullTarget]. // + // // `max_retry_duration` will be truncated to the nearest second. // // This field has the same meaning as @@ -556,6 +561,7 @@ type RetryConfig struct { // // This field is output only for [pull queues][google.cloud.tasks.v2beta2.PullTarget]. // + // // `min_backoff` will be truncated to the nearest second. // // This field has the same meaning as @@ -573,6 +579,7 @@ type RetryConfig struct { // // This field is output only for [pull queues][google.cloud.tasks.v2beta2.PullTarget]. // + // // `max_backoff` will be truncated to the nearest second. // // This field has the same meaning as @@ -603,6 +610,7 @@ type RetryConfig struct { // // This field is output only for [pull queues][google.cloud.tasks.v2beta2.PullTarget]. // + // // This field has the same meaning as // [max_doublings in // queue.yaml/xml](https://cloud.google.com/appengine/docs/standard/python/config/queueref#retry_parameters). diff --git a/cloudtasks/apiv2beta2/cloudtaskspb/target.pb.go b/cloudtasks/apiv2beta2/cloudtaskspb/target.pb.go index ff2b1eab6d72..f6ee87cb9077 100644 --- a/cloudtasks/apiv2beta2/cloudtaskspb/target.pb.go +++ b/cloudtasks/apiv2beta2/cloudtaskspb/target.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/tasks/v2beta2/target.proto package cloudtaskspb @@ -385,22 +385,22 @@ type AppEngineHttpRequest struct { // // Cloud Tasks sets some headers to default values: // - // - `User-Agent`: By default, this header is - // `"AppEngine-Google; (+http://code.google.com/appengine)"`. - // This header can be modified, but Cloud Tasks will append - // `"AppEngine-Google; (+http://code.google.com/appengine)"` to the - // modified `User-Agent`. + // * `User-Agent`: By default, this header is + // `"AppEngine-Google; (+http://code.google.com/appengine)"`. + // This header can be modified, but Cloud Tasks will append + // `"AppEngine-Google; (+http://code.google.com/appengine)"` to the + // modified `User-Agent`. // // If the task has a [payload][google.cloud.tasks.v2beta2.AppEngineHttpRequest.payload], Cloud // Tasks sets the following headers: // - // - `Content-Type`: By default, the `Content-Type` header is set to - // `"application/octet-stream"`. The default can be overridden by explicitly - // setting `Content-Type` to a particular media type when the - // [task is created][google.cloud.tasks.v2beta2.CloudTasks.CreateTask]. - // For example, `Content-Type` can be set to `"application/json"`. - // - `Content-Length`: This is computed by Cloud Tasks. This value is - // output only. It cannot be changed. + // * `Content-Type`: By default, the `Content-Type` header is set to + // `"application/octet-stream"`. The default can be overridden by explicitly + // setting `Content-Type` to a particular media type when the + // [task is created][google.cloud.tasks.v2beta2.CloudTasks.CreateTask]. + // For example, `Content-Type` can be set to `"application/json"`. + // * `Content-Length`: This is computed by Cloud Tasks. This value is + // output only. It cannot be changed. // // The headers below cannot be set or overridden: // @@ -570,42 +570,43 @@ type AppEngineRouting struct { // // The host is constructed as: // - // - `host = [application_domain_name]`
- // `| [service] + '.' + [application_domain_name]`
- // `| [version] + '.' + [application_domain_name]`
- // `| [version_dot_service]+ '.' + [application_domain_name]`
- // `| [instance] + '.' + [application_domain_name]`
- // `| [instance_dot_service] + '.' + [application_domain_name]`
- // `| [instance_dot_version] + '.' + [application_domain_name]`
- // `| [instance_dot_version_dot_service] + '.' + [application_domain_name]` // - // - `application_domain_name` = The domain name of the app, for - // example .appspot.com, which is associated with the - // queue's project ID. Some tasks which were created using the App Engine - // SDK use a custom domain name. + // * `host = [application_domain_name]`
+ // `| [service] + '.' + [application_domain_name]`
+ // `| [version] + '.' + [application_domain_name]`
+ // `| [version_dot_service]+ '.' + [application_domain_name]`
+ // `| [instance] + '.' + [application_domain_name]`
+ // `| [instance_dot_service] + '.' + [application_domain_name]`
+ // `| [instance_dot_version] + '.' + [application_domain_name]`
+ // `| [instance_dot_version_dot_service] + '.' + [application_domain_name]` + // + // * `application_domain_name` = The domain name of the app, for + // example .appspot.com, which is associated with the + // queue's project ID. Some tasks which were created using the App Engine + // SDK use a custom domain name. // // * `service =` [service][google.cloud.tasks.v2beta2.AppEngineRouting.service] // // * `version =` [version][google.cloud.tasks.v2beta2.AppEngineRouting.version] // - // - `version_dot_service =` - // [version][google.cloud.tasks.v2beta2.AppEngineRouting.version] `+ '.' +` - // [service][google.cloud.tasks.v2beta2.AppEngineRouting.service] + // * `version_dot_service =` + // [version][google.cloud.tasks.v2beta2.AppEngineRouting.version] `+ '.' +` + // [service][google.cloud.tasks.v2beta2.AppEngineRouting.service] // // * `instance =` [instance][google.cloud.tasks.v2beta2.AppEngineRouting.instance] // - // - `instance_dot_service =` - // [instance][google.cloud.tasks.v2beta2.AppEngineRouting.instance] `+ '.' +` - // [service][google.cloud.tasks.v2beta2.AppEngineRouting.service] + // * `instance_dot_service =` + // [instance][google.cloud.tasks.v2beta2.AppEngineRouting.instance] `+ '.' +` + // [service][google.cloud.tasks.v2beta2.AppEngineRouting.service] // - // - `instance_dot_version =` - // [instance][google.cloud.tasks.v2beta2.AppEngineRouting.instance] `+ '.' +` - // [version][google.cloud.tasks.v2beta2.AppEngineRouting.version] + // * `instance_dot_version =` + // [instance][google.cloud.tasks.v2beta2.AppEngineRouting.instance] `+ '.' +` + // [version][google.cloud.tasks.v2beta2.AppEngineRouting.version] // - // - `instance_dot_version_dot_service =` - // [instance][google.cloud.tasks.v2beta2.AppEngineRouting.instance] `+ '.' +` - // [version][google.cloud.tasks.v2beta2.AppEngineRouting.version] `+ '.' +` - // [service][google.cloud.tasks.v2beta2.AppEngineRouting.service] + // * `instance_dot_version_dot_service =` + // [instance][google.cloud.tasks.v2beta2.AppEngineRouting.instance] `+ '.' +` + // [version][google.cloud.tasks.v2beta2.AppEngineRouting.version] `+ '.' +` + // [service][google.cloud.tasks.v2beta2.AppEngineRouting.service] // // If [service][google.cloud.tasks.v2beta2.AppEngineRouting.service] is empty, then the task will be sent // to the service which is the default service when the task is attempted. diff --git a/cloudtasks/apiv2beta2/cloudtaskspb/task.pb.go b/cloudtasks/apiv2beta2/cloudtaskspb/task.pb.go index 0c779513732a..5af202db4c5c 100644 --- a/cloudtasks/apiv2beta2/cloudtaskspb/task.pb.go +++ b/cloudtasks/apiv2beta2/cloudtaskspb/task.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/tasks/v2beta2/task.proto package cloudtaskspb @@ -122,19 +122,19 @@ type Task struct { // The task name must have the following format: // `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID` // - // - `PROJECT_ID` can contain letters ([A-Za-z]), numbers ([0-9]), - // hyphens (-), colons (:), or periods (.). - // For more information, see - // [Identifying - // projects](https://cloud.google.com/resource-manager/docs/creating-managing-projects#identifying_projects) - // - `LOCATION_ID` is the canonical ID for the task's location. - // The list of available locations can be obtained by calling - // [ListLocations][google.cloud.location.Locations.ListLocations]. - // For more information, see https://cloud.google.com/about/locations/. - // - `QUEUE_ID` can contain letters ([A-Za-z]), numbers ([0-9]), or - // hyphens (-). The maximum length is 100 characters. - // - `TASK_ID` can contain only letters ([A-Za-z]), numbers ([0-9]), - // hyphens (-), or underscores (_). The maximum length is 500 characters. + // * `PROJECT_ID` can contain letters ([A-Za-z]), numbers ([0-9]), + // hyphens (-), colons (:), or periods (.). + // For more information, see + // [Identifying + // projects](https://cloud.google.com/resource-manager/docs/creating-managing-projects#identifying_projects) + // * `LOCATION_ID` is the canonical ID for the task's location. + // The list of available locations can be obtained by calling + // [ListLocations][google.cloud.location.Locations.ListLocations]. + // For more information, see https://cloud.google.com/about/locations/. + // * `QUEUE_ID` can contain letters ([A-Za-z]), numbers ([0-9]), or + // hyphens (-). The maximum length is 100 characters. + // * `TASK_ID` can contain only letters ([A-Za-z]), numbers ([0-9]), + // hyphens (-), or underscores (_). The maximum length is 500 characters. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Required. // @@ -142,7 +142,6 @@ type Task struct { // A payload is valid only if it is compatible with the queue's target. // // Types that are assignable to PayloadType: - // // *Task_AppEngineHttpRequest // *Task_PullMessage PayloadType isTask_PayloadType `protobuf_oneof:"payload_type"` diff --git a/cloudtasks/apiv2beta3/cloud_tasks_client.go b/cloudtasks/apiv2beta3/cloud_tasks_client.go index c5f8671c6617..ea71eac20f35 100644 --- a/cloudtasks/apiv2beta3/cloud_tasks_client.go +++ b/cloudtasks/apiv2beta3/cloud_tasks_client.go @@ -1115,6 +1115,7 @@ func (c *restClient) ListQueues(ctx context.Context, req *cloudtaskspb.ListQueue baseUrl.Path += fmt.Sprintf("/v2beta3/%v/queues", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1199,6 +1200,7 @@ func (c *restClient) GetQueue(ctx context.Context, req *cloudtaskspb.GetQueueReq baseUrl.Path += fmt.Sprintf("/v2beta3/%v", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetReadMask() != nil { readMask, err := protojson.Marshal(req.GetReadMask()) if err != nil { @@ -1280,6 +1282,11 @@ func (c *restClient) CreateQueue(ctx context.Context, req *cloudtaskspb.CreateQu } baseUrl.Path += fmt.Sprintf("/v2beta3/%v/queues", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1355,6 +1362,7 @@ func (c *restClient) UpdateQueue(ctx context.Context, req *cloudtaskspb.UpdateQu baseUrl.Path += fmt.Sprintf("/v2beta3/%v", req.GetQueue().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -1430,6 +1438,11 @@ func (c *restClient) DeleteQueue(ctx context.Context, req *cloudtaskspb.DeleteQu } baseUrl.Path += fmt.Sprintf("/v2beta3/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1476,6 +1489,11 @@ func (c *restClient) PurgeQueue(ctx context.Context, req *cloudtaskspb.PurgeQueu } baseUrl.Path += fmt.Sprintf("/v2beta3/%v:purge", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1541,6 +1559,11 @@ func (c *restClient) PauseQueue(ctx context.Context, req *cloudtaskspb.PauseQueu } baseUrl.Path += fmt.Sprintf("/v2beta3/%v:pause", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1612,6 +1635,11 @@ func (c *restClient) ResumeQueue(ctx context.Context, req *cloudtaskspb.ResumeQu } baseUrl.Path += fmt.Sprintf("/v2beta3/%v:resume", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1679,6 +1707,11 @@ func (c *restClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRe } baseUrl.Path += fmt.Sprintf("/v2beta3/%v:getIamPolicy", req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) @@ -1748,6 +1781,11 @@ func (c *restClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRe } baseUrl.Path += fmt.Sprintf("/v2beta3/%v:setIamPolicy", req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) @@ -1813,6 +1851,11 @@ func (c *restClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamP } baseUrl.Path += fmt.Sprintf("/v2beta3/%v:testIamPermissions", req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) @@ -1888,6 +1931,7 @@ func (c *restClient) ListTasks(ctx context.Context, req *cloudtaskspb.ListTasksR baseUrl.Path += fmt.Sprintf("/v2beta3/%v/tasks", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -1965,6 +2009,7 @@ func (c *restClient) GetTask(ctx context.Context, req *cloudtaskspb.GetTaskReque baseUrl.Path += fmt.Sprintf("/v2beta3/%v", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetResponseView() != 0 { params.Add("responseView", fmt.Sprintf("%v", req.GetResponseView())) } @@ -2034,6 +2079,11 @@ func (c *restClient) CreateTask(ctx context.Context, req *cloudtaskspb.CreateTas } baseUrl.Path += fmt.Sprintf("/v2beta3/%v/tasks", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -2091,6 +2141,11 @@ func (c *restClient) DeleteTask(ctx context.Context, req *cloudtaskspb.DeleteTas } baseUrl.Path += fmt.Sprintf("/v2beta3/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2155,6 +2210,11 @@ func (c *restClient) RunTask(ctx context.Context, req *cloudtaskspb.RunTaskReque } baseUrl.Path += fmt.Sprintf("/v2beta3/%v:run", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) diff --git a/cloudtasks/apiv2beta3/cloudtaskspb/cloudtasks.pb.go b/cloudtasks/apiv2beta3/cloudtaskspb/cloudtasks.pb.go index 0f3a236037f2..cc3ed72dd3c7 100644 --- a/cloudtasks/apiv2beta3/cloudtaskspb/cloudtasks.pb.go +++ b/cloudtasks/apiv2beta3/cloudtaskspb/cloudtasks.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/tasks/v2beta3/cloudtasks.proto package cloudtaskspb diff --git a/cloudtasks/apiv2beta3/cloudtaskspb/queue.pb.go b/cloudtasks/apiv2beta3/cloudtaskspb/queue.pb.go index 90173456c38b..7dd05867f0bb 100644 --- a/cloudtasks/apiv2beta3/cloudtaskspb/queue.pb.go +++ b/cloudtasks/apiv2beta3/cloudtaskspb/queue.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/tasks/v2beta3/queue.proto package cloudtaskspb @@ -186,20 +186,19 @@ type Queue struct { // The queue name must have the following format: // `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID` // - // - `PROJECT_ID` can contain letters ([A-Za-z]), numbers ([0-9]), - // hyphens (-), colons (:), or periods (.). - // For more information, see - // [Identifying - // projects](https://cloud.google.com/resource-manager/docs/creating-managing-projects#identifying_projects) - // - `LOCATION_ID` is the canonical ID for the queue's location. - // The list of available locations can be obtained by calling - // [ListLocations][google.cloud.location.Locations.ListLocations]. - // For more information, see https://cloud.google.com/about/locations/. - // - `QUEUE_ID` can contain letters ([A-Za-z]), numbers ([0-9]), or - // hyphens (-). The maximum length is 100 characters. + // * `PROJECT_ID` can contain letters ([A-Za-z]), numbers ([0-9]), + // hyphens (-), colons (:), or periods (.). + // For more information, see + // [Identifying + // projects](https://cloud.google.com/resource-manager/docs/creating-managing-projects#identifying_projects) + // * `LOCATION_ID` is the canonical ID for the queue's location. + // The list of available locations can be obtained by calling + // [ListLocations][google.cloud.location.Locations.ListLocations]. + // For more information, see https://cloud.google.com/about/locations/. + // * `QUEUE_ID` can contain letters ([A-Za-z]), numbers ([0-9]), or + // hyphens (-). The maximum length is 100 characters. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Types that are assignable to QueueType: - // // *Queue_AppEngineHttpQueue QueueType isQueue_QueueType `protobuf_oneof:"queue_type"` // Rate limits for task dispatches. @@ -208,35 +207,35 @@ type Queue struct { // related because they both control task attempts. However they control task // attempts in different ways: // - // - [rate_limits][google.cloud.tasks.v2beta3.Queue.rate_limits] controls the total rate of - // dispatches from a queue (i.e. all traffic dispatched from the - // queue, regardless of whether the dispatch is from a first - // attempt or a retry). - // - [retry_config][google.cloud.tasks.v2beta3.Queue.retry_config] controls what happens to - // particular a task after its first attempt fails. That is, - // [retry_config][google.cloud.tasks.v2beta3.Queue.retry_config] controls task retries (the - // second attempt, third attempt, etc). + // * [rate_limits][google.cloud.tasks.v2beta3.Queue.rate_limits] controls the total rate of + // dispatches from a queue (i.e. all traffic dispatched from the + // queue, regardless of whether the dispatch is from a first + // attempt or a retry). + // * [retry_config][google.cloud.tasks.v2beta3.Queue.retry_config] controls what happens to + // particular a task after its first attempt fails. That is, + // [retry_config][google.cloud.tasks.v2beta3.Queue.retry_config] controls task retries (the + // second attempt, third attempt, etc). // // The queue's actual dispatch rate is the result of: // - // - Number of tasks in the queue - // - User-specified throttling: [rate_limits][google.cloud.tasks.v2beta3.Queue.rate_limits], - // [retry_config][google.cloud.tasks.v2beta3.Queue.retry_config], and the - // [queue's state][google.cloud.tasks.v2beta3.Queue.state]. - // - System throttling due to `429` (Too Many Requests) or `503` (Service - // Unavailable) responses from the worker, high error rates, or to smooth - // sudden large traffic spikes. + // * Number of tasks in the queue + // * User-specified throttling: [rate_limits][google.cloud.tasks.v2beta3.Queue.rate_limits], + // [retry_config][google.cloud.tasks.v2beta3.Queue.retry_config], and the + // [queue's state][google.cloud.tasks.v2beta3.Queue.state]. + // * System throttling due to `429` (Too Many Requests) or `503` (Service + // Unavailable) responses from the worker, high error rates, or to smooth + // sudden large traffic spikes. RateLimits *RateLimits `protobuf:"bytes,4,opt,name=rate_limits,json=rateLimits,proto3" json:"rate_limits,omitempty"` // Settings that determine the retry behavior. // - // - For tasks created using Cloud Tasks: the queue-level retry settings - // apply to all tasks in the queue that were created using Cloud Tasks. - // Retry settings cannot be set on individual tasks. - // - For tasks created using the App Engine SDK: the queue-level retry - // settings apply to all tasks in the queue which do not have retry settings - // explicitly set on the task and were created by the App Engine SDK. See - // [App Engine - // documentation](https://cloud.google.com/appengine/docs/standard/python/taskqueue/push/retrying-tasks). + // * For tasks created using Cloud Tasks: the queue-level retry settings + // apply to all tasks in the queue that were created using Cloud Tasks. + // Retry settings cannot be set on individual tasks. + // * For tasks created using the App Engine SDK: the queue-level retry + // settings apply to all tasks in the queue which do not have retry settings + // explicitly set on the task and were created by the App Engine SDK. See + // [App Engine + // documentation](https://cloud.google.com/appengine/docs/standard/python/taskqueue/push/retrying-tasks). RetryConfig *RetryConfig `protobuf:"bytes,5,opt,name=retry_config,json=retryConfig,proto3" json:"retry_config,omitempty"` // Output only. The state of the queue. // @@ -444,8 +443,9 @@ type RateLimits struct { // If unspecified when the queue is created, Cloud Tasks will pick the // default. // - // - For [App Engine queues][google.cloud.tasks.v2beta3.AppEngineHttpQueue], the maximum allowed value - // is 500. + // * For [App Engine queues][google.cloud.tasks.v2beta3.AppEngineHttpQueue], the maximum allowed value + // is 500. + // // // This field has the same meaning as // [rate in @@ -483,6 +483,7 @@ type RateLimits struct { // `max_burst_size` value will get updated if // [UpdateQueue][google.cloud.tasks.v2beta3.CloudTasks.UpdateQueue] is updating // [max_dispatches_per_second][google.cloud.tasks.v2beta3.RateLimits.max_dispatches_per_second]. + // MaxBurstSize int32 `protobuf:"varint,2,opt,name=max_burst_size,json=maxBurstSize,proto3" json:"max_burst_size,omitempty"` // The maximum number of concurrent tasks that Cloud Tasks allows // to be dispatched for this queue. After this threshold has been @@ -492,8 +493,10 @@ type RateLimits struct { // If unspecified when the queue is created, Cloud Tasks will pick the // default. // + // // The maximum allowed value is 5,000. // + // // This field has the same meaning as // [max_concurrent_requests in // queue.yaml/xml](https://cloud.google.com/appengine/docs/standard/python/config/queueref#max_concurrent_requests). @@ -588,6 +591,7 @@ type RetryConfig struct { // If unspecified when the queue is created, Cloud Tasks will pick the // default. // + // // `max_retry_duration` will be truncated to the nearest second. // // This field has the same meaning as @@ -603,6 +607,7 @@ type RetryConfig struct { // If unspecified when the queue is created, Cloud Tasks will pick the // default. // + // // `min_backoff` will be truncated to the nearest second. // // This field has the same meaning as @@ -618,6 +623,7 @@ type RetryConfig struct { // If unspecified when the queue is created, Cloud Tasks will pick the // default. // + // // `max_backoff` will be truncated to the nearest second. // // This field has the same meaning as @@ -646,6 +652,7 @@ type RetryConfig struct { // If unspecified when the queue is created, Cloud Tasks will pick the // default. // + // // This field has the same meaning as // [max_doublings in // queue.yaml/xml](https://cloud.google.com/appengine/docs/standard/python/config/queueref#retry_parameters). diff --git a/cloudtasks/apiv2beta3/cloudtaskspb/target.pb.go b/cloudtasks/apiv2beta3/cloudtaskspb/target.pb.go index 7a2cb6af2d35..7b7e9711bd81 100644 --- a/cloudtasks/apiv2beta3/cloudtaskspb/target.pb.go +++ b/cloudtasks/apiv2beta3/cloudtaskspb/target.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/tasks/v2beta3/target.proto package cloudtaskspb @@ -237,19 +237,18 @@ type HttpRequest struct { // // A partial list of headers that will be ignored or replaced is: // - // - Host: This will be computed by Cloud Tasks and derived from - // [HttpRequest.url][google.cloud.tasks.v2beta3.HttpRequest.url]. - // - Content-Length: This will be computed by Cloud Tasks. - // - User-Agent: This will be set to `"Google-Cloud-Tasks"`. - // - `X-Google-*`: Google use only. - // - `X-AppEngine-*`: Google use only. + // * Host: This will be computed by Cloud Tasks and derived from + // [HttpRequest.url][google.cloud.tasks.v2beta3.HttpRequest.url]. + // * Content-Length: This will be computed by Cloud Tasks. + // * User-Agent: This will be set to `"Google-Cloud-Tasks"`. + // * `X-Google-*`: Google use only. + // * `X-AppEngine-*`: Google use only. // // `Content-Type` won't be set by Cloud Tasks. You can explicitly set // `Content-Type` to a media type when the - // - // [task is created][google.cloud.tasks.v2beta3.CloudTasks.CreateTask]. - // For example, `Content-Type` can be set to `"application/octet-stream"` or - // `"application/json"`. + // [task is created][google.cloud.tasks.v2beta3.CloudTasks.CreateTask]. + // For example, `Content-Type` can be set to `"application/octet-stream"` or + // `"application/json"`. // // Headers which can have multiple values (according to RFC2616) can be // specified using comma-separated values. @@ -268,7 +267,6 @@ type HttpRequest struct { // field will be overridden. // // Types that are assignable to AuthorizationHeader: - // // *HttpRequest_OauthToken // *HttpRequest_OidcToken AuthorizationHeader isHttpRequest_AuthorizationHeader `protobuf_oneof:"authorization_header"` @@ -549,22 +547,22 @@ type AppEngineHttpRequest struct { // // Cloud Tasks sets some headers to default values: // - // - `User-Agent`: By default, this header is - // `"AppEngine-Google; (+http://code.google.com/appengine)"`. - // This header can be modified, but Cloud Tasks will append - // `"AppEngine-Google; (+http://code.google.com/appengine)"` to the - // modified `User-Agent`. + // * `User-Agent`: By default, this header is + // `"AppEngine-Google; (+http://code.google.com/appengine)"`. + // This header can be modified, but Cloud Tasks will append + // `"AppEngine-Google; (+http://code.google.com/appengine)"` to the + // modified `User-Agent`. // // If the task has a [body][google.cloud.tasks.v2beta3.AppEngineHttpRequest.body], Cloud // Tasks sets the following headers: // - // - `Content-Type`: By default, the `Content-Type` header is set to - // `"application/octet-stream"`. The default can be overridden by explicitly - // setting `Content-Type` to a particular media type when the - // [task is created][google.cloud.tasks.v2beta3.CloudTasks.CreateTask]. - // For example, `Content-Type` can be set to `"application/json"`. - // - `Content-Length`: This is computed by Cloud Tasks. This value is - // output only. It cannot be changed. + // * `Content-Type`: By default, the `Content-Type` header is set to + // `"application/octet-stream"`. The default can be overridden by explicitly + // setting `Content-Type` to a particular media type when the + // [task is created][google.cloud.tasks.v2beta3.CloudTasks.CreateTask]. + // For example, `Content-Type` can be set to `"application/json"`. + // * `Content-Length`: This is computed by Cloud Tasks. This value is + // output only. It cannot be changed. // // The headers below cannot be set or overridden: // diff --git a/cloudtasks/apiv2beta3/cloudtaskspb/task.pb.go b/cloudtasks/apiv2beta3/cloudtaskspb/task.pb.go index 5f3fb9100039..b6db979192c3 100644 --- a/cloudtasks/apiv2beta3/cloudtaskspb/task.pb.go +++ b/cloudtasks/apiv2beta3/cloudtaskspb/task.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/tasks/v2beta3/task.proto package cloudtaskspb @@ -122,24 +122,23 @@ type Task struct { // The task name must have the following format: // `projects/PROJECT_ID/locations/LOCATION_ID/queues/QUEUE_ID/tasks/TASK_ID` // - // - `PROJECT_ID` can contain letters ([A-Za-z]), numbers ([0-9]), - // hyphens (-), colons (:), or periods (.). - // For more information, see - // [Identifying - // projects](https://cloud.google.com/resource-manager/docs/creating-managing-projects#identifying_projects) - // - `LOCATION_ID` is the canonical ID for the task's location. - // The list of available locations can be obtained by calling - // [ListLocations][google.cloud.location.Locations.ListLocations]. - // For more information, see https://cloud.google.com/about/locations/. - // - `QUEUE_ID` can contain letters ([A-Za-z]), numbers ([0-9]), or - // hyphens (-). The maximum length is 100 characters. - // - `TASK_ID` can contain only letters ([A-Za-z]), numbers ([0-9]), - // hyphens (-), or underscores (_). The maximum length is 500 characters. + // * `PROJECT_ID` can contain letters ([A-Za-z]), numbers ([0-9]), + // hyphens (-), colons (:), or periods (.). + // For more information, see + // [Identifying + // projects](https://cloud.google.com/resource-manager/docs/creating-managing-projects#identifying_projects) + // * `LOCATION_ID` is the canonical ID for the task's location. + // The list of available locations can be obtained by calling + // [ListLocations][google.cloud.location.Locations.ListLocations]. + // For more information, see https://cloud.google.com/about/locations/. + // * `QUEUE_ID` can contain letters ([A-Za-z]), numbers ([0-9]), or + // hyphens (-). The maximum length is 100 characters. + // * `TASK_ID` can contain only letters ([A-Za-z]), numbers ([0-9]), + // hyphens (-), or underscores (_). The maximum length is 500 characters. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Required. The message to send to the worker. // // Types that are assignable to PayloadType: - // // *Task_AppEngineHttpRequest // *Task_HttpRequest // *Task_PullMessage @@ -166,22 +165,22 @@ type Task struct { // // The default and maximum values depend on the type of request: // - // - For [HTTP tasks][google.cloud.tasks.v2beta3.HttpRequest], the default is 10 minutes. The deadline - // must be in the interval [15 seconds, 30 minutes]. + // * For [HTTP tasks][google.cloud.tasks.v2beta3.HttpRequest], the default is 10 minutes. The deadline + // must be in the interval [15 seconds, 30 minutes]. // - // - For [App Engine tasks][google.cloud.tasks.v2beta3.AppEngineHttpRequest], 0 indicates that the - // request has the default deadline. The default deadline depends on the - // [scaling - // type](https://cloud.google.com/appengine/docs/standard/go/how-instances-are-managed#instance_scaling) - // of the service: 10 minutes for standard apps with automatic scaling, 24 - // hours for standard apps with manual and basic scaling, and 60 minutes for - // flex apps. If the request deadline is set, it must be in the interval [15 - // seconds, 24 hours 15 seconds]. Regardless of the task's - // `dispatch_deadline`, the app handler will not run for longer than than - // the service's timeout. We recommend setting the `dispatch_deadline` to - // at most a few seconds more than the app handler's timeout. For more - // information see - // [Timeouts](https://cloud.google.com/tasks/docs/creating-appengine-handlers#timeouts). + // * For [App Engine tasks][google.cloud.tasks.v2beta3.AppEngineHttpRequest], 0 indicates that the + // request has the default deadline. The default deadline depends on the + // [scaling + // type](https://cloud.google.com/appengine/docs/standard/go/how-instances-are-managed#instance_scaling) + // of the service: 10 minutes for standard apps with automatic scaling, 24 + // hours for standard apps with manual and basic scaling, and 60 minutes for + // flex apps. If the request deadline is set, it must be in the interval [15 + // seconds, 24 hours 15 seconds]. Regardless of the task's + // `dispatch_deadline`, the app handler will not run for longer than than + // the service's timeout. We recommend setting the `dispatch_deadline` to + // at most a few seconds more than the app handler's timeout. For more + // information see + // [Timeouts](https://cloud.google.com/tasks/docs/creating-appengine-handlers#timeouts). // // `dispatch_deadline` will be truncated to the nearest millisecond. The // deadline is an approximate deadline. diff --git a/compute/apiv1/accelerator_types_client.go b/compute/apiv1/accelerator_types_client.go index 62803475efb2..478802ad55ce 100644 --- a/compute/apiv1/accelerator_types_client.go +++ b/compute/apiv1/accelerator_types_client.go @@ -210,6 +210,7 @@ func (c *acceleratorTypesRESTClient) AggregatedList(ctx context.Context, req *co baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/aggregated/acceleratorTypes", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -302,6 +303,11 @@ func (c *acceleratorTypesRESTClient) Get(ctx context.Context, req *computepb.Get } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/acceleratorTypes/%v", req.GetProject(), req.GetZone(), req.GetAcceleratorType()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "zone", url.QueryEscape(req.GetZone()), "accelerator_type", url.QueryEscape(req.GetAcceleratorType()))) @@ -369,6 +375,7 @@ func (c *acceleratorTypesRESTClient) List(ctx context.Context, req *computepb.Li baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/acceleratorTypes", req.GetProject(), req.GetZone()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/compute/apiv1/addresses_client.go b/compute/apiv1/addresses_client.go index af59465f6423..a1f8b4d206d9 100644 --- a/compute/apiv1/addresses_client.go +++ b/compute/apiv1/addresses_client.go @@ -247,6 +247,7 @@ func (c *addressesRESTClient) AggregatedList(ctx context.Context, req *computepb baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/aggregated/addresses", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -340,6 +341,7 @@ func (c *addressesRESTClient) Delete(ctx context.Context, req *computepb.DeleteA baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/addresses/%v", req.GetProject(), req.GetRegion(), req.GetAddress()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -407,6 +409,11 @@ func (c *addressesRESTClient) Get(ctx context.Context, req *computepb.GetAddress } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/addresses/%v", req.GetProject(), req.GetRegion(), req.GetAddress()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "address", url.QueryEscape(req.GetAddress()))) @@ -468,6 +475,7 @@ func (c *addressesRESTClient) Insert(ctx context.Context, req *computepb.InsertA baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/addresses", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -549,6 +557,7 @@ func (c *addressesRESTClient) List(ctx context.Context, req *computepb.ListAddre baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/addresses", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -639,6 +648,7 @@ func (c *addressesRESTClient) SetLabels(ctx context.Context, req *computepb.SetL baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/addresses/%v/setLabels", req.GetProject(), req.GetRegion(), req.GetResource()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } diff --git a/compute/apiv1/autoscalers_client.go b/compute/apiv1/autoscalers_client.go index 79686e547e5e..1b5bfc9c3836 100644 --- a/compute/apiv1/autoscalers_client.go +++ b/compute/apiv1/autoscalers_client.go @@ -255,6 +255,7 @@ func (c *autoscalersRESTClient) AggregatedList(ctx context.Context, req *compute baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/aggregated/autoscalers", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -348,6 +349,7 @@ func (c *autoscalersRESTClient) Delete(ctx context.Context, req *computepb.Delet baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/autoscalers/%v", req.GetProject(), req.GetZone(), req.GetAutoscaler()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -415,6 +417,11 @@ func (c *autoscalersRESTClient) Get(ctx context.Context, req *computepb.GetAutos } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/autoscalers/%v", req.GetProject(), req.GetZone(), req.GetAutoscaler()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "zone", url.QueryEscape(req.GetZone()), "autoscaler", url.QueryEscape(req.GetAutoscaler()))) @@ -476,6 +483,7 @@ func (c *autoscalersRESTClient) Insert(ctx context.Context, req *computepb.Inser baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/autoscalers", req.GetProject(), req.GetZone()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -557,6 +565,7 @@ func (c *autoscalersRESTClient) List(ctx context.Context, req *computepb.ListAut baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/autoscalers", req.GetProject(), req.GetZone()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -647,6 +656,7 @@ func (c *autoscalersRESTClient) Patch(ctx context.Context, req *computepb.PatchA baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/autoscalers", req.GetProject(), req.GetZone()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Autoscaler != nil { params.Add("autoscaler", fmt.Sprintf("%v", req.GetAutoscaler())) } @@ -725,6 +735,7 @@ func (c *autoscalersRESTClient) Update(ctx context.Context, req *computepb.Updat baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/autoscalers", req.GetProject(), req.GetZone()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Autoscaler != nil { params.Add("autoscaler", fmt.Sprintf("%v", req.GetAutoscaler())) } diff --git a/compute/apiv1/backend_buckets_client.go b/compute/apiv1/backend_buckets_client.go index 8254dd6208c0..5d1c65f6a0c6 100644 --- a/compute/apiv1/backend_buckets_client.go +++ b/compute/apiv1/backend_buckets_client.go @@ -264,6 +264,7 @@ func (c *backendBucketsRESTClient) AddSignedUrlKey(ctx context.Context, req *com baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/backendBuckets/%v/addSignedUrlKey", req.GetProject(), req.GetBackendBucket()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -331,6 +332,7 @@ func (c *backendBucketsRESTClient) Delete(ctx context.Context, req *computepb.De baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/backendBuckets/%v", req.GetProject(), req.GetBackendBucket()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -398,6 +400,7 @@ func (c *backendBucketsRESTClient) DeleteSignedUrlKey(ctx context.Context, req * baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/backendBuckets/%v/deleteSignedUrlKey", req.GetProject(), req.GetBackendBucket()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("keyName", fmt.Sprintf("%v", req.GetKeyName())) if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) @@ -465,6 +468,11 @@ func (c *backendBucketsRESTClient) Get(ctx context.Context, req *computepb.GetBa } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/backendBuckets/%v", req.GetProject(), req.GetBackendBucket()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "backend_bucket", url.QueryEscape(req.GetBackendBucket()))) @@ -526,6 +534,7 @@ func (c *backendBucketsRESTClient) Insert(ctx context.Context, req *computepb.In baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/backendBuckets", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -606,6 +615,7 @@ func (c *backendBucketsRESTClient) List(ctx context.Context, req *computepb.List baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/backendBuckets", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -696,6 +706,7 @@ func (c *backendBucketsRESTClient) Patch(ctx context.Context, req *computepb.Pat baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/backendBuckets/%v", req.GetProject(), req.GetBackendBucket()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -770,6 +781,7 @@ func (c *backendBucketsRESTClient) SetEdgeSecurityPolicy(ctx context.Context, re baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/backendBuckets/%v/setEdgeSecurityPolicy", req.GetProject(), req.GetBackendBucket()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -844,6 +856,7 @@ func (c *backendBucketsRESTClient) Update(ctx context.Context, req *computepb.Up baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/backendBuckets/%v", req.GetProject(), req.GetBackendBucket()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } diff --git a/compute/apiv1/backend_services_client.go b/compute/apiv1/backend_services_client.go index 89ab3c3ab7d7..e307f3f10aa7 100644 --- a/compute/apiv1/backend_services_client.go +++ b/compute/apiv1/backend_services_client.go @@ -305,6 +305,7 @@ func (c *backendServicesRESTClient) AddSignedUrlKey(ctx context.Context, req *co baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/backendServices/%v/addSignedUrlKey", req.GetProject(), req.GetBackendService()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -385,6 +386,7 @@ func (c *backendServicesRESTClient) AggregatedList(ctx context.Context, req *com baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/aggregated/backendServices", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -478,6 +480,7 @@ func (c *backendServicesRESTClient) Delete(ctx context.Context, req *computepb.D baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/backendServices/%v", req.GetProject(), req.GetBackendService()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -545,6 +548,7 @@ func (c *backendServicesRESTClient) DeleteSignedUrlKey(ctx context.Context, req baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/backendServices/%v/deleteSignedUrlKey", req.GetProject(), req.GetBackendService()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("keyName", fmt.Sprintf("%v", req.GetKeyName())) if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) @@ -612,6 +616,11 @@ func (c *backendServicesRESTClient) Get(ctx context.Context, req *computepb.GetB } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/backendServices/%v", req.GetProject(), req.GetBackendService()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "backend_service", url.QueryEscape(req.GetBackendService()))) @@ -672,6 +681,11 @@ func (c *backendServicesRESTClient) GetHealth(ctx context.Context, req *computep } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/backendServices/%v/getHealth", req.GetProject(), req.GetBackendService()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "backend_service", url.QueryEscape(req.GetBackendService()))) @@ -726,6 +740,7 @@ func (c *backendServicesRESTClient) GetIamPolicy(ctx context.Context, req *compu baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/backendServices/%v/getIamPolicy", req.GetProject(), req.GetResource()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.OptionsRequestedPolicyVersion != nil { params.Add("optionsRequestedPolicyVersion", fmt.Sprintf("%v", req.GetOptionsRequestedPolicyVersion())) } @@ -793,6 +808,7 @@ func (c *backendServicesRESTClient) Insert(ctx context.Context, req *computepb.I baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/backendServices", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -873,6 +889,7 @@ func (c *backendServicesRESTClient) List(ctx context.Context, req *computepb.Lis baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/backendServices", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -963,6 +980,7 @@ func (c *backendServicesRESTClient) Patch(ctx context.Context, req *computepb.Pa baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/backendServices/%v", req.GetProject(), req.GetBackendService()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -1037,6 +1055,7 @@ func (c *backendServicesRESTClient) SetEdgeSecurityPolicy(ctx context.Context, r baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/backendServices/%v/setEdgeSecurityPolicy", req.GetProject(), req.GetBackendService()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -1110,6 +1129,11 @@ func (c *backendServicesRESTClient) SetIamPolicy(ctx context.Context, req *compu } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/backendServices/%v/setIamPolicy", req.GetProject(), req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "resource", url.QueryEscape(req.GetResource()))) @@ -1171,6 +1195,7 @@ func (c *backendServicesRESTClient) SetSecurityPolicy(ctx context.Context, req * baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/backendServices/%v/setSecurityPolicy", req.GetProject(), req.GetBackendService()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -1245,6 +1270,7 @@ func (c *backendServicesRESTClient) Update(ctx context.Context, req *computepb.U baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/backendServices/%v", req.GetProject(), req.GetBackendService()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } diff --git a/compute/apiv1/computepb/compute.pb.go b/compute/apiv1/computepb/compute.pb.go index b6a08642c584..a52021c88ad0 100644 --- a/compute/apiv1/computepb/compute.pb.go +++ b/compute/apiv1/computepb/compute.pb.go @@ -20,8 +20,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/compute/v1/compute.proto package computepb @@ -40379,6 +40379,7 @@ type ForwardingRule struct { Ports []string `protobuf:"bytes,106854418,rep,name=ports,proto3" json:"ports,omitempty"` // [Output Only] The PSC connection id of the PSC Forwarding Rule. PscConnectionId *uint64 `protobuf:"varint,292082397,opt,name=psc_connection_id,json=pscConnectionId,proto3,oneof" json:"psc_connection_id,omitempty"` + // // Check the PscConnectionStatus enum for the list of possible values. PscConnectionStatus *string `protobuf:"bytes,184149172,opt,name=psc_connection_status,json=pscConnectionStatus,proto3,oneof" json:"psc_connection_status,omitempty"` // [Output Only] URL of the region where the regional forwarding rule resides. This field is not applicable to global forwarding rules. You must specify this field as part of the HTTP request URL. It is not settable as a field in the request body. @@ -49861,7 +49862,7 @@ type GuestAttributes struct { // [Output Only] Type of the resource. Always compute#guestAttributes for guest attributes entry. Kind *string `protobuf:"bytes,3292052,opt,name=kind,proto3,oneof" json:"kind,omitempty"` - // The path to be queried. This can be the default namespace (”) or a nested namespace ('\/') or a specified key ('\/\'). + // The path to be queried. This can be the default namespace ('') or a nested namespace ('\/') or a specified key ('\/\'). QueryPath *string `protobuf:"bytes,368591164,opt,name=query_path,json=queryPath,proto3,oneof" json:"query_path,omitempty"` // [Output Only] The value of the requested queried path. QueryValue *GuestAttributesValue `protobuf:"bytes,157570874,opt,name=query_value,json=queryValue,proto3,oneof" json:"query_value,omitempty"` @@ -51291,6 +51292,7 @@ type HealthStatus struct { // The named port of the instance group, not necessarily the port that is health-checked. Port *int32 `protobuf:"varint,3446913,opt,name=port,proto3,oneof" json:"port,omitempty"` Weight *string `protobuf:"bytes,282149496,opt,name=weight,proto3,oneof" json:"weight,omitempty"` + // // Check the WeightError enum for the list of possible values. WeightError *string `protobuf:"bytes,522501505,opt,name=weight_error,json=weightError,proto3,oneof" json:"weight_error,omitempty"` } @@ -59027,7 +59029,7 @@ type InstanceGroup struct { Kind *string `protobuf:"bytes,3292052,opt,name=kind,proto3,oneof" json:"kind,omitempty"` // The name of the instance group. The name must be 1-63 characters long, and comply with RFC1035. Name *string `protobuf:"bytes,3373707,opt,name=name,proto3,oneof" json:"name,omitempty"` - // Assigns a name to a port number. For example: {name: "http", port: 80} This allows the system to reference ports by the assigned name instead of a port number. Named ports can also contain multiple ports. For example: [{name: "app1", port: 8080}, {name: "app1", port: 8081}, {name: "app2", port: 8082}] Named ports apply to all instances in this instance group. + // Assigns a name to a port number. For example: {name: "http", port: 80} This allows the system to reference ports by the assigned name instead of a port number. Named ports can also contain multiple ports. For example: [{name: "app1", port: 8080}, {name: "app1", port: 8081}, {name: "app2", port: 8082}] Named ports apply to all instances in this instance group. NamedPorts []*NamedPort `protobuf:"bytes,427598732,rep,name=named_ports,json=namedPorts,proto3" json:"named_ports,omitempty"` // [Output Only] The URL of the network to which all instances in the instance group belong. If your instance has multiple network interfaces, then the network and subnetwork fields only refer to the network and subnet used by your primary interface (nic0). Network *string `protobuf:"bytes,232872494,opt,name=network,proto3,oneof" json:"network,omitempty"` @@ -80125,6 +80127,7 @@ type NetworkPerformanceConfig struct { sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields + // // Check the TotalEgressBandwidthTier enum for the list of possible values. TotalEgressBandwidthTier *string `protobuf:"bytes,130109439,opt,name=total_egress_bandwidth_tier,json=totalEgressBandwidthTier,proto3,oneof" json:"total_egress_bandwidth_tier,omitempty"` } @@ -80563,6 +80566,7 @@ type NodeGroup struct { ShareSettings *ShareSettings `protobuf:"bytes,266668163,opt,name=share_settings,json=shareSettings,proto3,oneof" json:"share_settings,omitempty"` // [Output Only] The total number of nodes in the node group. Size *int32 `protobuf:"varint,3530753,opt,name=size,proto3,oneof" json:"size,omitempty"` + // // Check the Status enum for the list of possible values. Status *string `protobuf:"bytes,181260274,opt,name=status,proto3,oneof" json:"status,omitempty"` // [Output Only] The name of the zone where the node group resides, such as us-central1-a. @@ -81062,6 +81066,7 @@ type NodeGroupNode struct { ServerBinding *ServerBinding `protobuf:"bytes,208179593,opt,name=server_binding,json=serverBinding,proto3,oneof" json:"server_binding,omitempty"` // Server ID associated with this node. ServerId *string `protobuf:"bytes,339433367,opt,name=server_id,json=serverId,proto3,oneof" json:"server_id,omitempty"` + // // Check the Status enum for the list of possible values. Status *string `protobuf:"bytes,181260274,opt,name=status,proto3,oneof" json:"status,omitempty"` // Total amount of available resources on the node. @@ -99704,8 +99709,10 @@ type SecurityPolicyAdvancedOptionsConfig struct { // Custom configuration to apply the JSON parsing. Only applicable when json_parsing is set to STANDARD. JsonCustomConfig *SecurityPolicyAdvancedOptionsConfigJsonCustomConfig `protobuf:"bytes,111570105,opt,name=json_custom_config,json=jsonCustomConfig,proto3,oneof" json:"json_custom_config,omitempty"` + // // Check the JsonParsing enum for the list of possible values. JsonParsing *string `protobuf:"bytes,282493529,opt,name=json_parsing,json=jsonParsing,proto3,oneof" json:"json_parsing,omitempty"` + // // Check the LogLevel enum for the list of possible values. LogLevel *string `protobuf:"bytes,140582601,opt,name=log_level,json=logLevel,proto3,oneof" json:"log_level,omitempty"` } @@ -99816,6 +99823,7 @@ type SecurityPolicyDdosProtectionConfig struct { sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields + // // Check the DdosProtection enum for the list of possible values. DdosProtection *string `protobuf:"bytes,275173268,opt,name=ddos_protection,json=ddosProtection,proto3,oneof" json:"ddos_protection,omitempty"` } @@ -100861,6 +100869,7 @@ type ServerBinding struct { sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields + // // Check the Type enum for the list of possible values. Type *string `protobuf:"bytes,3575610,opt,name=type,proto3,oneof" json:"type,omitempty"` } @@ -110964,6 +110973,7 @@ type Subsetting struct { sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields + // // Check the Policy enum for the list of possible values. Policy *string `protobuf:"bytes,91071794,opt,name=policy,proto3,oneof" json:"policy,omitempty"` } diff --git a/compute/apiv1/disk_types_client.go b/compute/apiv1/disk_types_client.go index 63abac722677..e6e0f96721dc 100644 --- a/compute/apiv1/disk_types_client.go +++ b/compute/apiv1/disk_types_client.go @@ -206,6 +206,7 @@ func (c *diskTypesRESTClient) AggregatedList(ctx context.Context, req *computepb baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/aggregated/diskTypes", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -298,6 +299,11 @@ func (c *diskTypesRESTClient) Get(ctx context.Context, req *computepb.GetDiskTyp } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/diskTypes/%v", req.GetProject(), req.GetZone(), req.GetDiskType()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "zone", url.QueryEscape(req.GetZone()), "disk_type", url.QueryEscape(req.GetDiskType()))) @@ -365,6 +371,7 @@ func (c *diskTypesRESTClient) List(ctx context.Context, req *computepb.ListDiskT baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/diskTypes", req.GetProject(), req.GetZone()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/compute/apiv1/disks_client.go b/compute/apiv1/disks_client.go index 3bdebcadf46c..7f9f0ac3ab16 100644 --- a/compute/apiv1/disks_client.go +++ b/compute/apiv1/disks_client.go @@ -297,6 +297,7 @@ func (c *disksRESTClient) AddResourcePolicies(ctx context.Context, req *computep baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/disks/%v/addResourcePolicies", req.GetProject(), req.GetZone(), req.GetDisk()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -378,6 +379,7 @@ func (c *disksRESTClient) AggregatedList(ctx context.Context, req *computepb.Agg baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/aggregated/disks", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -478,6 +480,7 @@ func (c *disksRESTClient) CreateSnapshot(ctx context.Context, req *computepb.Cre baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/disks/%v/createSnapshot", req.GetProject(), req.GetZone(), req.GetDisk()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.GuestFlush != nil { params.Add("guestFlush", fmt.Sprintf("%v", req.GetGuestFlush())) } @@ -549,6 +552,7 @@ func (c *disksRESTClient) Delete(ctx context.Context, req *computepb.DeleteDiskR baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/disks/%v", req.GetProject(), req.GetZone(), req.GetDisk()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -616,6 +620,11 @@ func (c *disksRESTClient) Get(ctx context.Context, req *computepb.GetDiskRequest } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/disks/%v", req.GetProject(), req.GetZone(), req.GetDisk()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "zone", url.QueryEscape(req.GetZone()), "disk", url.QueryEscape(req.GetDisk()))) @@ -670,6 +679,7 @@ func (c *disksRESTClient) GetIamPolicy(ctx context.Context, req *computepb.GetIa baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/disks/%v/getIamPolicy", req.GetProject(), req.GetZone(), req.GetResource()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.OptionsRequestedPolicyVersion != nil { params.Add("optionsRequestedPolicyVersion", fmt.Sprintf("%v", req.GetOptionsRequestedPolicyVersion())) } @@ -737,6 +747,7 @@ func (c *disksRESTClient) Insert(ctx context.Context, req *computepb.InsertDiskR baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/disks", req.GetProject(), req.GetZone()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -821,6 +832,7 @@ func (c *disksRESTClient) List(ctx context.Context, req *computepb.ListDisksRequ baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/disks", req.GetProject(), req.GetZone()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -911,6 +923,7 @@ func (c *disksRESTClient) RemoveResourcePolicies(ctx context.Context, req *compu baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/disks/%v/removeResourcePolicies", req.GetProject(), req.GetZone(), req.GetDisk()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -986,6 +999,7 @@ func (c *disksRESTClient) Resize(ctx context.Context, req *computepb.ResizeDiskR baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/disks/%v/resize", req.GetProject(), req.GetZone(), req.GetDisk()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -1060,6 +1074,11 @@ func (c *disksRESTClient) SetIamPolicy(ctx context.Context, req *computepb.SetIa } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/disks/%v/setIamPolicy", req.GetProject(), req.GetZone(), req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "zone", url.QueryEscape(req.GetZone()), "resource", url.QueryEscape(req.GetResource()))) @@ -1121,6 +1140,7 @@ func (c *disksRESTClient) SetLabels(ctx context.Context, req *computepb.SetLabel baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/disks/%v/setLabels", req.GetProject(), req.GetZone(), req.GetResource()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -1195,6 +1215,11 @@ func (c *disksRESTClient) TestIamPermissions(ctx context.Context, req *computepb } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/disks/%v/testIamPermissions", req.GetProject(), req.GetZone(), req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "zone", url.QueryEscape(req.GetZone()), "resource", url.QueryEscape(req.GetResource()))) diff --git a/compute/apiv1/external_vpn_gateways_client.go b/compute/apiv1/external_vpn_gateways_client.go index 20ad6652abd3..d48232bbbf39 100644 --- a/compute/apiv1/external_vpn_gateways_client.go +++ b/compute/apiv1/external_vpn_gateways_client.go @@ -233,6 +233,7 @@ func (c *externalVpnGatewaysRESTClient) Delete(ctx context.Context, req *compute baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/externalVpnGateways/%v", req.GetProject(), req.GetExternalVpnGateway()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -299,6 +300,11 @@ func (c *externalVpnGatewaysRESTClient) Get(ctx context.Context, req *computepb. } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/externalVpnGateways/%v", req.GetProject(), req.GetExternalVpnGateway()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "external_vpn_gateway", url.QueryEscape(req.GetExternalVpnGateway()))) @@ -360,6 +366,7 @@ func (c *externalVpnGatewaysRESTClient) Insert(ctx context.Context, req *compute baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/externalVpnGateways", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -440,6 +447,7 @@ func (c *externalVpnGatewaysRESTClient) List(ctx context.Context, req *computepb baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/externalVpnGateways", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -529,6 +537,11 @@ func (c *externalVpnGatewaysRESTClient) SetLabels(ctx context.Context, req *comp } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/externalVpnGateways/%v/setLabels", req.GetProject(), req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "resource", url.QueryEscape(req.GetResource()))) @@ -596,6 +609,11 @@ func (c *externalVpnGatewaysRESTClient) TestIamPermissions(ctx context.Context, } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/externalVpnGateways/%v/testIamPermissions", req.GetProject(), req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "resource", url.QueryEscape(req.GetResource()))) diff --git a/compute/apiv1/firewall_policies_client.go b/compute/apiv1/firewall_policies_client.go index f8046d5270d0..552242a8d010 100644 --- a/compute/apiv1/firewall_policies_client.go +++ b/compute/apiv1/firewall_policies_client.go @@ -336,6 +336,7 @@ func (c *firewallPoliciesRESTClient) AddAssociation(ctx context.Context, req *co baseUrl.Path += fmt.Sprintf("/compute/v1/locations/global/firewallPolicies/%v/addAssociation", req.GetFirewallPolicy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.ReplaceExistingAssociation != nil { params.Add("replaceExistingAssociation", fmt.Sprintf("%v", req.GetReplaceExistingAssociation())) } @@ -412,6 +413,7 @@ func (c *firewallPoliciesRESTClient) AddRule(ctx context.Context, req *computepb baseUrl.Path += fmt.Sprintf("/compute/v1/locations/global/firewallPolicies/%v/addRule", req.GetFirewallPolicy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -478,6 +480,7 @@ func (c *firewallPoliciesRESTClient) CloneRules(ctx context.Context, req *comput baseUrl.Path += fmt.Sprintf("/compute/v1/locations/global/firewallPolicies/%v/cloneRules", req.GetFirewallPolicy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -547,6 +550,7 @@ func (c *firewallPoliciesRESTClient) Delete(ctx context.Context, req *computepb. baseUrl.Path += fmt.Sprintf("/compute/v1/locations/global/firewallPolicies/%v", req.GetFirewallPolicy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -612,6 +616,11 @@ func (c *firewallPoliciesRESTClient) Get(ctx context.Context, req *computepb.Get } baseUrl.Path += fmt.Sprintf("/compute/v1/locations/global/firewallPolicies/%v", req.GetFirewallPolicy()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "firewall_policy", url.QueryEscape(req.GetFirewallPolicy()))) @@ -666,6 +675,7 @@ func (c *firewallPoliciesRESTClient) GetAssociation(ctx context.Context, req *co baseUrl.Path += fmt.Sprintf("/compute/v1/locations/global/firewallPolicies/%v/getAssociation", req.GetFirewallPolicy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Name != nil { params.Add("name", fmt.Sprintf("%v", req.GetName())) } @@ -726,6 +736,7 @@ func (c *firewallPoliciesRESTClient) GetIamPolicy(ctx context.Context, req *comp baseUrl.Path += fmt.Sprintf("/compute/v1/locations/global/firewallPolicies/%v/getIamPolicy", req.GetResource()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.OptionsRequestedPolicyVersion != nil { params.Add("optionsRequestedPolicyVersion", fmt.Sprintf("%v", req.GetOptionsRequestedPolicyVersion())) } @@ -786,6 +797,7 @@ func (c *firewallPoliciesRESTClient) GetRule(ctx context.Context, req *computepb baseUrl.Path += fmt.Sprintf("/compute/v1/locations/global/firewallPolicies/%v/getRule", req.GetFirewallPolicy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Priority != nil { params.Add("priority", fmt.Sprintf("%v", req.GetPriority())) } @@ -853,6 +865,7 @@ func (c *firewallPoliciesRESTClient) Insert(ctx context.Context, req *computepb. baseUrl.Path += fmt.Sprintf("/compute/v1/locations/global/firewallPolicies") params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("parentId", fmt.Sprintf("%v", req.GetParentId())) if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) @@ -931,6 +944,7 @@ func (c *firewallPoliciesRESTClient) List(ctx context.Context, req *computepb.Li baseUrl.Path += fmt.Sprintf("/compute/v1/locations/global/firewallPolicies") params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1017,6 +1031,7 @@ func (c *firewallPoliciesRESTClient) ListAssociations(ctx context.Context, req * baseUrl.Path += fmt.Sprintf("/compute/v1/locations/global/firewallPolicies/listAssociations") params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.TargetResource != nil { params.Add("targetResource", fmt.Sprintf("%v", req.GetTargetResource())) } @@ -1075,6 +1090,7 @@ func (c *firewallPoliciesRESTClient) Move(ctx context.Context, req *computepb.Mo baseUrl.Path += fmt.Sprintf("/compute/v1/locations/global/firewallPolicies/%v/move", req.GetFirewallPolicy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("parentId", fmt.Sprintf("%v", req.GetParentId())) if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) @@ -1149,6 +1165,7 @@ func (c *firewallPoliciesRESTClient) Patch(ctx context.Context, req *computepb.P baseUrl.Path += fmt.Sprintf("/compute/v1/locations/global/firewallPolicies/%v", req.GetFirewallPolicy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -1222,6 +1239,7 @@ func (c *firewallPoliciesRESTClient) PatchRule(ctx context.Context, req *compute baseUrl.Path += fmt.Sprintf("/compute/v1/locations/global/firewallPolicies/%v/patchRule", req.GetFirewallPolicy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Priority != nil { params.Add("priority", fmt.Sprintf("%v", req.GetPriority())) } @@ -1291,6 +1309,7 @@ func (c *firewallPoliciesRESTClient) RemoveAssociation(ctx context.Context, req baseUrl.Path += fmt.Sprintf("/compute/v1/locations/global/firewallPolicies/%v/removeAssociation", req.GetFirewallPolicy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Name != nil { params.Add("name", fmt.Sprintf("%v", req.GetName())) } @@ -1360,6 +1379,7 @@ func (c *firewallPoliciesRESTClient) RemoveRule(ctx context.Context, req *comput baseUrl.Path += fmt.Sprintf("/compute/v1/locations/global/firewallPolicies/%v/removeRule", req.GetFirewallPolicy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Priority != nil { params.Add("priority", fmt.Sprintf("%v", req.GetPriority())) } @@ -1435,6 +1455,11 @@ func (c *firewallPoliciesRESTClient) SetIamPolicy(ctx context.Context, req *comp } baseUrl.Path += fmt.Sprintf("/compute/v1/locations/global/firewallPolicies/%v/setIamPolicy", req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) @@ -1495,6 +1520,11 @@ func (c *firewallPoliciesRESTClient) TestIamPermissions(ctx context.Context, req } baseUrl.Path += fmt.Sprintf("/compute/v1/locations/global/firewallPolicies/%v/testIamPermissions", req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) diff --git a/compute/apiv1/firewalls_client.go b/compute/apiv1/firewalls_client.go index a9a080fd8888..d66fe16b4494 100644 --- a/compute/apiv1/firewalls_client.go +++ b/compute/apiv1/firewalls_client.go @@ -233,6 +233,7 @@ func (c *firewallsRESTClient) Delete(ctx context.Context, req *computepb.DeleteF baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/firewalls/%v", req.GetProject(), req.GetFirewall()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -299,6 +300,11 @@ func (c *firewallsRESTClient) Get(ctx context.Context, req *computepb.GetFirewal } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/firewalls/%v", req.GetProject(), req.GetFirewall()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "firewall", url.QueryEscape(req.GetFirewall()))) @@ -360,6 +366,7 @@ func (c *firewallsRESTClient) Insert(ctx context.Context, req *computepb.InsertF baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/firewalls", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -440,6 +447,7 @@ func (c *firewallsRESTClient) List(ctx context.Context, req *computepb.ListFirew baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/firewalls", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -530,6 +538,7 @@ func (c *firewallsRESTClient) Patch(ctx context.Context, req *computepb.PatchFir baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/firewalls/%v", req.GetProject(), req.GetFirewall()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -604,6 +613,7 @@ func (c *firewallsRESTClient) Update(ctx context.Context, req *computepb.UpdateF baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/firewalls/%v", req.GetProject(), req.GetFirewall()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } diff --git a/compute/apiv1/forwarding_rules_client.go b/compute/apiv1/forwarding_rules_client.go index b7f6917b4501..8e2bd4c57476 100644 --- a/compute/apiv1/forwarding_rules_client.go +++ b/compute/apiv1/forwarding_rules_client.go @@ -263,6 +263,7 @@ func (c *forwardingRulesRESTClient) AggregatedList(ctx context.Context, req *com baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/aggregated/forwardingRules", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -356,6 +357,7 @@ func (c *forwardingRulesRESTClient) Delete(ctx context.Context, req *computepb.D baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/forwardingRules/%v", req.GetProject(), req.GetRegion(), req.GetForwardingRule()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -423,6 +425,11 @@ func (c *forwardingRulesRESTClient) Get(ctx context.Context, req *computepb.GetF } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/forwardingRules/%v", req.GetProject(), req.GetRegion(), req.GetForwardingRule()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "forwarding_rule", url.QueryEscape(req.GetForwardingRule()))) @@ -484,6 +491,7 @@ func (c *forwardingRulesRESTClient) Insert(ctx context.Context, req *computepb.I baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/forwardingRules", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -565,6 +573,7 @@ func (c *forwardingRulesRESTClient) List(ctx context.Context, req *computepb.Lis baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/forwardingRules", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -655,6 +664,7 @@ func (c *forwardingRulesRESTClient) Patch(ctx context.Context, req *computepb.Pa baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/forwardingRules/%v", req.GetProject(), req.GetRegion(), req.GetForwardingRule()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -730,6 +740,7 @@ func (c *forwardingRulesRESTClient) SetLabels(ctx context.Context, req *computep baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/forwardingRules/%v/setLabels", req.GetProject(), req.GetRegion(), req.GetResource()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -805,6 +816,7 @@ func (c *forwardingRulesRESTClient) SetTarget(ctx context.Context, req *computep baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/forwardingRules/%v/setTarget", req.GetProject(), req.GetRegion(), req.GetForwardingRule()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } diff --git a/compute/apiv1/global_addresses_client.go b/compute/apiv1/global_addresses_client.go index 5bb733727b77..a87744b0da61 100644 --- a/compute/apiv1/global_addresses_client.go +++ b/compute/apiv1/global_addresses_client.go @@ -225,6 +225,7 @@ func (c *globalAddressesRESTClient) Delete(ctx context.Context, req *computepb.D baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/addresses/%v", req.GetProject(), req.GetAddress()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -291,6 +292,11 @@ func (c *globalAddressesRESTClient) Get(ctx context.Context, req *computepb.GetG } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/addresses/%v", req.GetProject(), req.GetAddress()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "address", url.QueryEscape(req.GetAddress()))) @@ -352,6 +358,7 @@ func (c *globalAddressesRESTClient) Insert(ctx context.Context, req *computepb.I baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/addresses", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -432,6 +439,7 @@ func (c *globalAddressesRESTClient) List(ctx context.Context, req *computepb.Lis baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/addresses", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -521,6 +529,11 @@ func (c *globalAddressesRESTClient) SetLabels(ctx context.Context, req *computep } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/addresses/%v/setLabels", req.GetProject(), req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "resource", url.QueryEscape(req.GetResource()))) diff --git a/compute/apiv1/global_forwarding_rules_client.go b/compute/apiv1/global_forwarding_rules_client.go index 84781b242abc..befea6624650 100644 --- a/compute/apiv1/global_forwarding_rules_client.go +++ b/compute/apiv1/global_forwarding_rules_client.go @@ -241,6 +241,7 @@ func (c *globalForwardingRulesRESTClient) Delete(ctx context.Context, req *compu baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/forwardingRules/%v", req.GetProject(), req.GetForwardingRule()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -307,6 +308,11 @@ func (c *globalForwardingRulesRESTClient) Get(ctx context.Context, req *computep } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/forwardingRules/%v", req.GetProject(), req.GetForwardingRule()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "forwarding_rule", url.QueryEscape(req.GetForwardingRule()))) @@ -368,6 +374,7 @@ func (c *globalForwardingRulesRESTClient) Insert(ctx context.Context, req *compu baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/forwardingRules", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -448,6 +455,7 @@ func (c *globalForwardingRulesRESTClient) List(ctx context.Context, req *compute baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/forwardingRules", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -538,6 +546,7 @@ func (c *globalForwardingRulesRESTClient) Patch(ctx context.Context, req *comput baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/forwardingRules/%v", req.GetProject(), req.GetForwardingRule()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -611,6 +620,11 @@ func (c *globalForwardingRulesRESTClient) SetLabels(ctx context.Context, req *co } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/forwardingRules/%v/setLabels", req.GetProject(), req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "resource", url.QueryEscape(req.GetResource()))) @@ -679,6 +693,7 @@ func (c *globalForwardingRulesRESTClient) SetTarget(ctx context.Context, req *co baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/forwardingRules/%v/setTarget", req.GetProject(), req.GetForwardingRule()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } diff --git a/compute/apiv1/global_network_endpoint_groups_client.go b/compute/apiv1/global_network_endpoint_groups_client.go index 4bf8ac1a4741..686dc102c624 100644 --- a/compute/apiv1/global_network_endpoint_groups_client.go +++ b/compute/apiv1/global_network_endpoint_groups_client.go @@ -248,6 +248,7 @@ func (c *globalNetworkEndpointGroupsRESTClient) AttachNetworkEndpoints(ctx conte baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/networkEndpointGroups/%v/attachNetworkEndpoints", req.GetProject(), req.GetNetworkEndpointGroup()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -315,6 +316,7 @@ func (c *globalNetworkEndpointGroupsRESTClient) Delete(ctx context.Context, req baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/networkEndpointGroups/%v", req.GetProject(), req.GetNetworkEndpointGroup()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -389,6 +391,7 @@ func (c *globalNetworkEndpointGroupsRESTClient) DetachNetworkEndpoints(ctx conte baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/networkEndpointGroups/%v/detachNetworkEndpoints", req.GetProject(), req.GetNetworkEndpointGroup()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -455,6 +458,11 @@ func (c *globalNetworkEndpointGroupsRESTClient) Get(ctx context.Context, req *co } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/networkEndpointGroups/%v", req.GetProject(), req.GetNetworkEndpointGroup()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "network_endpoint_group", url.QueryEscape(req.GetNetworkEndpointGroup()))) @@ -516,6 +524,7 @@ func (c *globalNetworkEndpointGroupsRESTClient) Insert(ctx context.Context, req baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/networkEndpointGroups", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -596,6 +605,7 @@ func (c *globalNetworkEndpointGroupsRESTClient) List(ctx context.Context, req *c baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/networkEndpointGroups", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -692,6 +702,7 @@ func (c *globalNetworkEndpointGroupsRESTClient) ListNetworkEndpoints(ctx context baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/networkEndpointGroups/%v/listNetworkEndpoints", req.GetProject(), req.GetNetworkEndpointGroup()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/compute/apiv1/global_operations_client.go b/compute/apiv1/global_operations_client.go index f1e4fa61575c..6abb48380b16 100644 --- a/compute/apiv1/global_operations_client.go +++ b/compute/apiv1/global_operations_client.go @@ -222,6 +222,7 @@ func (c *globalOperationsRESTClient) AggregatedList(ctx context.Context, req *co baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/aggregated/operations", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -314,6 +315,11 @@ func (c *globalOperationsRESTClient) Delete(ctx context.Context, req *computepb. } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/operations/%v", req.GetProject(), req.GetOperation()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "operation", url.QueryEscape(req.GetOperation()))) @@ -367,6 +373,11 @@ func (c *globalOperationsRESTClient) Get(ctx context.Context, req *computepb.Get } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/operations/%v", req.GetProject(), req.GetOperation()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "operation", url.QueryEscape(req.GetOperation()))) @@ -434,6 +445,7 @@ func (c *globalOperationsRESTClient) List(ctx context.Context, req *computepb.Li baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/operations", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -516,6 +528,11 @@ func (c *globalOperationsRESTClient) Wait(ctx context.Context, req *computepb.Wa } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/operations/%v/wait", req.GetProject(), req.GetOperation()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "operation", url.QueryEscape(req.GetOperation()))) diff --git a/compute/apiv1/global_organization_operations_client.go b/compute/apiv1/global_organization_operations_client.go index 33b5b4e0f5c9..9a73a2492992 100644 --- a/compute/apiv1/global_organization_operations_client.go +++ b/compute/apiv1/global_organization_operations_client.go @@ -192,6 +192,7 @@ func (c *globalOrganizationOperationsRESTClient) Delete(ctx context.Context, req baseUrl.Path += fmt.Sprintf("/compute/v1/locations/global/operations/%v", req.GetOperation()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.ParentId != nil { params.Add("parentId", fmt.Sprintf("%v", req.GetParentId())) } @@ -252,6 +253,7 @@ func (c *globalOrganizationOperationsRESTClient) Get(ctx context.Context, req *c baseUrl.Path += fmt.Sprintf("/compute/v1/locations/global/operations/%v", req.GetOperation()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.ParentId != nil { params.Add("parentId", fmt.Sprintf("%v", req.GetParentId())) } @@ -325,6 +327,7 @@ func (c *globalOrganizationOperationsRESTClient) List(ctx context.Context, req * baseUrl.Path += fmt.Sprintf("/compute/v1/locations/global/operations") params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/compute/apiv1/global_public_delegated_prefixes_client.go b/compute/apiv1/global_public_delegated_prefixes_client.go index a16b3ccdedde..a39fe4a11cb9 100644 --- a/compute/apiv1/global_public_delegated_prefixes_client.go +++ b/compute/apiv1/global_public_delegated_prefixes_client.go @@ -225,6 +225,7 @@ func (c *globalPublicDelegatedPrefixesRESTClient) Delete(ctx context.Context, re baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/publicDelegatedPrefixes/%v", req.GetProject(), req.GetPublicDelegatedPrefix()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -291,6 +292,11 @@ func (c *globalPublicDelegatedPrefixesRESTClient) Get(ctx context.Context, req * } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/publicDelegatedPrefixes/%v", req.GetProject(), req.GetPublicDelegatedPrefix()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "public_delegated_prefix", url.QueryEscape(req.GetPublicDelegatedPrefix()))) @@ -352,6 +358,7 @@ func (c *globalPublicDelegatedPrefixesRESTClient) Insert(ctx context.Context, re baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/publicDelegatedPrefixes", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -432,6 +439,7 @@ func (c *globalPublicDelegatedPrefixesRESTClient) List(ctx context.Context, req baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/publicDelegatedPrefixes", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -522,6 +530,7 @@ func (c *globalPublicDelegatedPrefixesRESTClient) Patch(ctx context.Context, req baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/publicDelegatedPrefixes/%v", req.GetProject(), req.GetPublicDelegatedPrefix()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } diff --git a/compute/apiv1/health_checks_client.go b/compute/apiv1/health_checks_client.go index 63e87f2ff134..d9928d66b1a8 100644 --- a/compute/apiv1/health_checks_client.go +++ b/compute/apiv1/health_checks_client.go @@ -255,6 +255,7 @@ func (c *healthChecksRESTClient) AggregatedList(ctx context.Context, req *comput baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/aggregated/healthChecks", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -348,6 +349,7 @@ func (c *healthChecksRESTClient) Delete(ctx context.Context, req *computepb.Dele baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/healthChecks/%v", req.GetProject(), req.GetHealthCheck()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -414,6 +416,11 @@ func (c *healthChecksRESTClient) Get(ctx context.Context, req *computepb.GetHeal } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/healthChecks/%v", req.GetProject(), req.GetHealthCheck()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "health_check", url.QueryEscape(req.GetHealthCheck()))) @@ -475,6 +482,7 @@ func (c *healthChecksRESTClient) Insert(ctx context.Context, req *computepb.Inse baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/healthChecks", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -555,6 +563,7 @@ func (c *healthChecksRESTClient) List(ctx context.Context, req *computepb.ListHe baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/healthChecks", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -645,6 +654,7 @@ func (c *healthChecksRESTClient) Patch(ctx context.Context, req *computepb.Patch baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/healthChecks/%v", req.GetProject(), req.GetHealthCheck()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -719,6 +729,7 @@ func (c *healthChecksRESTClient) Update(ctx context.Context, req *computepb.Upda baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/healthChecks/%v", req.GetProject(), req.GetHealthCheck()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } diff --git a/compute/apiv1/image_family_views_client.go b/compute/apiv1/image_family_views_client.go index b9afe2d58e41..4a47aa601ca0 100644 --- a/compute/apiv1/image_family_views_client.go +++ b/compute/apiv1/image_family_views_client.go @@ -172,6 +172,11 @@ func (c *imageFamilyViewsRESTClient) Get(ctx context.Context, req *computepb.Get } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/imageFamilyViews/%v", req.GetProject(), req.GetZone(), req.GetFamily()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "zone", url.QueryEscape(req.GetZone()), "family", url.QueryEscape(req.GetFamily()))) diff --git a/compute/apiv1/images_client.go b/compute/apiv1/images_client.go index f2baccc991cc..ad731d5e8e33 100644 --- a/compute/apiv1/images_client.go +++ b/compute/apiv1/images_client.go @@ -273,6 +273,7 @@ func (c *imagesRESTClient) Delete(ctx context.Context, req *computepb.DeleteImag baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/images/%v", req.GetProject(), req.GetImage()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -347,6 +348,7 @@ func (c *imagesRESTClient) Deprecate(ctx context.Context, req *computepb.Depreca baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/images/%v/deprecate", req.GetProject(), req.GetImage()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -413,6 +415,11 @@ func (c *imagesRESTClient) Get(ctx context.Context, req *computepb.GetImageReque } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/images/%v", req.GetProject(), req.GetImage()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "image", url.QueryEscape(req.GetImage()))) @@ -466,6 +473,11 @@ func (c *imagesRESTClient) GetFromFamily(ctx context.Context, req *computepb.Get } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/images/family/%v", req.GetProject(), req.GetFamily()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "family", url.QueryEscape(req.GetFamily()))) @@ -520,6 +532,7 @@ func (c *imagesRESTClient) GetIamPolicy(ctx context.Context, req *computepb.GetI baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/images/%v/getIamPolicy", req.GetProject(), req.GetResource()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.OptionsRequestedPolicyVersion != nil { params.Add("optionsRequestedPolicyVersion", fmt.Sprintf("%v", req.GetOptionsRequestedPolicyVersion())) } @@ -587,6 +600,7 @@ func (c *imagesRESTClient) Insert(ctx context.Context, req *computepb.InsertImag baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/images", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.ForceCreate != nil { params.Add("forceCreate", fmt.Sprintf("%v", req.GetForceCreate())) } @@ -670,6 +684,7 @@ func (c *imagesRESTClient) List(ctx context.Context, req *computepb.ListImagesRe baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/images", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -760,6 +775,7 @@ func (c *imagesRESTClient) Patch(ctx context.Context, req *computepb.PatchImageR baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/images/%v", req.GetProject(), req.GetImage()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -833,6 +849,11 @@ func (c *imagesRESTClient) SetIamPolicy(ctx context.Context, req *computepb.SetI } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/images/%v/setIamPolicy", req.GetProject(), req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "resource", url.QueryEscape(req.GetResource()))) @@ -893,6 +914,11 @@ func (c *imagesRESTClient) SetLabels(ctx context.Context, req *computepb.SetLabe } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/images/%v/setLabels", req.GetProject(), req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "resource", url.QueryEscape(req.GetResource()))) @@ -960,6 +986,11 @@ func (c *imagesRESTClient) TestIamPermissions(ctx context.Context, req *computep } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/images/%v/testIamPermissions", req.GetProject(), req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "resource", url.QueryEscape(req.GetResource()))) diff --git a/compute/apiv1/instance_group_managers_client.go b/compute/apiv1/instance_group_managers_client.go index 7e1b8ba409a1..a2c45128f11e 100644 --- a/compute/apiv1/instance_group_managers_client.go +++ b/compute/apiv1/instance_group_managers_client.go @@ -353,6 +353,7 @@ func (c *instanceGroupManagersRESTClient) AbandonInstances(ctx context.Context, baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instanceGroupManagers/%v/abandonInstances", req.GetProject(), req.GetZone(), req.GetInstanceGroupManager()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -434,6 +435,7 @@ func (c *instanceGroupManagersRESTClient) AggregatedList(ctx context.Context, re baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/aggregated/instanceGroupManagers", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -533,6 +535,11 @@ func (c *instanceGroupManagersRESTClient) ApplyUpdatesToInstances(ctx context.Co } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instanceGroupManagers/%v/applyUpdatesToInstances", req.GetProject(), req.GetZone(), req.GetInstanceGroupManager()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "zone", url.QueryEscape(req.GetZone()), "instance_group_manager", url.QueryEscape(req.GetInstanceGroupManager()))) @@ -602,6 +609,7 @@ func (c *instanceGroupManagersRESTClient) CreateInstances(ctx context.Context, r baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instanceGroupManagers/%v/createInstances", req.GetProject(), req.GetZone(), req.GetInstanceGroupManager()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -670,6 +678,7 @@ func (c *instanceGroupManagersRESTClient) Delete(ctx context.Context, req *compu baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instanceGroupManagers/%v", req.GetProject(), req.GetZone(), req.GetInstanceGroupManager()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -745,6 +754,7 @@ func (c *instanceGroupManagersRESTClient) DeleteInstances(ctx context.Context, r baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instanceGroupManagers/%v/deleteInstances", req.GetProject(), req.GetZone(), req.GetInstanceGroupManager()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -819,6 +829,11 @@ func (c *instanceGroupManagersRESTClient) DeletePerInstanceConfigs(ctx context.C } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instanceGroupManagers/%v/deletePerInstanceConfigs", req.GetProject(), req.GetZone(), req.GetInstanceGroupManager()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "zone", url.QueryEscape(req.GetZone()), "instance_group_manager", url.QueryEscape(req.GetInstanceGroupManager()))) @@ -880,6 +895,11 @@ func (c *instanceGroupManagersRESTClient) Get(ctx context.Context, req *computep } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instanceGroupManagers/%v", req.GetProject(), req.GetZone(), req.GetInstanceGroupManager()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "zone", url.QueryEscape(req.GetZone()), "instance_group_manager", url.QueryEscape(req.GetInstanceGroupManager()))) @@ -941,6 +961,7 @@ func (c *instanceGroupManagersRESTClient) Insert(ctx context.Context, req *compu baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instanceGroupManagers", req.GetProject(), req.GetZone()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -1022,6 +1043,7 @@ func (c *instanceGroupManagersRESTClient) List(ctx context.Context, req *compute baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instanceGroupManagers", req.GetProject(), req.GetZone()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1118,6 +1140,7 @@ func (c *instanceGroupManagersRESTClient) ListErrors(ctx context.Context, req *c baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instanceGroupManagers/%v/listErrors", req.GetProject(), req.GetZone(), req.GetInstanceGroupManager()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1214,6 +1237,7 @@ func (c *instanceGroupManagersRESTClient) ListManagedInstances(ctx context.Conte baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instanceGroupManagers/%v/listManagedInstances", req.GetProject(), req.GetZone(), req.GetInstanceGroupManager()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1310,6 +1334,7 @@ func (c *instanceGroupManagersRESTClient) ListPerInstanceConfigs(ctx context.Con baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instanceGroupManagers/%v/listPerInstanceConfigs", req.GetProject(), req.GetZone(), req.GetInstanceGroupManager()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1400,6 +1425,7 @@ func (c *instanceGroupManagersRESTClient) Patch(ctx context.Context, req *comput baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instanceGroupManagers/%v", req.GetProject(), req.GetZone(), req.GetInstanceGroupManager()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -1475,6 +1501,7 @@ func (c *instanceGroupManagersRESTClient) PatchPerInstanceConfigs(ctx context.Co baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instanceGroupManagers/%v/patchPerInstanceConfigs", req.GetProject(), req.GetZone(), req.GetInstanceGroupManager()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -1550,6 +1577,7 @@ func (c *instanceGroupManagersRESTClient) RecreateInstances(ctx context.Context, baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instanceGroupManagers/%v/recreateInstances", req.GetProject(), req.GetZone(), req.GetInstanceGroupManager()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -1618,6 +1646,7 @@ func (c *instanceGroupManagersRESTClient) Resize(ctx context.Context, req *compu baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instanceGroupManagers/%v/resize", req.GetProject(), req.GetZone(), req.GetInstanceGroupManager()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -1694,6 +1723,7 @@ func (c *instanceGroupManagersRESTClient) SetInstanceTemplate(ctx context.Contex baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instanceGroupManagers/%v/setInstanceTemplate", req.GetProject(), req.GetZone(), req.GetInstanceGroupManager()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -1769,6 +1799,7 @@ func (c *instanceGroupManagersRESTClient) SetTargetPools(ctx context.Context, re baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instanceGroupManagers/%v/setTargetPools", req.GetProject(), req.GetZone(), req.GetInstanceGroupManager()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -1844,6 +1875,7 @@ func (c *instanceGroupManagersRESTClient) UpdatePerInstanceConfigs(ctx context.C baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instanceGroupManagers/%v/updatePerInstanceConfigs", req.GetProject(), req.GetZone(), req.GetInstanceGroupManager()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } diff --git a/compute/apiv1/instance_groups_client.go b/compute/apiv1/instance_groups_client.go index 3bc522200490..db7a62f18bc8 100644 --- a/compute/apiv1/instance_groups_client.go +++ b/compute/apiv1/instance_groups_client.go @@ -265,6 +265,7 @@ func (c *instanceGroupsRESTClient) AddInstances(ctx context.Context, req *comput baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instanceGroups/%v/addInstances", req.GetProject(), req.GetZone(), req.GetInstanceGroup()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -346,6 +347,7 @@ func (c *instanceGroupsRESTClient) AggregatedList(ctx context.Context, req *comp baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/aggregated/instanceGroups", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -439,6 +441,7 @@ func (c *instanceGroupsRESTClient) Delete(ctx context.Context, req *computepb.De baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instanceGroups/%v", req.GetProject(), req.GetZone(), req.GetInstanceGroup()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -506,6 +509,11 @@ func (c *instanceGroupsRESTClient) Get(ctx context.Context, req *computepb.GetIn } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instanceGroups/%v", req.GetProject(), req.GetZone(), req.GetInstanceGroup()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "zone", url.QueryEscape(req.GetZone()), "instance_group", url.QueryEscape(req.GetInstanceGroup()))) @@ -567,6 +575,7 @@ func (c *instanceGroupsRESTClient) Insert(ctx context.Context, req *computepb.In baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instanceGroups", req.GetProject(), req.GetZone()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -648,6 +657,7 @@ func (c *instanceGroupsRESTClient) List(ctx context.Context, req *computepb.List baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instanceGroups", req.GetProject(), req.GetZone()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -750,6 +760,7 @@ func (c *instanceGroupsRESTClient) ListInstances(ctx context.Context, req *compu baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instanceGroups/%v/listInstances", req.GetProject(), req.GetZone(), req.GetInstanceGroup()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -840,6 +851,7 @@ func (c *instanceGroupsRESTClient) RemoveInstances(ctx context.Context, req *com baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instanceGroups/%v/removeInstances", req.GetProject(), req.GetZone(), req.GetInstanceGroup()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -915,6 +927,7 @@ func (c *instanceGroupsRESTClient) SetNamedPorts(ctx context.Context, req *compu baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instanceGroups/%v/setNamedPorts", req.GetProject(), req.GetZone(), req.GetInstanceGroup()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } diff --git a/compute/apiv1/instance_templates_client.go b/compute/apiv1/instance_templates_client.go index ba60b67cd610..95dcc036efcd 100644 --- a/compute/apiv1/instance_templates_client.go +++ b/compute/apiv1/instance_templates_client.go @@ -241,6 +241,7 @@ func (c *instanceTemplatesRESTClient) Delete(ctx context.Context, req *computepb baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/instanceTemplates/%v", req.GetProject(), req.GetInstanceTemplate()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -307,6 +308,11 @@ func (c *instanceTemplatesRESTClient) Get(ctx context.Context, req *computepb.Ge } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/instanceTemplates/%v", req.GetProject(), req.GetInstanceTemplate()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "instance_template", url.QueryEscape(req.GetInstanceTemplate()))) @@ -361,6 +367,7 @@ func (c *instanceTemplatesRESTClient) GetIamPolicy(ctx context.Context, req *com baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/instanceTemplates/%v/getIamPolicy", req.GetProject(), req.GetResource()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.OptionsRequestedPolicyVersion != nil { params.Add("optionsRequestedPolicyVersion", fmt.Sprintf("%v", req.GetOptionsRequestedPolicyVersion())) } @@ -428,6 +435,7 @@ func (c *instanceTemplatesRESTClient) Insert(ctx context.Context, req *computepb baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/instanceTemplates", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -508,6 +516,7 @@ func (c *instanceTemplatesRESTClient) List(ctx context.Context, req *computepb.L baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/instanceTemplates", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -597,6 +606,11 @@ func (c *instanceTemplatesRESTClient) SetIamPolicy(ctx context.Context, req *com } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/instanceTemplates/%v/setIamPolicy", req.GetProject(), req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "resource", url.QueryEscape(req.GetResource()))) @@ -657,6 +671,11 @@ func (c *instanceTemplatesRESTClient) TestIamPermissions(ctx context.Context, re } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/instanceTemplates/%v/testIamPermissions", req.GetProject(), req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "resource", url.QueryEscape(req.GetResource()))) diff --git a/compute/apiv1/instances_client.go b/compute/apiv1/instances_client.go index a3c64feb1730..aa88ddc412e0 100644 --- a/compute/apiv1/instances_client.go +++ b/compute/apiv1/instances_client.go @@ -553,6 +553,7 @@ func (c *instancesRESTClient) AddAccessConfig(ctx context.Context, req *computep baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instances/%v/addAccessConfig", req.GetProject(), req.GetZone(), req.GetInstance()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("networkInterface", fmt.Sprintf("%v", req.GetNetworkInterface())) if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) @@ -629,6 +630,7 @@ func (c *instancesRESTClient) AddResourcePolicies(ctx context.Context, req *comp baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instances/%v/addResourcePolicies", req.GetProject(), req.GetZone(), req.GetInstance()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -710,6 +712,7 @@ func (c *instancesRESTClient) AggregatedList(ctx context.Context, req *computepb baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/aggregated/instances", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -810,6 +813,7 @@ func (c *instancesRESTClient) AttachDisk(ctx context.Context, req *computepb.Att baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instances/%v/attachDisk", req.GetProject(), req.GetZone(), req.GetInstance()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.ForceAttach != nil { params.Add("forceAttach", fmt.Sprintf("%v", req.GetForceAttach())) } @@ -888,6 +892,7 @@ func (c *instancesRESTClient) BulkInsert(ctx context.Context, req *computepb.Bul baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instances/bulkInsert", req.GetProject(), req.GetZone()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -956,6 +961,7 @@ func (c *instancesRESTClient) Delete(ctx context.Context, req *computepb.DeleteI baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instances/%v", req.GetProject(), req.GetZone(), req.GetInstance()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -1024,6 +1030,7 @@ func (c *instancesRESTClient) DeleteAccessConfig(ctx context.Context, req *compu baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instances/%v/deleteAccessConfig", req.GetProject(), req.GetZone(), req.GetInstance()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("accessConfig", fmt.Sprintf("%v", req.GetAccessConfig())) params.Add("networkInterface", fmt.Sprintf("%v", req.GetNetworkInterface())) if req != nil && req.RequestId != nil { @@ -1094,6 +1101,7 @@ func (c *instancesRESTClient) DetachDisk(ctx context.Context, req *computepb.Det baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instances/%v/detachDisk", req.GetProject(), req.GetZone(), req.GetInstance()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("deviceName", fmt.Sprintf("%v", req.GetDeviceName())) if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) @@ -1162,6 +1170,11 @@ func (c *instancesRESTClient) Get(ctx context.Context, req *computepb.GetInstanc } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instances/%v", req.GetProject(), req.GetZone(), req.GetInstance()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "zone", url.QueryEscape(req.GetZone()), "instance", url.QueryEscape(req.GetInstance()))) @@ -1216,6 +1229,7 @@ func (c *instancesRESTClient) GetEffectiveFirewalls(ctx context.Context, req *co baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instances/%v/getEffectiveFirewalls", req.GetProject(), req.GetZone(), req.GetInstance()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("networkInterface", fmt.Sprintf("%v", req.GetNetworkInterface())) baseUrl.RawQuery = params.Encode() @@ -1274,6 +1288,7 @@ func (c *instancesRESTClient) GetGuestAttributes(ctx context.Context, req *compu baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instances/%v/getGuestAttributes", req.GetProject(), req.GetZone(), req.GetInstance()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.QueryPath != nil { params.Add("queryPath", fmt.Sprintf("%v", req.GetQueryPath())) } @@ -1337,6 +1352,7 @@ func (c *instancesRESTClient) GetIamPolicy(ctx context.Context, req *computepb.G baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instances/%v/getIamPolicy", req.GetProject(), req.GetZone(), req.GetResource()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.OptionsRequestedPolicyVersion != nil { params.Add("optionsRequestedPolicyVersion", fmt.Sprintf("%v", req.GetOptionsRequestedPolicyVersion())) } @@ -1396,6 +1412,11 @@ func (c *instancesRESTClient) GetScreenshot(ctx context.Context, req *computepb. } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instances/%v/screenshot", req.GetProject(), req.GetZone(), req.GetInstance()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "zone", url.QueryEscape(req.GetZone()), "instance", url.QueryEscape(req.GetInstance()))) @@ -1450,6 +1471,7 @@ func (c *instancesRESTClient) GetSerialPortOutput(ctx context.Context, req *comp baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instances/%v/serialPort", req.GetProject(), req.GetZone(), req.GetInstance()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Port != nil { params.Add("port", fmt.Sprintf("%v", req.GetPort())) } @@ -1512,6 +1534,11 @@ func (c *instancesRESTClient) GetShieldedInstanceIdentity(ctx context.Context, r } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instances/%v/getShieldedInstanceIdentity", req.GetProject(), req.GetZone(), req.GetInstance()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "zone", url.QueryEscape(req.GetZone()), "instance", url.QueryEscape(req.GetInstance()))) @@ -1573,6 +1600,7 @@ func (c *instancesRESTClient) Insert(ctx context.Context, req *computepb.InsertI baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instances", req.GetProject(), req.GetZone()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -1660,6 +1688,7 @@ func (c *instancesRESTClient) List(ctx context.Context, req *computepb.ListInsta baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instances", req.GetProject(), req.GetZone()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1756,6 +1785,7 @@ func (c *instancesRESTClient) ListReferrers(ctx context.Context, req *computepb. baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instances/%v/referrers", req.GetProject(), req.GetZone(), req.GetInstance()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1846,6 +1876,7 @@ func (c *instancesRESTClient) RemoveResourcePolicies(ctx context.Context, req *c baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instances/%v/removeResourcePolicies", req.GetProject(), req.GetZone(), req.GetInstance()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -1914,6 +1945,7 @@ func (c *instancesRESTClient) Reset(ctx context.Context, req *computepb.ResetIns baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instances/%v/reset", req.GetProject(), req.GetZone(), req.GetInstance()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -1982,6 +2014,7 @@ func (c *instancesRESTClient) Resume(ctx context.Context, req *computepb.ResumeI baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instances/%v/resume", req.GetProject(), req.GetZone(), req.GetInstance()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -2049,6 +2082,11 @@ func (c *instancesRESTClient) SendDiagnosticInterrupt(ctx context.Context, req * } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instances/%v/sendDiagnosticInterrupt", req.GetProject(), req.GetZone(), req.GetInstance()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "zone", url.QueryEscape(req.GetZone()), "instance", url.QueryEscape(req.GetInstance()))) @@ -2103,6 +2141,7 @@ func (c *instancesRESTClient) SetDeletionProtection(ctx context.Context, req *co baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instances/%v/setDeletionProtection", req.GetProject(), req.GetZone(), req.GetResource()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.DeletionProtection != nil { params.Add("deletionProtection", fmt.Sprintf("%v", req.GetDeletionProtection())) } @@ -2174,6 +2213,7 @@ func (c *instancesRESTClient) SetDiskAutoDelete(ctx context.Context, req *comput baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instances/%v/setDiskAutoDelete", req.GetProject(), req.GetZone(), req.GetInstance()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("autoDelete", fmt.Sprintf("%v", req.GetAutoDelete())) params.Add("deviceName", fmt.Sprintf("%v", req.GetDeviceName())) if req != nil && req.RequestId != nil { @@ -2250,6 +2290,11 @@ func (c *instancesRESTClient) SetIamPolicy(ctx context.Context, req *computepb.S } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instances/%v/setIamPolicy", req.GetProject(), req.GetZone(), req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "zone", url.QueryEscape(req.GetZone()), "resource", url.QueryEscape(req.GetResource()))) @@ -2311,6 +2356,7 @@ func (c *instancesRESTClient) SetLabels(ctx context.Context, req *computepb.SetL baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instances/%v/setLabels", req.GetProject(), req.GetZone(), req.GetInstance()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -2386,6 +2432,7 @@ func (c *instancesRESTClient) SetMachineResources(ctx context.Context, req *comp baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instances/%v/setMachineResources", req.GetProject(), req.GetZone(), req.GetInstance()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -2461,6 +2508,7 @@ func (c *instancesRESTClient) SetMachineType(ctx context.Context, req *computepb baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instances/%v/setMachineType", req.GetProject(), req.GetZone(), req.GetInstance()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -2536,6 +2584,7 @@ func (c *instancesRESTClient) SetMetadata(ctx context.Context, req *computepb.Se baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instances/%v/setMetadata", req.GetProject(), req.GetZone(), req.GetInstance()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -2611,6 +2660,7 @@ func (c *instancesRESTClient) SetMinCpuPlatform(ctx context.Context, req *comput baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instances/%v/setMinCpuPlatform", req.GetProject(), req.GetZone(), req.GetInstance()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -2686,6 +2736,7 @@ func (c *instancesRESTClient) SetScheduling(ctx context.Context, req *computepb. baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instances/%v/setScheduling", req.GetProject(), req.GetZone(), req.GetInstance()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -2761,6 +2812,7 @@ func (c *instancesRESTClient) SetServiceAccount(ctx context.Context, req *comput baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instances/%v/setServiceAccount", req.GetProject(), req.GetZone(), req.GetInstance()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -2836,6 +2888,7 @@ func (c *instancesRESTClient) SetShieldedInstanceIntegrityPolicy(ctx context.Con baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instances/%v/setShieldedInstanceIntegrityPolicy", req.GetProject(), req.GetZone(), req.GetInstance()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -2911,6 +2964,7 @@ func (c *instancesRESTClient) SetTags(ctx context.Context, req *computepb.SetTag baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instances/%v/setTags", req.GetProject(), req.GetZone(), req.GetInstance()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -2978,6 +3032,11 @@ func (c *instancesRESTClient) SimulateMaintenanceEvent(ctx context.Context, req } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instances/%v/simulateMaintenanceEvent", req.GetProject(), req.GetZone(), req.GetInstance()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "zone", url.QueryEscape(req.GetZone()), "instance", url.QueryEscape(req.GetInstance()))) @@ -3040,6 +3099,7 @@ func (c *instancesRESTClient) Start(ctx context.Context, req *computepb.StartIns baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instances/%v/start", req.GetProject(), req.GetZone(), req.GetInstance()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -3115,6 +3175,7 @@ func (c *instancesRESTClient) StartWithEncryptionKey(ctx context.Context, req *c baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instances/%v/startWithEncryptionKey", req.GetProject(), req.GetZone(), req.GetInstance()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -3183,6 +3244,7 @@ func (c *instancesRESTClient) Stop(ctx context.Context, req *computepb.StopInsta baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instances/%v/stop", req.GetProject(), req.GetZone(), req.GetInstance()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -3251,6 +3313,7 @@ func (c *instancesRESTClient) Suspend(ctx context.Context, req *computepb.Suspen baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instances/%v/suspend", req.GetProject(), req.GetZone(), req.GetInstance()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -3325,6 +3388,11 @@ func (c *instancesRESTClient) TestIamPermissions(ctx context.Context, req *compu } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instances/%v/testIamPermissions", req.GetProject(), req.GetZone(), req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "zone", url.QueryEscape(req.GetZone()), "resource", url.QueryEscape(req.GetResource()))) @@ -3386,6 +3454,7 @@ func (c *instancesRESTClient) Update(ctx context.Context, req *computepb.UpdateI baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instances/%v", req.GetProject(), req.GetZone(), req.GetInstance()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.MinimalAction != nil { params.Add("minimalAction", fmt.Sprintf("%v", req.GetMinimalAction())) } @@ -3467,6 +3536,7 @@ func (c *instancesRESTClient) UpdateAccessConfig(ctx context.Context, req *compu baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instances/%v/updateAccessConfig", req.GetProject(), req.GetZone(), req.GetInstance()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("networkInterface", fmt.Sprintf("%v", req.GetNetworkInterface())) if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) @@ -3543,6 +3613,7 @@ func (c *instancesRESTClient) UpdateDisplayDevice(ctx context.Context, req *comp baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instances/%v/updateDisplayDevice", req.GetProject(), req.GetZone(), req.GetInstance()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -3618,6 +3689,7 @@ func (c *instancesRESTClient) UpdateNetworkInterface(ctx context.Context, req *c baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instances/%v/updateNetworkInterface", req.GetProject(), req.GetZone(), req.GetInstance()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("networkInterface", fmt.Sprintf("%v", req.GetNetworkInterface())) if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) @@ -3694,6 +3766,7 @@ func (c *instancesRESTClient) UpdateShieldedInstanceConfig(ctx context.Context, baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/instances/%v/updateShieldedInstanceConfig", req.GetProject(), req.GetZone(), req.GetInstance()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } diff --git a/compute/apiv1/interconnect_attachments_client.go b/compute/apiv1/interconnect_attachments_client.go index 969ba7931653..e73c72bc9ab4 100644 --- a/compute/apiv1/interconnect_attachments_client.go +++ b/compute/apiv1/interconnect_attachments_client.go @@ -255,6 +255,7 @@ func (c *interconnectAttachmentsRESTClient) AggregatedList(ctx context.Context, baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/aggregated/interconnectAttachments", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -348,6 +349,7 @@ func (c *interconnectAttachmentsRESTClient) Delete(ctx context.Context, req *com baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/interconnectAttachments/%v", req.GetProject(), req.GetRegion(), req.GetInterconnectAttachment()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -415,6 +417,11 @@ func (c *interconnectAttachmentsRESTClient) Get(ctx context.Context, req *comput } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/interconnectAttachments/%v", req.GetProject(), req.GetRegion(), req.GetInterconnectAttachment()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "interconnect_attachment", url.QueryEscape(req.GetInterconnectAttachment()))) @@ -476,6 +483,7 @@ func (c *interconnectAttachmentsRESTClient) Insert(ctx context.Context, req *com baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/interconnectAttachments", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -560,6 +568,7 @@ func (c *interconnectAttachmentsRESTClient) List(ctx context.Context, req *compu baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/interconnectAttachments", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -650,6 +659,7 @@ func (c *interconnectAttachmentsRESTClient) Patch(ctx context.Context, req *comp baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/interconnectAttachments/%v", req.GetProject(), req.GetRegion(), req.GetInterconnectAttachment()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -725,6 +735,7 @@ func (c *interconnectAttachmentsRESTClient) SetLabels(ctx context.Context, req * baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/interconnectAttachments/%v/setLabels", req.GetProject(), req.GetRegion(), req.GetResource()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } diff --git a/compute/apiv1/interconnect_locations_client.go b/compute/apiv1/interconnect_locations_client.go index a6a511561445..4fa97c655a7a 100644 --- a/compute/apiv1/interconnect_locations_client.go +++ b/compute/apiv1/interconnect_locations_client.go @@ -183,6 +183,11 @@ func (c *interconnectLocationsRESTClient) Get(ctx context.Context, req *computep } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/interconnectLocations/%v", req.GetProject(), req.GetInterconnectLocation()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "interconnect_location", url.QueryEscape(req.GetInterconnectLocation()))) @@ -250,6 +255,7 @@ func (c *interconnectLocationsRESTClient) List(ctx context.Context, req *compute baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/interconnectLocations", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/compute/apiv1/interconnects_client.go b/compute/apiv1/interconnects_client.go index 89714f6a6f93..ba2e0ad03672 100644 --- a/compute/apiv1/interconnects_client.go +++ b/compute/apiv1/interconnects_client.go @@ -241,6 +241,7 @@ func (c *interconnectsRESTClient) Delete(ctx context.Context, req *computepb.Del baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/interconnects/%v", req.GetProject(), req.GetInterconnect()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -307,6 +308,11 @@ func (c *interconnectsRESTClient) Get(ctx context.Context, req *computepb.GetInt } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/interconnects/%v", req.GetProject(), req.GetInterconnect()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "interconnect", url.QueryEscape(req.GetInterconnect()))) @@ -360,6 +366,11 @@ func (c *interconnectsRESTClient) GetDiagnostics(ctx context.Context, req *compu } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/interconnects/%v/getDiagnostics", req.GetProject(), req.GetInterconnect()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "interconnect", url.QueryEscape(req.GetInterconnect()))) @@ -421,6 +432,7 @@ func (c *interconnectsRESTClient) Insert(ctx context.Context, req *computepb.Ins baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/interconnects", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -501,6 +513,7 @@ func (c *interconnectsRESTClient) List(ctx context.Context, req *computepb.ListI baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/interconnects", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -591,6 +604,7 @@ func (c *interconnectsRESTClient) Patch(ctx context.Context, req *computepb.Patc baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/interconnects/%v", req.GetProject(), req.GetInterconnect()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -664,6 +678,11 @@ func (c *interconnectsRESTClient) SetLabels(ctx context.Context, req *computepb. } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/interconnects/%v/setLabels", req.GetProject(), req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "resource", url.QueryEscape(req.GetResource()))) diff --git a/compute/apiv1/license_codes_client.go b/compute/apiv1/license_codes_client.go index 3c873ed63951..a60040d333c6 100644 --- a/compute/apiv1/license_codes_client.go +++ b/compute/apiv1/license_codes_client.go @@ -181,6 +181,11 @@ func (c *licenseCodesRESTClient) Get(ctx context.Context, req *computepb.GetLice } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/licenseCodes/%v", req.GetProject(), req.GetLicenseCode()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "license_code", url.QueryEscape(req.GetLicenseCode()))) @@ -241,6 +246,11 @@ func (c *licenseCodesRESTClient) TestIamPermissions(ctx context.Context, req *co } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/licenseCodes/%v/testIamPermissions", req.GetProject(), req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "resource", url.QueryEscape(req.GetResource()))) diff --git a/compute/apiv1/licenses_client.go b/compute/apiv1/licenses_client.go index a4b894ff83af..0d46704b59ca 100644 --- a/compute/apiv1/licenses_client.go +++ b/compute/apiv1/licenses_client.go @@ -241,6 +241,7 @@ func (c *licensesRESTClient) Delete(ctx context.Context, req *computepb.DeleteLi baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/licenses/%v", req.GetProject(), req.GetLicense()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -307,6 +308,11 @@ func (c *licensesRESTClient) Get(ctx context.Context, req *computepb.GetLicenseR } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/licenses/%v", req.GetProject(), req.GetLicense()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "license", url.QueryEscape(req.GetLicense()))) @@ -361,6 +367,7 @@ func (c *licensesRESTClient) GetIamPolicy(ctx context.Context, req *computepb.Ge baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/licenses/%v/getIamPolicy", req.GetProject(), req.GetResource()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.OptionsRequestedPolicyVersion != nil { params.Add("optionsRequestedPolicyVersion", fmt.Sprintf("%v", req.GetOptionsRequestedPolicyVersion())) } @@ -428,6 +435,7 @@ func (c *licensesRESTClient) Insert(ctx context.Context, req *computepb.InsertLi baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/licenses", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -508,6 +516,7 @@ func (c *licensesRESTClient) List(ctx context.Context, req *computepb.ListLicens baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/licenses", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -597,6 +606,11 @@ func (c *licensesRESTClient) SetIamPolicy(ctx context.Context, req *computepb.Se } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/licenses/%v/setIamPolicy", req.GetProject(), req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "resource", url.QueryEscape(req.GetResource()))) @@ -657,6 +671,11 @@ func (c *licensesRESTClient) TestIamPermissions(ctx context.Context, req *comput } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/licenses/%v/testIamPermissions", req.GetProject(), req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "resource", url.QueryEscape(req.GetResource()))) diff --git a/compute/apiv1/machine_images_client.go b/compute/apiv1/machine_images_client.go index 624022258b1a..d092081c1011 100644 --- a/compute/apiv1/machine_images_client.go +++ b/compute/apiv1/machine_images_client.go @@ -241,6 +241,7 @@ func (c *machineImagesRESTClient) Delete(ctx context.Context, req *computepb.Del baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/machineImages/%v", req.GetProject(), req.GetMachineImage()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -307,6 +308,11 @@ func (c *machineImagesRESTClient) Get(ctx context.Context, req *computepb.GetMac } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/machineImages/%v", req.GetProject(), req.GetMachineImage()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "machine_image", url.QueryEscape(req.GetMachineImage()))) @@ -361,6 +367,7 @@ func (c *machineImagesRESTClient) GetIamPolicy(ctx context.Context, req *compute baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/machineImages/%v/getIamPolicy", req.GetProject(), req.GetResource()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.OptionsRequestedPolicyVersion != nil { params.Add("optionsRequestedPolicyVersion", fmt.Sprintf("%v", req.GetOptionsRequestedPolicyVersion())) } @@ -428,6 +435,7 @@ func (c *machineImagesRESTClient) Insert(ctx context.Context, req *computepb.Ins baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/machineImages", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -511,6 +519,7 @@ func (c *machineImagesRESTClient) List(ctx context.Context, req *computepb.ListM baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/machineImages", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -600,6 +609,11 @@ func (c *machineImagesRESTClient) SetIamPolicy(ctx context.Context, req *compute } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/machineImages/%v/setIamPolicy", req.GetProject(), req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "resource", url.QueryEscape(req.GetResource()))) @@ -660,6 +674,11 @@ func (c *machineImagesRESTClient) TestIamPermissions(ctx context.Context, req *c } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/machineImages/%v/testIamPermissions", req.GetProject(), req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "resource", url.QueryEscape(req.GetResource()))) diff --git a/compute/apiv1/machine_types_client.go b/compute/apiv1/machine_types_client.go index d17a2e015395..68a28b91f6c1 100644 --- a/compute/apiv1/machine_types_client.go +++ b/compute/apiv1/machine_types_client.go @@ -206,6 +206,7 @@ func (c *machineTypesRESTClient) AggregatedList(ctx context.Context, req *comput baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/aggregated/machineTypes", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -298,6 +299,11 @@ func (c *machineTypesRESTClient) Get(ctx context.Context, req *computepb.GetMach } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/machineTypes/%v", req.GetProject(), req.GetZone(), req.GetMachineType()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "zone", url.QueryEscape(req.GetZone()), "machine_type", url.QueryEscape(req.GetMachineType()))) @@ -365,6 +371,7 @@ func (c *machineTypesRESTClient) List(ctx context.Context, req *computepb.ListMa baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/machineTypes", req.GetProject(), req.GetZone()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/compute/apiv1/network_edge_security_services_client.go b/compute/apiv1/network_edge_security_services_client.go index f5d2af95a93b..06dc3cb6aa65 100644 --- a/compute/apiv1/network_edge_security_services_client.go +++ b/compute/apiv1/network_edge_security_services_client.go @@ -239,6 +239,7 @@ func (c *networkEdgeSecurityServicesRESTClient) AggregatedList(ctx context.Conte baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/aggregated/networkEdgeSecurityServices", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -332,6 +333,7 @@ func (c *networkEdgeSecurityServicesRESTClient) Delete(ctx context.Context, req baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/networkEdgeSecurityServices/%v", req.GetProject(), req.GetRegion(), req.GetNetworkEdgeSecurityService()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -399,6 +401,11 @@ func (c *networkEdgeSecurityServicesRESTClient) Get(ctx context.Context, req *co } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/networkEdgeSecurityServices/%v", req.GetProject(), req.GetRegion(), req.GetNetworkEdgeSecurityService()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "network_edge_security_service", url.QueryEscape(req.GetNetworkEdgeSecurityService()))) @@ -460,6 +467,7 @@ func (c *networkEdgeSecurityServicesRESTClient) Insert(ctx context.Context, req baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/networkEdgeSecurityServices", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -538,6 +546,7 @@ func (c *networkEdgeSecurityServicesRESTClient) Patch(ctx context.Context, req * baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/networkEdgeSecurityServices/%v", req.GetProject(), req.GetRegion(), req.GetNetworkEdgeSecurityService()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Paths != nil { params.Add("paths", fmt.Sprintf("%v", req.GetPaths())) } diff --git a/compute/apiv1/network_endpoint_groups_client.go b/compute/apiv1/network_endpoint_groups_client.go index e2278cef9525..ce7fc5155f16 100644 --- a/compute/apiv1/network_endpoint_groups_client.go +++ b/compute/apiv1/network_endpoint_groups_client.go @@ -271,6 +271,7 @@ func (c *networkEndpointGroupsRESTClient) AggregatedList(ctx context.Context, re baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/aggregated/networkEndpointGroups", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -371,6 +372,7 @@ func (c *networkEndpointGroupsRESTClient) AttachNetworkEndpoints(ctx context.Con baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/networkEndpointGroups/%v/attachNetworkEndpoints", req.GetProject(), req.GetZone(), req.GetNetworkEndpointGroup()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -439,6 +441,7 @@ func (c *networkEndpointGroupsRESTClient) Delete(ctx context.Context, req *compu baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/networkEndpointGroups/%v", req.GetProject(), req.GetZone(), req.GetNetworkEndpointGroup()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -514,6 +517,7 @@ func (c *networkEndpointGroupsRESTClient) DetachNetworkEndpoints(ctx context.Con baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/networkEndpointGroups/%v/detachNetworkEndpoints", req.GetProject(), req.GetZone(), req.GetNetworkEndpointGroup()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -581,6 +585,11 @@ func (c *networkEndpointGroupsRESTClient) Get(ctx context.Context, req *computep } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/networkEndpointGroups/%v", req.GetProject(), req.GetZone(), req.GetNetworkEndpointGroup()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "zone", url.QueryEscape(req.GetZone()), "network_endpoint_group", url.QueryEscape(req.GetNetworkEndpointGroup()))) @@ -642,6 +651,7 @@ func (c *networkEndpointGroupsRESTClient) Insert(ctx context.Context, req *compu baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/networkEndpointGroups", req.GetProject(), req.GetZone()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -723,6 +733,7 @@ func (c *networkEndpointGroupsRESTClient) List(ctx context.Context, req *compute baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/networkEndpointGroups", req.GetProject(), req.GetZone()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -825,6 +836,7 @@ func (c *networkEndpointGroupsRESTClient) ListNetworkEndpoints(ctx context.Conte baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/networkEndpointGroups/%v/listNetworkEndpoints", req.GetProject(), req.GetZone(), req.GetNetworkEndpointGroup()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -914,6 +926,11 @@ func (c *networkEndpointGroupsRESTClient) TestIamPermissions(ctx context.Context } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/networkEndpointGroups/%v/testIamPermissions", req.GetProject(), req.GetZone(), req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "zone", url.QueryEscape(req.GetZone()), "resource", url.QueryEscape(req.GetResource()))) diff --git a/compute/apiv1/network_firewall_policies_client.go b/compute/apiv1/network_firewall_policies_client.go index 2ff804157f57..294a9527c47a 100644 --- a/compute/apiv1/network_firewall_policies_client.go +++ b/compute/apiv1/network_firewall_policies_client.go @@ -320,6 +320,7 @@ func (c *networkFirewallPoliciesRESTClient) AddAssociation(ctx context.Context, baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/firewallPolicies/%v/addAssociation", req.GetProject(), req.GetFirewallPolicy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.ReplaceExistingAssociation != nil { params.Add("replaceExistingAssociation", fmt.Sprintf("%v", req.GetReplaceExistingAssociation())) } @@ -397,6 +398,7 @@ func (c *networkFirewallPoliciesRESTClient) AddRule(ctx context.Context, req *co baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/firewallPolicies/%v/addRule", req.GetProject(), req.GetFirewallPolicy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.MaxPriority != nil { params.Add("maxPriority", fmt.Sprintf("%v", req.GetMaxPriority())) } @@ -470,6 +472,7 @@ func (c *networkFirewallPoliciesRESTClient) CloneRules(ctx context.Context, req baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/firewallPolicies/%v/cloneRules", req.GetProject(), req.GetFirewallPolicy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -540,6 +543,7 @@ func (c *networkFirewallPoliciesRESTClient) Delete(ctx context.Context, req *com baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/firewallPolicies/%v", req.GetProject(), req.GetFirewallPolicy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -606,6 +610,11 @@ func (c *networkFirewallPoliciesRESTClient) Get(ctx context.Context, req *comput } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/firewallPolicies/%v", req.GetProject(), req.GetFirewallPolicy()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "firewall_policy", url.QueryEscape(req.GetFirewallPolicy()))) @@ -660,6 +669,7 @@ func (c *networkFirewallPoliciesRESTClient) GetAssociation(ctx context.Context, baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/firewallPolicies/%v/getAssociation", req.GetProject(), req.GetFirewallPolicy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Name != nil { params.Add("name", fmt.Sprintf("%v", req.GetName())) } @@ -720,6 +730,7 @@ func (c *networkFirewallPoliciesRESTClient) GetIamPolicy(ctx context.Context, re baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/firewallPolicies/%v/getIamPolicy", req.GetProject(), req.GetResource()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.OptionsRequestedPolicyVersion != nil { params.Add("optionsRequestedPolicyVersion", fmt.Sprintf("%v", req.GetOptionsRequestedPolicyVersion())) } @@ -780,6 +791,7 @@ func (c *networkFirewallPoliciesRESTClient) GetRule(ctx context.Context, req *co baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/firewallPolicies/%v/getRule", req.GetProject(), req.GetFirewallPolicy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Priority != nil { params.Add("priority", fmt.Sprintf("%v", req.GetPriority())) } @@ -847,6 +859,7 @@ func (c *networkFirewallPoliciesRESTClient) Insert(ctx context.Context, req *com baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/firewallPolicies", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -927,6 +940,7 @@ func (c *networkFirewallPoliciesRESTClient) List(ctx context.Context, req *compu baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/firewallPolicies", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1017,6 +1031,7 @@ func (c *networkFirewallPoliciesRESTClient) Patch(ctx context.Context, req *comp baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/firewallPolicies/%v", req.GetProject(), req.GetFirewallPolicy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -1091,6 +1106,7 @@ func (c *networkFirewallPoliciesRESTClient) PatchRule(ctx context.Context, req * baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/firewallPolicies/%v/patchRule", req.GetProject(), req.GetFirewallPolicy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Priority != nil { params.Add("priority", fmt.Sprintf("%v", req.GetPriority())) } @@ -1161,6 +1177,7 @@ func (c *networkFirewallPoliciesRESTClient) RemoveAssociation(ctx context.Contex baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/firewallPolicies/%v/removeAssociation", req.GetProject(), req.GetFirewallPolicy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Name != nil { params.Add("name", fmt.Sprintf("%v", req.GetName())) } @@ -1231,6 +1248,7 @@ func (c *networkFirewallPoliciesRESTClient) RemoveRule(ctx context.Context, req baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/firewallPolicies/%v/removeRule", req.GetProject(), req.GetFirewallPolicy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Priority != nil { params.Add("priority", fmt.Sprintf("%v", req.GetPriority())) } @@ -1307,6 +1325,11 @@ func (c *networkFirewallPoliciesRESTClient) SetIamPolicy(ctx context.Context, re } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/firewallPolicies/%v/setIamPolicy", req.GetProject(), req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "resource", url.QueryEscape(req.GetResource()))) @@ -1367,6 +1390,11 @@ func (c *networkFirewallPoliciesRESTClient) TestIamPermissions(ctx context.Conte } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/firewallPolicies/%v/testIamPermissions", req.GetProject(), req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "resource", url.QueryEscape(req.GetResource()))) diff --git a/compute/apiv1/networks_client.go b/compute/apiv1/networks_client.go index 179eeb9e10a1..f99da89ecd13 100644 --- a/compute/apiv1/networks_client.go +++ b/compute/apiv1/networks_client.go @@ -280,6 +280,7 @@ func (c *networksRESTClient) AddPeering(ctx context.Context, req *computepb.AddP baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/networks/%v/addPeering", req.GetProject(), req.GetNetwork()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -347,6 +348,7 @@ func (c *networksRESTClient) Delete(ctx context.Context, req *computepb.DeleteNe baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/networks/%v", req.GetProject(), req.GetNetwork()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -413,6 +415,11 @@ func (c *networksRESTClient) Get(ctx context.Context, req *computepb.GetNetworkR } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/networks/%v", req.GetProject(), req.GetNetwork()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "network", url.QueryEscape(req.GetNetwork()))) @@ -466,6 +473,11 @@ func (c *networksRESTClient) GetEffectiveFirewalls(ctx context.Context, req *com } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/networks/%v/getEffectiveFirewalls", req.GetProject(), req.GetNetwork()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "network", url.QueryEscape(req.GetNetwork()))) @@ -527,6 +539,7 @@ func (c *networksRESTClient) Insert(ctx context.Context, req *computepb.InsertNe baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/networks", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -607,6 +620,7 @@ func (c *networksRESTClient) List(ctx context.Context, req *computepb.ListNetwor baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/networks", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -703,6 +717,7 @@ func (c *networksRESTClient) ListPeeringRoutes(ctx context.Context, req *compute baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/networks/%v/listPeeringRoutes", req.GetProject(), req.GetNetwork()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Direction != nil { params.Add("direction", fmt.Sprintf("%v", req.GetDirection())) } @@ -802,6 +817,7 @@ func (c *networksRESTClient) Patch(ctx context.Context, req *computepb.PatchNetw baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/networks/%v", req.GetProject(), req.GetNetwork()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -876,6 +892,7 @@ func (c *networksRESTClient) RemovePeering(ctx context.Context, req *computepb.R baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/networks/%v/removePeering", req.GetProject(), req.GetNetwork()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -943,6 +960,7 @@ func (c *networksRESTClient) SwitchToCustomMode(ctx context.Context, req *comput baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/networks/%v/switchToCustomMode", req.GetProject(), req.GetNetwork()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -1017,6 +1035,7 @@ func (c *networksRESTClient) UpdatePeering(ctx context.Context, req *computepb.U baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/networks/%v/updatePeering", req.GetProject(), req.GetNetwork()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } diff --git a/compute/apiv1/node_groups_client.go b/compute/apiv1/node_groups_client.go index f36f9435e75b..c8b3e862278d 100644 --- a/compute/apiv1/node_groups_client.go +++ b/compute/apiv1/node_groups_client.go @@ -297,6 +297,7 @@ func (c *nodeGroupsRESTClient) AddNodes(ctx context.Context, req *computepb.AddN baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/nodeGroups/%v/addNodes", req.GetProject(), req.GetZone(), req.GetNodeGroup()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -378,6 +379,7 @@ func (c *nodeGroupsRESTClient) AggregatedList(ctx context.Context, req *computep baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/aggregated/nodeGroups", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -471,6 +473,7 @@ func (c *nodeGroupsRESTClient) Delete(ctx context.Context, req *computepb.Delete baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/nodeGroups/%v", req.GetProject(), req.GetZone(), req.GetNodeGroup()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -546,6 +549,7 @@ func (c *nodeGroupsRESTClient) DeleteNodes(ctx context.Context, req *computepb.D baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/nodeGroups/%v/deleteNodes", req.GetProject(), req.GetZone(), req.GetNodeGroup()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -613,6 +617,11 @@ func (c *nodeGroupsRESTClient) Get(ctx context.Context, req *computepb.GetNodeGr } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/nodeGroups/%v", req.GetProject(), req.GetZone(), req.GetNodeGroup()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "zone", url.QueryEscape(req.GetZone()), "node_group", url.QueryEscape(req.GetNodeGroup()))) @@ -667,6 +676,7 @@ func (c *nodeGroupsRESTClient) GetIamPolicy(ctx context.Context, req *computepb. baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/nodeGroups/%v/getIamPolicy", req.GetProject(), req.GetZone(), req.GetResource()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.OptionsRequestedPolicyVersion != nil { params.Add("optionsRequestedPolicyVersion", fmt.Sprintf("%v", req.GetOptionsRequestedPolicyVersion())) } @@ -734,6 +744,7 @@ func (c *nodeGroupsRESTClient) Insert(ctx context.Context, req *computepb.Insert baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/nodeGroups", req.GetProject(), req.GetZone()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("initialNodeCount", fmt.Sprintf("%v", req.GetInitialNodeCount())) if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) @@ -816,6 +827,7 @@ func (c *nodeGroupsRESTClient) List(ctx context.Context, req *computepb.ListNode baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/nodeGroups", req.GetProject(), req.GetZone()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -912,6 +924,7 @@ func (c *nodeGroupsRESTClient) ListNodes(ctx context.Context, req *computepb.Lis baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/nodeGroups/%v/listNodes", req.GetProject(), req.GetZone(), req.GetNodeGroup()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1002,6 +1015,7 @@ func (c *nodeGroupsRESTClient) Patch(ctx context.Context, req *computepb.PatchNo baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/nodeGroups/%v", req.GetProject(), req.GetZone(), req.GetNodeGroup()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -1076,6 +1090,11 @@ func (c *nodeGroupsRESTClient) SetIamPolicy(ctx context.Context, req *computepb. } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/nodeGroups/%v/setIamPolicy", req.GetProject(), req.GetZone(), req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "zone", url.QueryEscape(req.GetZone()), "resource", url.QueryEscape(req.GetResource()))) @@ -1137,6 +1156,7 @@ func (c *nodeGroupsRESTClient) SetNodeTemplate(ctx context.Context, req *compute baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/nodeGroups/%v/setNodeTemplate", req.GetProject(), req.GetZone(), req.GetNodeGroup()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -1211,6 +1231,11 @@ func (c *nodeGroupsRESTClient) TestIamPermissions(ctx context.Context, req *comp } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/nodeGroups/%v/testIamPermissions", req.GetProject(), req.GetZone(), req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "zone", url.QueryEscape(req.GetZone()), "resource", url.QueryEscape(req.GetResource()))) diff --git a/compute/apiv1/node_templates_client.go b/compute/apiv1/node_templates_client.go index 7f8a971fa54f..ee0dcaefef1e 100644 --- a/compute/apiv1/node_templates_client.go +++ b/compute/apiv1/node_templates_client.go @@ -263,6 +263,7 @@ func (c *nodeTemplatesRESTClient) AggregatedList(ctx context.Context, req *compu baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/aggregated/nodeTemplates", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -356,6 +357,7 @@ func (c *nodeTemplatesRESTClient) Delete(ctx context.Context, req *computepb.Del baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/nodeTemplates/%v", req.GetProject(), req.GetRegion(), req.GetNodeTemplate()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -423,6 +425,11 @@ func (c *nodeTemplatesRESTClient) Get(ctx context.Context, req *computepb.GetNod } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/nodeTemplates/%v", req.GetProject(), req.GetRegion(), req.GetNodeTemplate()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "node_template", url.QueryEscape(req.GetNodeTemplate()))) @@ -477,6 +484,7 @@ func (c *nodeTemplatesRESTClient) GetIamPolicy(ctx context.Context, req *compute baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/nodeTemplates/%v/getIamPolicy", req.GetProject(), req.GetRegion(), req.GetResource()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.OptionsRequestedPolicyVersion != nil { params.Add("optionsRequestedPolicyVersion", fmt.Sprintf("%v", req.GetOptionsRequestedPolicyVersion())) } @@ -544,6 +552,7 @@ func (c *nodeTemplatesRESTClient) Insert(ctx context.Context, req *computepb.Ins baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/nodeTemplates", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -625,6 +634,7 @@ func (c *nodeTemplatesRESTClient) List(ctx context.Context, req *computepb.ListN baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/nodeTemplates", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -714,6 +724,11 @@ func (c *nodeTemplatesRESTClient) SetIamPolicy(ctx context.Context, req *compute } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/nodeTemplates/%v/setIamPolicy", req.GetProject(), req.GetRegion(), req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "resource", url.QueryEscape(req.GetResource()))) @@ -774,6 +789,11 @@ func (c *nodeTemplatesRESTClient) TestIamPermissions(ctx context.Context, req *c } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/nodeTemplates/%v/testIamPermissions", req.GetProject(), req.GetRegion(), req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "resource", url.QueryEscape(req.GetResource()))) diff --git a/compute/apiv1/node_types_client.go b/compute/apiv1/node_types_client.go index 08b32e789d2b..751bcd37b442 100644 --- a/compute/apiv1/node_types_client.go +++ b/compute/apiv1/node_types_client.go @@ -206,6 +206,7 @@ func (c *nodeTypesRESTClient) AggregatedList(ctx context.Context, req *computepb baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/aggregated/nodeTypes", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -298,6 +299,11 @@ func (c *nodeTypesRESTClient) Get(ctx context.Context, req *computepb.GetNodeTyp } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/nodeTypes/%v", req.GetProject(), req.GetZone(), req.GetNodeType()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "zone", url.QueryEscape(req.GetZone()), "node_type", url.QueryEscape(req.GetNodeType()))) @@ -365,6 +371,7 @@ func (c *nodeTypesRESTClient) List(ctx context.Context, req *computepb.ListNodeT baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/nodeTypes", req.GetProject(), req.GetZone()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/compute/apiv1/packet_mirrorings_client.go b/compute/apiv1/packet_mirrorings_client.go index dc932c295711..bc0c8a7a8810 100644 --- a/compute/apiv1/packet_mirrorings_client.go +++ b/compute/apiv1/packet_mirrorings_client.go @@ -255,6 +255,7 @@ func (c *packetMirroringsRESTClient) AggregatedList(ctx context.Context, req *co baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/aggregated/packetMirrorings", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -348,6 +349,7 @@ func (c *packetMirroringsRESTClient) Delete(ctx context.Context, req *computepb. baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/packetMirrorings/%v", req.GetProject(), req.GetRegion(), req.GetPacketMirroring()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -415,6 +417,11 @@ func (c *packetMirroringsRESTClient) Get(ctx context.Context, req *computepb.Get } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/packetMirrorings/%v", req.GetProject(), req.GetRegion(), req.GetPacketMirroring()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "packet_mirroring", url.QueryEscape(req.GetPacketMirroring()))) @@ -476,6 +483,7 @@ func (c *packetMirroringsRESTClient) Insert(ctx context.Context, req *computepb. baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/packetMirrorings", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -557,6 +565,7 @@ func (c *packetMirroringsRESTClient) List(ctx context.Context, req *computepb.Li baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/packetMirrorings", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -647,6 +656,7 @@ func (c *packetMirroringsRESTClient) Patch(ctx context.Context, req *computepb.P baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/packetMirrorings/%v", req.GetProject(), req.GetRegion(), req.GetPacketMirroring()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -721,6 +731,11 @@ func (c *packetMirroringsRESTClient) TestIamPermissions(ctx context.Context, req } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/packetMirrorings/%v/testIamPermissions", req.GetProject(), req.GetRegion(), req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "resource", url.QueryEscape(req.GetResource()))) diff --git a/compute/apiv1/projects_client.go b/compute/apiv1/projects_client.go index 893b25feb852..fe25d00664fe 100644 --- a/compute/apiv1/projects_client.go +++ b/compute/apiv1/projects_client.go @@ -289,6 +289,7 @@ func (c *projectsRESTClient) DisableXpnHost(ctx context.Context, req *computepb. baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/disableXpnHost", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -363,6 +364,7 @@ func (c *projectsRESTClient) DisableXpnResource(ctx context.Context, req *comput baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/disableXpnResource", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -430,6 +432,7 @@ func (c *projectsRESTClient) EnableXpnHost(ctx context.Context, req *computepb.E baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/enableXpnHost", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -504,6 +507,7 @@ func (c *projectsRESTClient) EnableXpnResource(ctx context.Context, req *compute baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/enableXpnResource", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -570,6 +574,11 @@ func (c *projectsRESTClient) Get(ctx context.Context, req *computepb.GetProjectR } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v", req.GetProject()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "project", url.QueryEscape(req.GetProject()))) @@ -623,6 +632,11 @@ func (c *projectsRESTClient) GetXpnHost(ctx context.Context, req *computepb.GetX } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/getXpnHost", req.GetProject()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "project", url.QueryEscape(req.GetProject()))) @@ -690,6 +704,7 @@ func (c *projectsRESTClient) GetXpnResources(ctx context.Context, req *computepb baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/getXpnResources", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -792,6 +807,7 @@ func (c *projectsRESTClient) ListXpnHosts(ctx context.Context, req *computepb.Li baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/listXpnHosts", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -882,6 +898,7 @@ func (c *projectsRESTClient) MoveDisk(ctx context.Context, req *computepb.MoveDi baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/moveDisk", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -956,6 +973,7 @@ func (c *projectsRESTClient) MoveInstance(ctx context.Context, req *computepb.Mo baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/moveInstance", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -1030,6 +1048,7 @@ func (c *projectsRESTClient) SetCommonInstanceMetadata(ctx context.Context, req baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/setCommonInstanceMetadata", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -1104,6 +1123,7 @@ func (c *projectsRESTClient) SetDefaultNetworkTier(ctx context.Context, req *com baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/setDefaultNetworkTier", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -1178,6 +1198,7 @@ func (c *projectsRESTClient) SetUsageExportBucket(ctx context.Context, req *comp baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/setUsageExportBucket", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } diff --git a/compute/apiv1/public_advertised_prefixes_client.go b/compute/apiv1/public_advertised_prefixes_client.go index 9357b5e5cbfa..3932a7777532 100644 --- a/compute/apiv1/public_advertised_prefixes_client.go +++ b/compute/apiv1/public_advertised_prefixes_client.go @@ -225,6 +225,7 @@ func (c *publicAdvertisedPrefixesRESTClient) Delete(ctx context.Context, req *co baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/publicAdvertisedPrefixes/%v", req.GetProject(), req.GetPublicAdvertisedPrefix()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -291,6 +292,11 @@ func (c *publicAdvertisedPrefixesRESTClient) Get(ctx context.Context, req *compu } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/publicAdvertisedPrefixes/%v", req.GetProject(), req.GetPublicAdvertisedPrefix()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "public_advertised_prefix", url.QueryEscape(req.GetPublicAdvertisedPrefix()))) @@ -352,6 +358,7 @@ func (c *publicAdvertisedPrefixesRESTClient) Insert(ctx context.Context, req *co baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/publicAdvertisedPrefixes", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -432,6 +439,7 @@ func (c *publicAdvertisedPrefixesRESTClient) List(ctx context.Context, req *comp baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/publicAdvertisedPrefixes", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -522,6 +530,7 @@ func (c *publicAdvertisedPrefixesRESTClient) Patch(ctx context.Context, req *com baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/publicAdvertisedPrefixes/%v", req.GetProject(), req.GetPublicAdvertisedPrefix()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } diff --git a/compute/apiv1/public_delegated_prefixes_client.go b/compute/apiv1/public_delegated_prefixes_client.go index 2409a1c07516..f69fa1b8eb09 100644 --- a/compute/apiv1/public_delegated_prefixes_client.go +++ b/compute/apiv1/public_delegated_prefixes_client.go @@ -247,6 +247,7 @@ func (c *publicDelegatedPrefixesRESTClient) AggregatedList(ctx context.Context, baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/aggregated/publicDelegatedPrefixes", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -340,6 +341,7 @@ func (c *publicDelegatedPrefixesRESTClient) Delete(ctx context.Context, req *com baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/publicDelegatedPrefixes/%v", req.GetProject(), req.GetRegion(), req.GetPublicDelegatedPrefix()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -407,6 +409,11 @@ func (c *publicDelegatedPrefixesRESTClient) Get(ctx context.Context, req *comput } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/publicDelegatedPrefixes/%v", req.GetProject(), req.GetRegion(), req.GetPublicDelegatedPrefix()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "public_delegated_prefix", url.QueryEscape(req.GetPublicDelegatedPrefix()))) @@ -468,6 +475,7 @@ func (c *publicDelegatedPrefixesRESTClient) Insert(ctx context.Context, req *com baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/publicDelegatedPrefixes", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -549,6 +557,7 @@ func (c *publicDelegatedPrefixesRESTClient) List(ctx context.Context, req *compu baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/publicDelegatedPrefixes", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -639,6 +648,7 @@ func (c *publicDelegatedPrefixesRESTClient) Patch(ctx context.Context, req *comp baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/publicDelegatedPrefixes/%v", req.GetProject(), req.GetRegion(), req.GetPublicDelegatedPrefix()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } diff --git a/compute/apiv1/region_autoscalers_client.go b/compute/apiv1/region_autoscalers_client.go index a49f60668c64..bdd3b83dca32 100644 --- a/compute/apiv1/region_autoscalers_client.go +++ b/compute/apiv1/region_autoscalers_client.go @@ -233,6 +233,7 @@ func (c *regionAutoscalersRESTClient) Delete(ctx context.Context, req *computepb baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/autoscalers/%v", req.GetProject(), req.GetRegion(), req.GetAutoscaler()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -300,6 +301,11 @@ func (c *regionAutoscalersRESTClient) Get(ctx context.Context, req *computepb.Ge } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/autoscalers/%v", req.GetProject(), req.GetRegion(), req.GetAutoscaler()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "autoscaler", url.QueryEscape(req.GetAutoscaler()))) @@ -361,6 +367,7 @@ func (c *regionAutoscalersRESTClient) Insert(ctx context.Context, req *computepb baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/autoscalers", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -442,6 +449,7 @@ func (c *regionAutoscalersRESTClient) List(ctx context.Context, req *computepb.L baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/autoscalers", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -532,6 +540,7 @@ func (c *regionAutoscalersRESTClient) Patch(ctx context.Context, req *computepb. baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/autoscalers", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Autoscaler != nil { params.Add("autoscaler", fmt.Sprintf("%v", req.GetAutoscaler())) } @@ -610,6 +619,7 @@ func (c *regionAutoscalersRESTClient) Update(ctx context.Context, req *computepb baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/autoscalers", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Autoscaler != nil { params.Add("autoscaler", fmt.Sprintf("%v", req.GetAutoscaler())) } diff --git a/compute/apiv1/region_backend_services_client.go b/compute/apiv1/region_backend_services_client.go index 01fc37019584..711e88cf07c2 100644 --- a/compute/apiv1/region_backend_services_client.go +++ b/compute/apiv1/region_backend_services_client.go @@ -257,6 +257,7 @@ func (c *regionBackendServicesRESTClient) Delete(ctx context.Context, req *compu baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/backendServices/%v", req.GetProject(), req.GetRegion(), req.GetBackendService()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -324,6 +325,11 @@ func (c *regionBackendServicesRESTClient) Get(ctx context.Context, req *computep } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/backendServices/%v", req.GetProject(), req.GetRegion(), req.GetBackendService()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "backend_service", url.QueryEscape(req.GetBackendService()))) @@ -384,6 +390,11 @@ func (c *regionBackendServicesRESTClient) GetHealth(ctx context.Context, req *co } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/backendServices/%v/getHealth", req.GetProject(), req.GetRegion(), req.GetBackendService()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "backend_service", url.QueryEscape(req.GetBackendService()))) @@ -438,6 +449,7 @@ func (c *regionBackendServicesRESTClient) GetIamPolicy(ctx context.Context, req baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/backendServices/%v/getIamPolicy", req.GetProject(), req.GetRegion(), req.GetResource()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.OptionsRequestedPolicyVersion != nil { params.Add("optionsRequestedPolicyVersion", fmt.Sprintf("%v", req.GetOptionsRequestedPolicyVersion())) } @@ -505,6 +517,7 @@ func (c *regionBackendServicesRESTClient) Insert(ctx context.Context, req *compu baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/backendServices", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -586,6 +599,7 @@ func (c *regionBackendServicesRESTClient) List(ctx context.Context, req *compute baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/backendServices", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -676,6 +690,7 @@ func (c *regionBackendServicesRESTClient) Patch(ctx context.Context, req *comput baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/backendServices/%v", req.GetProject(), req.GetRegion(), req.GetBackendService()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -750,6 +765,11 @@ func (c *regionBackendServicesRESTClient) SetIamPolicy(ctx context.Context, req } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/backendServices/%v/setIamPolicy", req.GetProject(), req.GetRegion(), req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "resource", url.QueryEscape(req.GetResource()))) @@ -811,6 +831,7 @@ func (c *regionBackendServicesRESTClient) Update(ctx context.Context, req *compu baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/backendServices/%v", req.GetProject(), req.GetRegion(), req.GetBackendService()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } diff --git a/compute/apiv1/region_commitments_client.go b/compute/apiv1/region_commitments_client.go index 67333e59394a..5cd65079f687 100644 --- a/compute/apiv1/region_commitments_client.go +++ b/compute/apiv1/region_commitments_client.go @@ -239,6 +239,7 @@ func (c *regionCommitmentsRESTClient) AggregatedList(ctx context.Context, req *c baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/aggregated/commitments", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -331,6 +332,11 @@ func (c *regionCommitmentsRESTClient) Get(ctx context.Context, req *computepb.Ge } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/commitments/%v", req.GetProject(), req.GetRegion(), req.GetCommitment()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "commitment", url.QueryEscape(req.GetCommitment()))) @@ -392,6 +398,7 @@ func (c *regionCommitmentsRESTClient) Insert(ctx context.Context, req *computepb baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/commitments", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -473,6 +480,7 @@ func (c *regionCommitmentsRESTClient) List(ctx context.Context, req *computepb.L baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/commitments", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -563,6 +571,7 @@ func (c *regionCommitmentsRESTClient) Update(ctx context.Context, req *computepb baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/commitments/%v", req.GetProject(), req.GetRegion(), req.GetCommitment()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Paths != nil { params.Add("paths", fmt.Sprintf("%v", req.GetPaths())) } diff --git a/compute/apiv1/region_disk_types_client.go b/compute/apiv1/region_disk_types_client.go index 127c074f78c6..e99c54932a1c 100644 --- a/compute/apiv1/region_disk_types_client.go +++ b/compute/apiv1/region_disk_types_client.go @@ -183,6 +183,11 @@ func (c *regionDiskTypesRESTClient) Get(ctx context.Context, req *computepb.GetR } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/diskTypes/%v", req.GetProject(), req.GetRegion(), req.GetDiskType()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "disk_type", url.QueryEscape(req.GetDiskType()))) @@ -250,6 +255,7 @@ func (c *regionDiskTypesRESTClient) List(ctx context.Context, req *computepb.Lis baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/diskTypes", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/compute/apiv1/region_disks_client.go b/compute/apiv1/region_disks_client.go index 06c59714731d..c19ee7e6f127 100644 --- a/compute/apiv1/region_disks_client.go +++ b/compute/apiv1/region_disks_client.go @@ -288,6 +288,7 @@ func (c *regionDisksRESTClient) AddResourcePolicies(ctx context.Context, req *co baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/disks/%v/addResourcePolicies", req.GetProject(), req.GetRegion(), req.GetDisk()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -363,6 +364,7 @@ func (c *regionDisksRESTClient) CreateSnapshot(ctx context.Context, req *compute baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/disks/%v/createSnapshot", req.GetProject(), req.GetRegion(), req.GetDisk()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -431,6 +433,7 @@ func (c *regionDisksRESTClient) Delete(ctx context.Context, req *computepb.Delet baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/disks/%v", req.GetProject(), req.GetRegion(), req.GetDisk()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -498,6 +501,11 @@ func (c *regionDisksRESTClient) Get(ctx context.Context, req *computepb.GetRegio } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/disks/%v", req.GetProject(), req.GetRegion(), req.GetDisk()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "disk", url.QueryEscape(req.GetDisk()))) @@ -552,6 +560,7 @@ func (c *regionDisksRESTClient) GetIamPolicy(ctx context.Context, req *computepb baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/disks/%v/getIamPolicy", req.GetProject(), req.GetRegion(), req.GetResource()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.OptionsRequestedPolicyVersion != nil { params.Add("optionsRequestedPolicyVersion", fmt.Sprintf("%v", req.GetOptionsRequestedPolicyVersion())) } @@ -619,6 +628,7 @@ func (c *regionDisksRESTClient) Insert(ctx context.Context, req *computepb.Inser baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/disks", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -703,6 +713,7 @@ func (c *regionDisksRESTClient) List(ctx context.Context, req *computepb.ListReg baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/disks", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -793,6 +804,7 @@ func (c *regionDisksRESTClient) RemoveResourcePolicies(ctx context.Context, req baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/disks/%v/removeResourcePolicies", req.GetProject(), req.GetRegion(), req.GetDisk()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -868,6 +880,7 @@ func (c *regionDisksRESTClient) Resize(ctx context.Context, req *computepb.Resiz baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/disks/%v/resize", req.GetProject(), req.GetRegion(), req.GetDisk()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -942,6 +955,11 @@ func (c *regionDisksRESTClient) SetIamPolicy(ctx context.Context, req *computepb } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/disks/%v/setIamPolicy", req.GetProject(), req.GetRegion(), req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "resource", url.QueryEscape(req.GetResource()))) @@ -1003,6 +1021,7 @@ func (c *regionDisksRESTClient) SetLabels(ctx context.Context, req *computepb.Se baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/disks/%v/setLabels", req.GetProject(), req.GetRegion(), req.GetResource()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -1077,6 +1096,11 @@ func (c *regionDisksRESTClient) TestIamPermissions(ctx context.Context, req *com } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/disks/%v/testIamPermissions", req.GetProject(), req.GetRegion(), req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "resource", url.QueryEscape(req.GetResource()))) diff --git a/compute/apiv1/region_health_check_services_client.go b/compute/apiv1/region_health_check_services_client.go index 935c3366246a..b0cf09ca36b6 100644 --- a/compute/apiv1/region_health_check_services_client.go +++ b/compute/apiv1/region_health_check_services_client.go @@ -225,6 +225,7 @@ func (c *regionHealthCheckServicesRESTClient) Delete(ctx context.Context, req *c baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/healthCheckServices/%v", req.GetProject(), req.GetRegion(), req.GetHealthCheckService()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -292,6 +293,11 @@ func (c *regionHealthCheckServicesRESTClient) Get(ctx context.Context, req *comp } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/healthCheckServices/%v", req.GetProject(), req.GetRegion(), req.GetHealthCheckService()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "health_check_service", url.QueryEscape(req.GetHealthCheckService()))) @@ -353,6 +359,7 @@ func (c *regionHealthCheckServicesRESTClient) Insert(ctx context.Context, req *c baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/healthCheckServices", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -434,6 +441,7 @@ func (c *regionHealthCheckServicesRESTClient) List(ctx context.Context, req *com baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/healthCheckServices", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -524,6 +532,7 @@ func (c *regionHealthCheckServicesRESTClient) Patch(ctx context.Context, req *co baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/healthCheckServices/%v", req.GetProject(), req.GetRegion(), req.GetHealthCheckService()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } diff --git a/compute/apiv1/region_health_checks_client.go b/compute/apiv1/region_health_checks_client.go index 8e93a1d868bd..6b6bbf6cc40f 100644 --- a/compute/apiv1/region_health_checks_client.go +++ b/compute/apiv1/region_health_checks_client.go @@ -233,6 +233,7 @@ func (c *regionHealthChecksRESTClient) Delete(ctx context.Context, req *computep baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/healthChecks/%v", req.GetProject(), req.GetRegion(), req.GetHealthCheck()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -300,6 +301,11 @@ func (c *regionHealthChecksRESTClient) Get(ctx context.Context, req *computepb.G } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/healthChecks/%v", req.GetProject(), req.GetRegion(), req.GetHealthCheck()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "health_check", url.QueryEscape(req.GetHealthCheck()))) @@ -361,6 +367,7 @@ func (c *regionHealthChecksRESTClient) Insert(ctx context.Context, req *computep baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/healthChecks", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -442,6 +449,7 @@ func (c *regionHealthChecksRESTClient) List(ctx context.Context, req *computepb. baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/healthChecks", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -532,6 +540,7 @@ func (c *regionHealthChecksRESTClient) Patch(ctx context.Context, req *computepb baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/healthChecks/%v", req.GetProject(), req.GetRegion(), req.GetHealthCheck()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -607,6 +616,7 @@ func (c *regionHealthChecksRESTClient) Update(ctx context.Context, req *computep baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/healthChecks/%v", req.GetProject(), req.GetRegion(), req.GetHealthCheck()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } diff --git a/compute/apiv1/region_instance_group_managers_client.go b/compute/apiv1/region_instance_group_managers_client.go index 379a391fd801..6e3e4e435020 100644 --- a/compute/apiv1/region_instance_group_managers_client.go +++ b/compute/apiv1/region_instance_group_managers_client.go @@ -344,6 +344,7 @@ func (c *regionInstanceGroupManagersRESTClient) AbandonInstances(ctx context.Con baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/instanceGroupManagers/%v/abandonInstances", req.GetProject(), req.GetRegion(), req.GetInstanceGroupManager()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -418,6 +419,11 @@ func (c *regionInstanceGroupManagersRESTClient) ApplyUpdatesToInstances(ctx cont } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/instanceGroupManagers/%v/applyUpdatesToInstances", req.GetProject(), req.GetRegion(), req.GetInstanceGroupManager()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "instance_group_manager", url.QueryEscape(req.GetInstanceGroupManager()))) @@ -487,6 +493,7 @@ func (c *regionInstanceGroupManagersRESTClient) CreateInstances(ctx context.Cont baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/instanceGroupManagers/%v/createInstances", req.GetProject(), req.GetRegion(), req.GetInstanceGroupManager()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -555,6 +562,7 @@ func (c *regionInstanceGroupManagersRESTClient) Delete(ctx context.Context, req baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/instanceGroupManagers/%v", req.GetProject(), req.GetRegion(), req.GetInstanceGroupManager()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -630,6 +638,7 @@ func (c *regionInstanceGroupManagersRESTClient) DeleteInstances(ctx context.Cont baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/instanceGroupManagers/%v/deleteInstances", req.GetProject(), req.GetRegion(), req.GetInstanceGroupManager()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -704,6 +713,11 @@ func (c *regionInstanceGroupManagersRESTClient) DeletePerInstanceConfigs(ctx con } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/instanceGroupManagers/%v/deletePerInstanceConfigs", req.GetProject(), req.GetRegion(), req.GetInstanceGroupManager()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "instance_group_manager", url.QueryEscape(req.GetInstanceGroupManager()))) @@ -765,6 +779,11 @@ func (c *regionInstanceGroupManagersRESTClient) Get(ctx context.Context, req *co } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/instanceGroupManagers/%v", req.GetProject(), req.GetRegion(), req.GetInstanceGroupManager()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "instance_group_manager", url.QueryEscape(req.GetInstanceGroupManager()))) @@ -826,6 +845,7 @@ func (c *regionInstanceGroupManagersRESTClient) Insert(ctx context.Context, req baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/instanceGroupManagers", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -907,6 +927,7 @@ func (c *regionInstanceGroupManagersRESTClient) List(ctx context.Context, req *c baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/instanceGroupManagers", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1003,6 +1024,7 @@ func (c *regionInstanceGroupManagersRESTClient) ListErrors(ctx context.Context, baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/instanceGroupManagers/%v/listErrors", req.GetProject(), req.GetRegion(), req.GetInstanceGroupManager()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1099,6 +1121,7 @@ func (c *regionInstanceGroupManagersRESTClient) ListManagedInstances(ctx context baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/instanceGroupManagers/%v/listManagedInstances", req.GetProject(), req.GetRegion(), req.GetInstanceGroupManager()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1195,6 +1218,7 @@ func (c *regionInstanceGroupManagersRESTClient) ListPerInstanceConfigs(ctx conte baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/instanceGroupManagers/%v/listPerInstanceConfigs", req.GetProject(), req.GetRegion(), req.GetInstanceGroupManager()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1285,6 +1309,7 @@ func (c *regionInstanceGroupManagersRESTClient) Patch(ctx context.Context, req * baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/instanceGroupManagers/%v", req.GetProject(), req.GetRegion(), req.GetInstanceGroupManager()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -1360,6 +1385,7 @@ func (c *regionInstanceGroupManagersRESTClient) PatchPerInstanceConfigs(ctx cont baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/instanceGroupManagers/%v/patchPerInstanceConfigs", req.GetProject(), req.GetRegion(), req.GetInstanceGroupManager()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -1435,6 +1461,7 @@ func (c *regionInstanceGroupManagersRESTClient) RecreateInstances(ctx context.Co baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/instanceGroupManagers/%v/recreateInstances", req.GetProject(), req.GetRegion(), req.GetInstanceGroupManager()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -1503,6 +1530,7 @@ func (c *regionInstanceGroupManagersRESTClient) Resize(ctx context.Context, req baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/instanceGroupManagers/%v/resize", req.GetProject(), req.GetRegion(), req.GetInstanceGroupManager()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -1579,6 +1607,7 @@ func (c *regionInstanceGroupManagersRESTClient) SetInstanceTemplate(ctx context. baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/instanceGroupManagers/%v/setInstanceTemplate", req.GetProject(), req.GetRegion(), req.GetInstanceGroupManager()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -1654,6 +1683,7 @@ func (c *regionInstanceGroupManagersRESTClient) SetTargetPools(ctx context.Conte baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/instanceGroupManagers/%v/setTargetPools", req.GetProject(), req.GetRegion(), req.GetInstanceGroupManager()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -1729,6 +1759,7 @@ func (c *regionInstanceGroupManagersRESTClient) UpdatePerInstanceConfigs(ctx con baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/instanceGroupManagers/%v/updatePerInstanceConfigs", req.GetProject(), req.GetRegion(), req.GetInstanceGroupManager()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } diff --git a/compute/apiv1/region_instance_groups_client.go b/compute/apiv1/region_instance_groups_client.go index e23cb3bc2a9e..289be6c85e97 100644 --- a/compute/apiv1/region_instance_groups_client.go +++ b/compute/apiv1/region_instance_groups_client.go @@ -216,6 +216,11 @@ func (c *regionInstanceGroupsRESTClient) Get(ctx context.Context, req *computepb } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/instanceGroups/%v", req.GetProject(), req.GetRegion(), req.GetInstanceGroup()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "instance_group", url.QueryEscape(req.GetInstanceGroup()))) @@ -283,6 +288,7 @@ func (c *regionInstanceGroupsRESTClient) List(ctx context.Context, req *computep baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/instanceGroups", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -385,6 +391,7 @@ func (c *regionInstanceGroupsRESTClient) ListInstances(ctx context.Context, req baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/instanceGroups/%v/listInstances", req.GetProject(), req.GetRegion(), req.GetInstanceGroup()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -475,6 +482,7 @@ func (c *regionInstanceGroupsRESTClient) SetNamedPorts(ctx context.Context, req baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/instanceGroups/%v/setNamedPorts", req.GetProject(), req.GetRegion(), req.GetInstanceGroup()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } diff --git a/compute/apiv1/region_instances_client.go b/compute/apiv1/region_instances_client.go index 6d90485aac35..3490577ea6a0 100644 --- a/compute/apiv1/region_instances_client.go +++ b/compute/apiv1/region_instances_client.go @@ -197,6 +197,7 @@ func (c *regionInstancesRESTClient) BulkInsert(ctx context.Context, req *compute baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/instances/bulkInsert", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } diff --git a/compute/apiv1/region_network_endpoint_groups_client.go b/compute/apiv1/region_network_endpoint_groups_client.go index b07a44540ac3..8d23ace557e7 100644 --- a/compute/apiv1/region_network_endpoint_groups_client.go +++ b/compute/apiv1/region_network_endpoint_groups_client.go @@ -217,6 +217,7 @@ func (c *regionNetworkEndpointGroupsRESTClient) Delete(ctx context.Context, req baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/networkEndpointGroups/%v", req.GetProject(), req.GetRegion(), req.GetNetworkEndpointGroup()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -284,6 +285,11 @@ func (c *regionNetworkEndpointGroupsRESTClient) Get(ctx context.Context, req *co } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/networkEndpointGroups/%v", req.GetProject(), req.GetRegion(), req.GetNetworkEndpointGroup()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "network_endpoint_group", url.QueryEscape(req.GetNetworkEndpointGroup()))) @@ -345,6 +351,7 @@ func (c *regionNetworkEndpointGroupsRESTClient) Insert(ctx context.Context, req baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/networkEndpointGroups", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -426,6 +433,7 @@ func (c *regionNetworkEndpointGroupsRESTClient) List(ctx context.Context, req *c baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/networkEndpointGroups", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/compute/apiv1/region_network_firewall_policies_client.go b/compute/apiv1/region_network_firewall_policies_client.go index e0ec5d4d4738..3baf9e363440 100644 --- a/compute/apiv1/region_network_firewall_policies_client.go +++ b/compute/apiv1/region_network_firewall_policies_client.go @@ -328,6 +328,7 @@ func (c *regionNetworkFirewallPoliciesRESTClient) AddAssociation(ctx context.Con baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/firewallPolicies/%v/addAssociation", req.GetProject(), req.GetRegion(), req.GetFirewallPolicy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.ReplaceExistingAssociation != nil { params.Add("replaceExistingAssociation", fmt.Sprintf("%v", req.GetReplaceExistingAssociation())) } @@ -406,6 +407,7 @@ func (c *regionNetworkFirewallPoliciesRESTClient) AddRule(ctx context.Context, r baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/firewallPolicies/%v/addRule", req.GetProject(), req.GetRegion(), req.GetFirewallPolicy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.MaxPriority != nil { params.Add("maxPriority", fmt.Sprintf("%v", req.GetMaxPriority())) } @@ -480,6 +482,7 @@ func (c *regionNetworkFirewallPoliciesRESTClient) CloneRules(ctx context.Context baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/firewallPolicies/%v/cloneRules", req.GetProject(), req.GetRegion(), req.GetFirewallPolicy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -551,6 +554,7 @@ func (c *regionNetworkFirewallPoliciesRESTClient) Delete(ctx context.Context, re baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/firewallPolicies/%v", req.GetProject(), req.GetRegion(), req.GetFirewallPolicy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -618,6 +622,11 @@ func (c *regionNetworkFirewallPoliciesRESTClient) Get(ctx context.Context, req * } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/firewallPolicies/%v", req.GetProject(), req.GetRegion(), req.GetFirewallPolicy()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "firewall_policy", url.QueryEscape(req.GetFirewallPolicy()))) @@ -672,6 +681,7 @@ func (c *regionNetworkFirewallPoliciesRESTClient) GetAssociation(ctx context.Con baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/firewallPolicies/%v/getAssociation", req.GetProject(), req.GetRegion(), req.GetFirewallPolicy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Name != nil { params.Add("name", fmt.Sprintf("%v", req.GetName())) } @@ -732,6 +742,7 @@ func (c *regionNetworkFirewallPoliciesRESTClient) GetEffectiveFirewalls(ctx cont baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/firewallPolicies/getEffectiveFirewalls", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("network", fmt.Sprintf("%v", req.GetNetwork())) baseUrl.RawQuery = params.Encode() @@ -790,6 +801,7 @@ func (c *regionNetworkFirewallPoliciesRESTClient) GetIamPolicy(ctx context.Conte baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/firewallPolicies/%v/getIamPolicy", req.GetProject(), req.GetRegion(), req.GetResource()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.OptionsRequestedPolicyVersion != nil { params.Add("optionsRequestedPolicyVersion", fmt.Sprintf("%v", req.GetOptionsRequestedPolicyVersion())) } @@ -850,6 +862,7 @@ func (c *regionNetworkFirewallPoliciesRESTClient) GetRule(ctx context.Context, r baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/firewallPolicies/%v/getRule", req.GetProject(), req.GetRegion(), req.GetFirewallPolicy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Priority != nil { params.Add("priority", fmt.Sprintf("%v", req.GetPriority())) } @@ -917,6 +930,7 @@ func (c *regionNetworkFirewallPoliciesRESTClient) Insert(ctx context.Context, re baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/firewallPolicies", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -998,6 +1012,7 @@ func (c *regionNetworkFirewallPoliciesRESTClient) List(ctx context.Context, req baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/firewallPolicies", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1088,6 +1103,7 @@ func (c *regionNetworkFirewallPoliciesRESTClient) Patch(ctx context.Context, req baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/firewallPolicies/%v", req.GetProject(), req.GetRegion(), req.GetFirewallPolicy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -1163,6 +1179,7 @@ func (c *regionNetworkFirewallPoliciesRESTClient) PatchRule(ctx context.Context, baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/firewallPolicies/%v/patchRule", req.GetProject(), req.GetRegion(), req.GetFirewallPolicy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Priority != nil { params.Add("priority", fmt.Sprintf("%v", req.GetPriority())) } @@ -1234,6 +1251,7 @@ func (c *regionNetworkFirewallPoliciesRESTClient) RemoveAssociation(ctx context. baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/firewallPolicies/%v/removeAssociation", req.GetProject(), req.GetRegion(), req.GetFirewallPolicy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Name != nil { params.Add("name", fmt.Sprintf("%v", req.GetName())) } @@ -1305,6 +1323,7 @@ func (c *regionNetworkFirewallPoliciesRESTClient) RemoveRule(ctx context.Context baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/firewallPolicies/%v/removeRule", req.GetProject(), req.GetRegion(), req.GetFirewallPolicy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Priority != nil { params.Add("priority", fmt.Sprintf("%v", req.GetPriority())) } @@ -1382,6 +1401,11 @@ func (c *regionNetworkFirewallPoliciesRESTClient) SetIamPolicy(ctx context.Conte } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/firewallPolicies/%v/setIamPolicy", req.GetProject(), req.GetRegion(), req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "resource", url.QueryEscape(req.GetResource()))) @@ -1442,6 +1466,11 @@ func (c *regionNetworkFirewallPoliciesRESTClient) TestIamPermissions(ctx context } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/firewallPolicies/%v/testIamPermissions", req.GetProject(), req.GetRegion(), req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "resource", url.QueryEscape(req.GetResource()))) diff --git a/compute/apiv1/region_notification_endpoints_client.go b/compute/apiv1/region_notification_endpoints_client.go index d4245901b905..68f6881666b5 100644 --- a/compute/apiv1/region_notification_endpoints_client.go +++ b/compute/apiv1/region_notification_endpoints_client.go @@ -217,6 +217,7 @@ func (c *regionNotificationEndpointsRESTClient) Delete(ctx context.Context, req baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/notificationEndpoints/%v", req.GetProject(), req.GetRegion(), req.GetNotificationEndpoint()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -284,6 +285,11 @@ func (c *regionNotificationEndpointsRESTClient) Get(ctx context.Context, req *co } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/notificationEndpoints/%v", req.GetProject(), req.GetRegion(), req.GetNotificationEndpoint()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "notification_endpoint", url.QueryEscape(req.GetNotificationEndpoint()))) @@ -345,6 +351,7 @@ func (c *regionNotificationEndpointsRESTClient) Insert(ctx context.Context, req baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/notificationEndpoints", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -426,6 +433,7 @@ func (c *regionNotificationEndpointsRESTClient) List(ctx context.Context, req *c baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/notificationEndpoints", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/compute/apiv1/region_operations_client.go b/compute/apiv1/region_operations_client.go index 2954b99eda59..b1bec5cef3bc 100644 --- a/compute/apiv1/region_operations_client.go +++ b/compute/apiv1/region_operations_client.go @@ -199,6 +199,11 @@ func (c *regionOperationsRESTClient) Delete(ctx context.Context, req *computepb. } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/operations/%v", req.GetProject(), req.GetRegion(), req.GetOperation()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "operation", url.QueryEscape(req.GetOperation()))) @@ -252,6 +257,11 @@ func (c *regionOperationsRESTClient) Get(ctx context.Context, req *computepb.Get } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/operations/%v", req.GetProject(), req.GetRegion(), req.GetOperation()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "operation", url.QueryEscape(req.GetOperation()))) @@ -319,6 +329,7 @@ func (c *regionOperationsRESTClient) List(ctx context.Context, req *computepb.Li baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/operations", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -401,6 +412,11 @@ func (c *regionOperationsRESTClient) Wait(ctx context.Context, req *computepb.Wa } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/operations/%v/wait", req.GetProject(), req.GetRegion(), req.GetOperation()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "operation", url.QueryEscape(req.GetOperation()))) diff --git a/compute/apiv1/region_security_policies_client.go b/compute/apiv1/region_security_policies_client.go index 40243d8695d5..8ab0960f279b 100644 --- a/compute/apiv1/region_security_policies_client.go +++ b/compute/apiv1/region_security_policies_client.go @@ -225,6 +225,7 @@ func (c *regionSecurityPoliciesRESTClient) Delete(ctx context.Context, req *comp baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/securityPolicies/%v", req.GetProject(), req.GetRegion(), req.GetSecurityPolicy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -292,6 +293,11 @@ func (c *regionSecurityPoliciesRESTClient) Get(ctx context.Context, req *compute } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/securityPolicies/%v", req.GetProject(), req.GetRegion(), req.GetSecurityPolicy()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "security_policy", url.QueryEscape(req.GetSecurityPolicy()))) @@ -353,6 +359,7 @@ func (c *regionSecurityPoliciesRESTClient) Insert(ctx context.Context, req *comp baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/securityPolicies", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -437,6 +444,7 @@ func (c *regionSecurityPoliciesRESTClient) List(ctx context.Context, req *comput baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/securityPolicies", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -527,6 +535,7 @@ func (c *regionSecurityPoliciesRESTClient) Patch(ctx context.Context, req *compu baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/securityPolicies/%v", req.GetProject(), req.GetRegion(), req.GetSecurityPolicy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } diff --git a/compute/apiv1/region_ssl_certificates_client.go b/compute/apiv1/region_ssl_certificates_client.go index 16fa5a3d9ef2..f6bcda1f2649 100644 --- a/compute/apiv1/region_ssl_certificates_client.go +++ b/compute/apiv1/region_ssl_certificates_client.go @@ -217,6 +217,7 @@ func (c *regionSslCertificatesRESTClient) Delete(ctx context.Context, req *compu baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/sslCertificates/%v", req.GetProject(), req.GetRegion(), req.GetSslCertificate()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -284,6 +285,11 @@ func (c *regionSslCertificatesRESTClient) Get(ctx context.Context, req *computep } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/sslCertificates/%v", req.GetProject(), req.GetRegion(), req.GetSslCertificate()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "ssl_certificate", url.QueryEscape(req.GetSslCertificate()))) @@ -345,6 +351,7 @@ func (c *regionSslCertificatesRESTClient) Insert(ctx context.Context, req *compu baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/sslCertificates", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -426,6 +433,7 @@ func (c *regionSslCertificatesRESTClient) List(ctx context.Context, req *compute baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/sslCertificates", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/compute/apiv1/region_ssl_policies_client.go b/compute/apiv1/region_ssl_policies_client.go index 70c13bd7ef65..0730009108ad 100644 --- a/compute/apiv1/region_ssl_policies_client.go +++ b/compute/apiv1/region_ssl_policies_client.go @@ -233,6 +233,7 @@ func (c *regionSslPoliciesRESTClient) Delete(ctx context.Context, req *computepb baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/sslPolicies/%v", req.GetProject(), req.GetRegion(), req.GetSslPolicy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -300,6 +301,11 @@ func (c *regionSslPoliciesRESTClient) Get(ctx context.Context, req *computepb.Ge } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/sslPolicies/%v", req.GetProject(), req.GetRegion(), req.GetSslPolicy()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "ssl_policy", url.QueryEscape(req.GetSslPolicy()))) @@ -361,6 +367,7 @@ func (c *regionSslPoliciesRESTClient) Insert(ctx context.Context, req *computepb baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/sslPolicies", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -442,6 +449,7 @@ func (c *regionSslPoliciesRESTClient) List(ctx context.Context, req *computepb.L baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/sslPolicies", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -525,6 +533,7 @@ func (c *regionSslPoliciesRESTClient) ListAvailableFeatures(ctx context.Context, baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/sslPolicies/listAvailableFeatures", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -604,6 +613,7 @@ func (c *regionSslPoliciesRESTClient) Patch(ctx context.Context, req *computepb. baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/sslPolicies/%v", req.GetProject(), req.GetRegion(), req.GetSslPolicy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } diff --git a/compute/apiv1/region_target_http_proxies_client.go b/compute/apiv1/region_target_http_proxies_client.go index a36525ec16d6..bbc10575b59a 100644 --- a/compute/apiv1/region_target_http_proxies_client.go +++ b/compute/apiv1/region_target_http_proxies_client.go @@ -225,6 +225,7 @@ func (c *regionTargetHttpProxiesRESTClient) Delete(ctx context.Context, req *com baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/targetHttpProxies/%v", req.GetProject(), req.GetRegion(), req.GetTargetHttpProxy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -292,6 +293,11 @@ func (c *regionTargetHttpProxiesRESTClient) Get(ctx context.Context, req *comput } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/targetHttpProxies/%v", req.GetProject(), req.GetRegion(), req.GetTargetHttpProxy()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "target_http_proxy", url.QueryEscape(req.GetTargetHttpProxy()))) @@ -353,6 +359,7 @@ func (c *regionTargetHttpProxiesRESTClient) Insert(ctx context.Context, req *com baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/targetHttpProxies", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -434,6 +441,7 @@ func (c *regionTargetHttpProxiesRESTClient) List(ctx context.Context, req *compu baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/targetHttpProxies", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -524,6 +532,7 @@ func (c *regionTargetHttpProxiesRESTClient) SetUrlMap(ctx context.Context, req * baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/targetHttpProxies/%v/setUrlMap", req.GetProject(), req.GetRegion(), req.GetTargetHttpProxy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } diff --git a/compute/apiv1/region_target_https_proxies_client.go b/compute/apiv1/region_target_https_proxies_client.go index 81ea6d44157d..12ded3fca0f9 100644 --- a/compute/apiv1/region_target_https_proxies_client.go +++ b/compute/apiv1/region_target_https_proxies_client.go @@ -241,6 +241,7 @@ func (c *regionTargetHttpsProxiesRESTClient) Delete(ctx context.Context, req *co baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/targetHttpsProxies/%v", req.GetProject(), req.GetRegion(), req.GetTargetHttpsProxy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -308,6 +309,11 @@ func (c *regionTargetHttpsProxiesRESTClient) Get(ctx context.Context, req *compu } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/targetHttpsProxies/%v", req.GetProject(), req.GetRegion(), req.GetTargetHttpsProxy()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "target_https_proxy", url.QueryEscape(req.GetTargetHttpsProxy()))) @@ -369,6 +375,7 @@ func (c *regionTargetHttpsProxiesRESTClient) Insert(ctx context.Context, req *co baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/targetHttpsProxies", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -450,6 +457,7 @@ func (c *regionTargetHttpsProxiesRESTClient) List(ctx context.Context, req *comp baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/targetHttpsProxies", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -540,6 +548,7 @@ func (c *regionTargetHttpsProxiesRESTClient) Patch(ctx context.Context, req *com baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/targetHttpsProxies/%v", req.GetProject(), req.GetRegion(), req.GetTargetHttpsProxy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -615,6 +624,7 @@ func (c *regionTargetHttpsProxiesRESTClient) SetSslCertificates(ctx context.Cont baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/targetHttpsProxies/%v/setSslCertificates", req.GetProject(), req.GetRegion(), req.GetTargetHttpsProxy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -690,6 +700,7 @@ func (c *regionTargetHttpsProxiesRESTClient) SetUrlMap(ctx context.Context, req baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/targetHttpsProxies/%v/setUrlMap", req.GetProject(), req.GetRegion(), req.GetTargetHttpsProxy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } diff --git a/compute/apiv1/region_target_tcp_proxies_client.go b/compute/apiv1/region_target_tcp_proxies_client.go index 0e405b1e9a19..7ec5501bcbfe 100644 --- a/compute/apiv1/region_target_tcp_proxies_client.go +++ b/compute/apiv1/region_target_tcp_proxies_client.go @@ -217,6 +217,7 @@ func (c *regionTargetTcpProxiesRESTClient) Delete(ctx context.Context, req *comp baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/targetTcpProxies/%v", req.GetProject(), req.GetRegion(), req.GetTargetTcpProxy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -284,6 +285,11 @@ func (c *regionTargetTcpProxiesRESTClient) Get(ctx context.Context, req *compute } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/targetTcpProxies/%v", req.GetProject(), req.GetRegion(), req.GetTargetTcpProxy()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "target_tcp_proxy", url.QueryEscape(req.GetTargetTcpProxy()))) @@ -345,6 +351,7 @@ func (c *regionTargetTcpProxiesRESTClient) Insert(ctx context.Context, req *comp baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/targetTcpProxies", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -426,6 +433,7 @@ func (c *regionTargetTcpProxiesRESTClient) List(ctx context.Context, req *comput baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/targetTcpProxies", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/compute/apiv1/region_url_maps_client.go b/compute/apiv1/region_url_maps_client.go index 047cfc3a6ef6..366585a1702e 100644 --- a/compute/apiv1/region_url_maps_client.go +++ b/compute/apiv1/region_url_maps_client.go @@ -241,6 +241,7 @@ func (c *regionUrlMapsRESTClient) Delete(ctx context.Context, req *computepb.Del baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/urlMaps/%v", req.GetProject(), req.GetRegion(), req.GetUrlMap()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -308,6 +309,11 @@ func (c *regionUrlMapsRESTClient) Get(ctx context.Context, req *computepb.GetReg } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/urlMaps/%v", req.GetProject(), req.GetRegion(), req.GetUrlMap()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "url_map", url.QueryEscape(req.GetUrlMap()))) @@ -369,6 +375,7 @@ func (c *regionUrlMapsRESTClient) Insert(ctx context.Context, req *computepb.Ins baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/urlMaps", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -450,6 +457,7 @@ func (c *regionUrlMapsRESTClient) List(ctx context.Context, req *computepb.ListR baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/urlMaps", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -540,6 +548,7 @@ func (c *regionUrlMapsRESTClient) Patch(ctx context.Context, req *computepb.Patc baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/urlMaps/%v", req.GetProject(), req.GetRegion(), req.GetUrlMap()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -615,6 +624,7 @@ func (c *regionUrlMapsRESTClient) Update(ctx context.Context, req *computepb.Upd baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/urlMaps/%v", req.GetProject(), req.GetRegion(), req.GetUrlMap()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -689,6 +699,11 @@ func (c *regionUrlMapsRESTClient) Validate(ctx context.Context, req *computepb.V } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/urlMaps/%v/validate", req.GetProject(), req.GetRegion(), req.GetUrlMap()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "url_map", url.QueryEscape(req.GetUrlMap()))) diff --git a/compute/apiv1/regions_client.go b/compute/apiv1/regions_client.go index 6fa636238eee..73b1802d0f1e 100644 --- a/compute/apiv1/regions_client.go +++ b/compute/apiv1/regions_client.go @@ -183,6 +183,11 @@ func (c *regionsRESTClient) Get(ctx context.Context, req *computepb.GetRegionReq } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v", req.GetProject(), req.GetRegion()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()))) @@ -250,6 +255,7 @@ func (c *regionsRESTClient) List(ctx context.Context, req *computepb.ListRegions baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/compute/apiv1/reservations_client.go b/compute/apiv1/reservations_client.go index 04add0c75369..5c3fe746a0a8 100644 --- a/compute/apiv1/reservations_client.go +++ b/compute/apiv1/reservations_client.go @@ -279,6 +279,7 @@ func (c *reservationsRESTClient) AggregatedList(ctx context.Context, req *comput baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/aggregated/reservations", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -372,6 +373,7 @@ func (c *reservationsRESTClient) Delete(ctx context.Context, req *computepb.Dele baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/reservations/%v", req.GetProject(), req.GetZone(), req.GetReservation()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -439,6 +441,11 @@ func (c *reservationsRESTClient) Get(ctx context.Context, req *computepb.GetRese } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/reservations/%v", req.GetProject(), req.GetZone(), req.GetReservation()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "zone", url.QueryEscape(req.GetZone()), "reservation", url.QueryEscape(req.GetReservation()))) @@ -493,6 +500,7 @@ func (c *reservationsRESTClient) GetIamPolicy(ctx context.Context, req *computep baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/reservations/%v/getIamPolicy", req.GetProject(), req.GetZone(), req.GetResource()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.OptionsRequestedPolicyVersion != nil { params.Add("optionsRequestedPolicyVersion", fmt.Sprintf("%v", req.GetOptionsRequestedPolicyVersion())) } @@ -560,6 +568,7 @@ func (c *reservationsRESTClient) Insert(ctx context.Context, req *computepb.Inse baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/reservations", req.GetProject(), req.GetZone()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -641,6 +650,7 @@ func (c *reservationsRESTClient) List(ctx context.Context, req *computepb.ListRe baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/reservations", req.GetProject(), req.GetZone()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -731,6 +741,7 @@ func (c *reservationsRESTClient) Resize(ctx context.Context, req *computepb.Resi baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/reservations/%v/resize", req.GetProject(), req.GetZone(), req.GetReservation()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -805,6 +816,11 @@ func (c *reservationsRESTClient) SetIamPolicy(ctx context.Context, req *computep } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/reservations/%v/setIamPolicy", req.GetProject(), req.GetZone(), req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "zone", url.QueryEscape(req.GetZone()), "resource", url.QueryEscape(req.GetResource()))) @@ -865,6 +881,11 @@ func (c *reservationsRESTClient) TestIamPermissions(ctx context.Context, req *co } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/reservations/%v/testIamPermissions", req.GetProject(), req.GetZone(), req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "zone", url.QueryEscape(req.GetZone()), "resource", url.QueryEscape(req.GetResource()))) @@ -926,6 +947,7 @@ func (c *reservationsRESTClient) Update(ctx context.Context, req *computepb.Upda baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/reservations/%v", req.GetProject(), req.GetZone(), req.GetReservation()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Paths != nil { params.Add("paths", fmt.Sprintf("%v", req.GetPaths())) } diff --git a/compute/apiv1/resource_policies_client.go b/compute/apiv1/resource_policies_client.go index 2ace628292c2..2313b37bdced 100644 --- a/compute/apiv1/resource_policies_client.go +++ b/compute/apiv1/resource_policies_client.go @@ -263,6 +263,7 @@ func (c *resourcePoliciesRESTClient) AggregatedList(ctx context.Context, req *co baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/aggregated/resourcePolicies", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -356,6 +357,7 @@ func (c *resourcePoliciesRESTClient) Delete(ctx context.Context, req *computepb. baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/resourcePolicies/%v", req.GetProject(), req.GetRegion(), req.GetResourcePolicy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -423,6 +425,11 @@ func (c *resourcePoliciesRESTClient) Get(ctx context.Context, req *computepb.Get } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/resourcePolicies/%v", req.GetProject(), req.GetRegion(), req.GetResourcePolicy()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "resource_policy", url.QueryEscape(req.GetResourcePolicy()))) @@ -477,6 +484,7 @@ func (c *resourcePoliciesRESTClient) GetIamPolicy(ctx context.Context, req *comp baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/resourcePolicies/%v/getIamPolicy", req.GetProject(), req.GetRegion(), req.GetResource()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.OptionsRequestedPolicyVersion != nil { params.Add("optionsRequestedPolicyVersion", fmt.Sprintf("%v", req.GetOptionsRequestedPolicyVersion())) } @@ -544,6 +552,7 @@ func (c *resourcePoliciesRESTClient) Insert(ctx context.Context, req *computepb. baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/resourcePolicies", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -625,6 +634,7 @@ func (c *resourcePoliciesRESTClient) List(ctx context.Context, req *computepb.Li baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/resourcePolicies", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -714,6 +724,11 @@ func (c *resourcePoliciesRESTClient) SetIamPolicy(ctx context.Context, req *comp } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/resourcePolicies/%v/setIamPolicy", req.GetProject(), req.GetRegion(), req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "resource", url.QueryEscape(req.GetResource()))) @@ -774,6 +789,11 @@ func (c *resourcePoliciesRESTClient) TestIamPermissions(ctx context.Context, req } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/resourcePolicies/%v/testIamPermissions", req.GetProject(), req.GetRegion(), req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "resource", url.QueryEscape(req.GetResource()))) diff --git a/compute/apiv1/routers_client.go b/compute/apiv1/routers_client.go index 2af3879250d3..a0beb185c9d6 100644 --- a/compute/apiv1/routers_client.go +++ b/compute/apiv1/routers_client.go @@ -279,6 +279,7 @@ func (c *routersRESTClient) AggregatedList(ctx context.Context, req *computepb.A baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/aggregated/routers", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -372,6 +373,7 @@ func (c *routersRESTClient) Delete(ctx context.Context, req *computepb.DeleteRou baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/routers/%v", req.GetProject(), req.GetRegion(), req.GetRouter()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -439,6 +441,11 @@ func (c *routersRESTClient) Get(ctx context.Context, req *computepb.GetRouterReq } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/routers/%v", req.GetProject(), req.GetRegion(), req.GetRouter()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "router", url.QueryEscape(req.GetRouter()))) @@ -506,6 +513,7 @@ func (c *routersRESTClient) GetNatMappingInfo(ctx context.Context, req *computep baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/routers/%v/getNatMappingInfo", req.GetProject(), req.GetRegion(), req.GetRouter()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -588,6 +596,11 @@ func (c *routersRESTClient) GetRouterStatus(ctx context.Context, req *computepb. } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/routers/%v/getRouterStatus", req.GetProject(), req.GetRegion(), req.GetRouter()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "router", url.QueryEscape(req.GetRouter()))) @@ -649,6 +662,7 @@ func (c *routersRESTClient) Insert(ctx context.Context, req *computepb.InsertRou baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/routers", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -730,6 +744,7 @@ func (c *routersRESTClient) List(ctx context.Context, req *computepb.ListRouters baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/routers", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -820,6 +835,7 @@ func (c *routersRESTClient) Patch(ctx context.Context, req *computepb.PatchRoute baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/routers/%v", req.GetProject(), req.GetRegion(), req.GetRouter()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -894,6 +910,11 @@ func (c *routersRESTClient) Preview(ctx context.Context, req *computepb.PreviewR } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/routers/%v/preview", req.GetProject(), req.GetRegion(), req.GetRouter()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "router", url.QueryEscape(req.GetRouter()))) @@ -955,6 +976,7 @@ func (c *routersRESTClient) Update(ctx context.Context, req *computepb.UpdateRou baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/routers/%v", req.GetProject(), req.GetRegion(), req.GetRouter()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } diff --git a/compute/apiv1/routes_client.go b/compute/apiv1/routes_client.go index f141874cb8b2..aaae7e3fdded 100644 --- a/compute/apiv1/routes_client.go +++ b/compute/apiv1/routes_client.go @@ -217,6 +217,7 @@ func (c *routesRESTClient) Delete(ctx context.Context, req *computepb.DeleteRout baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/routes/%v", req.GetProject(), req.GetRoute()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -283,6 +284,11 @@ func (c *routesRESTClient) Get(ctx context.Context, req *computepb.GetRouteReque } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/routes/%v", req.GetProject(), req.GetRoute()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "route", url.QueryEscape(req.GetRoute()))) @@ -344,6 +350,7 @@ func (c *routesRESTClient) Insert(ctx context.Context, req *computepb.InsertRout baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/routes", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -424,6 +431,7 @@ func (c *routesRESTClient) List(ctx context.Context, req *computepb.ListRoutesRe baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/routes", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/compute/apiv1/security_policies_client.go b/compute/apiv1/security_policies_client.go index adde4e0f3f1c..886642048087 100644 --- a/compute/apiv1/security_policies_client.go +++ b/compute/apiv1/security_policies_client.go @@ -289,6 +289,7 @@ func (c *securityPoliciesRESTClient) AddRule(ctx context.Context, req *computepb baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/securityPolicies/%v/addRule", req.GetProject(), req.GetSecurityPolicy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.ValidateOnly != nil { params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) } @@ -369,6 +370,7 @@ func (c *securityPoliciesRESTClient) AggregatedList(ctx context.Context, req *co baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/aggregated/securityPolicies", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -462,6 +464,7 @@ func (c *securityPoliciesRESTClient) Delete(ctx context.Context, req *computepb. baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/securityPolicies/%v", req.GetProject(), req.GetSecurityPolicy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -528,6 +531,11 @@ func (c *securityPoliciesRESTClient) Get(ctx context.Context, req *computepb.Get } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/securityPolicies/%v", req.GetProject(), req.GetSecurityPolicy()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "security_policy", url.QueryEscape(req.GetSecurityPolicy()))) @@ -582,6 +590,7 @@ func (c *securityPoliciesRESTClient) GetRule(ctx context.Context, req *computepb baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/securityPolicies/%v/getRule", req.GetProject(), req.GetSecurityPolicy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Priority != nil { params.Add("priority", fmt.Sprintf("%v", req.GetPriority())) } @@ -649,6 +658,7 @@ func (c *securityPoliciesRESTClient) Insert(ctx context.Context, req *computepb. baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/securityPolicies", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -732,6 +742,7 @@ func (c *securityPoliciesRESTClient) List(ctx context.Context, req *computepb.Li baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/securityPolicies", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -815,6 +826,7 @@ func (c *securityPoliciesRESTClient) ListPreconfiguredExpressionSets(ctx context baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/securityPolicies/listPreconfiguredExpressionSets", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -894,6 +906,7 @@ func (c *securityPoliciesRESTClient) Patch(ctx context.Context, req *computepb.P baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/securityPolicies/%v", req.GetProject(), req.GetSecurityPolicy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -968,6 +981,7 @@ func (c *securityPoliciesRESTClient) PatchRule(ctx context.Context, req *compute baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/securityPolicies/%v/patchRule", req.GetProject(), req.GetSecurityPolicy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Priority != nil { params.Add("priority", fmt.Sprintf("%v", req.GetPriority())) } @@ -1038,6 +1052,7 @@ func (c *securityPoliciesRESTClient) RemoveRule(ctx context.Context, req *comput baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/securityPolicies/%v/removeRule", req.GetProject(), req.GetSecurityPolicy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Priority != nil { params.Add("priority", fmt.Sprintf("%v", req.GetPriority())) } @@ -1111,6 +1126,11 @@ func (c *securityPoliciesRESTClient) SetLabels(ctx context.Context, req *compute } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/securityPolicies/%v/setLabels", req.GetProject(), req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "resource", url.QueryEscape(req.GetResource()))) diff --git a/compute/apiv1/service_attachments_client.go b/compute/apiv1/service_attachments_client.go index 3c2ad4f39bd9..c285f311ebdf 100644 --- a/compute/apiv1/service_attachments_client.go +++ b/compute/apiv1/service_attachments_client.go @@ -271,6 +271,7 @@ func (c *serviceAttachmentsRESTClient) AggregatedList(ctx context.Context, req * baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/aggregated/serviceAttachments", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -364,6 +365,7 @@ func (c *serviceAttachmentsRESTClient) Delete(ctx context.Context, req *computep baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/serviceAttachments/%v", req.GetProject(), req.GetRegion(), req.GetServiceAttachment()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -431,6 +433,11 @@ func (c *serviceAttachmentsRESTClient) Get(ctx context.Context, req *computepb.G } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/serviceAttachments/%v", req.GetProject(), req.GetRegion(), req.GetServiceAttachment()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "service_attachment", url.QueryEscape(req.GetServiceAttachment()))) @@ -485,6 +492,7 @@ func (c *serviceAttachmentsRESTClient) GetIamPolicy(ctx context.Context, req *co baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/serviceAttachments/%v/getIamPolicy", req.GetProject(), req.GetRegion(), req.GetResource()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.OptionsRequestedPolicyVersion != nil { params.Add("optionsRequestedPolicyVersion", fmt.Sprintf("%v", req.GetOptionsRequestedPolicyVersion())) } @@ -552,6 +560,7 @@ func (c *serviceAttachmentsRESTClient) Insert(ctx context.Context, req *computep baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/serviceAttachments", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -633,6 +642,7 @@ func (c *serviceAttachmentsRESTClient) List(ctx context.Context, req *computepb. baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/serviceAttachments", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -723,6 +733,7 @@ func (c *serviceAttachmentsRESTClient) Patch(ctx context.Context, req *computepb baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/serviceAttachments/%v", req.GetProject(), req.GetRegion(), req.GetServiceAttachment()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -797,6 +808,11 @@ func (c *serviceAttachmentsRESTClient) SetIamPolicy(ctx context.Context, req *co } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/serviceAttachments/%v/setIamPolicy", req.GetProject(), req.GetRegion(), req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "resource", url.QueryEscape(req.GetResource()))) @@ -857,6 +873,11 @@ func (c *serviceAttachmentsRESTClient) TestIamPermissions(ctx context.Context, r } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/serviceAttachments/%v/testIamPermissions", req.GetProject(), req.GetRegion(), req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "resource", url.QueryEscape(req.GetResource()))) diff --git a/compute/apiv1/snapshots_client.go b/compute/apiv1/snapshots_client.go index 0846f0e47dfc..67dbd0a10f36 100644 --- a/compute/apiv1/snapshots_client.go +++ b/compute/apiv1/snapshots_client.go @@ -249,6 +249,7 @@ func (c *snapshotsRESTClient) Delete(ctx context.Context, req *computepb.DeleteS baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/snapshots/%v", req.GetProject(), req.GetSnapshot()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -315,6 +316,11 @@ func (c *snapshotsRESTClient) Get(ctx context.Context, req *computepb.GetSnapsho } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/snapshots/%v", req.GetProject(), req.GetSnapshot()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "snapshot", url.QueryEscape(req.GetSnapshot()))) @@ -369,6 +375,7 @@ func (c *snapshotsRESTClient) GetIamPolicy(ctx context.Context, req *computepb.G baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/snapshots/%v/getIamPolicy", req.GetProject(), req.GetResource()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.OptionsRequestedPolicyVersion != nil { params.Add("optionsRequestedPolicyVersion", fmt.Sprintf("%v", req.GetOptionsRequestedPolicyVersion())) } @@ -436,6 +443,7 @@ func (c *snapshotsRESTClient) Insert(ctx context.Context, req *computepb.InsertS baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/snapshots", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -516,6 +524,7 @@ func (c *snapshotsRESTClient) List(ctx context.Context, req *computepb.ListSnaps baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/snapshots", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -605,6 +614,11 @@ func (c *snapshotsRESTClient) SetIamPolicy(ctx context.Context, req *computepb.S } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/snapshots/%v/setIamPolicy", req.GetProject(), req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "resource", url.QueryEscape(req.GetResource()))) @@ -665,6 +679,11 @@ func (c *snapshotsRESTClient) SetLabels(ctx context.Context, req *computepb.SetL } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/snapshots/%v/setLabels", req.GetProject(), req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "resource", url.QueryEscape(req.GetResource()))) @@ -732,6 +751,11 @@ func (c *snapshotsRESTClient) TestIamPermissions(ctx context.Context, req *compu } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/snapshots/%v/testIamPermissions", req.GetProject(), req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "resource", url.QueryEscape(req.GetResource()))) diff --git a/compute/apiv1/ssl_certificates_client.go b/compute/apiv1/ssl_certificates_client.go index 63ee5a3e1f5a..cee1818cf1f2 100644 --- a/compute/apiv1/ssl_certificates_client.go +++ b/compute/apiv1/ssl_certificates_client.go @@ -239,6 +239,7 @@ func (c *sslCertificatesRESTClient) AggregatedList(ctx context.Context, req *com baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/aggregated/sslCertificates", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -332,6 +333,7 @@ func (c *sslCertificatesRESTClient) Delete(ctx context.Context, req *computepb.D baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/sslCertificates/%v", req.GetProject(), req.GetSslCertificate()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -398,6 +400,11 @@ func (c *sslCertificatesRESTClient) Get(ctx context.Context, req *computepb.GetS } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/sslCertificates/%v", req.GetProject(), req.GetSslCertificate()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "ssl_certificate", url.QueryEscape(req.GetSslCertificate()))) @@ -459,6 +466,7 @@ func (c *sslCertificatesRESTClient) Insert(ctx context.Context, req *computepb.I baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/sslCertificates", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -539,6 +547,7 @@ func (c *sslCertificatesRESTClient) List(ctx context.Context, req *computepb.Lis baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/sslCertificates", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/compute/apiv1/ssl_policies_client.go b/compute/apiv1/ssl_policies_client.go index d03011b3505b..b4328a86f0d9 100644 --- a/compute/apiv1/ssl_policies_client.go +++ b/compute/apiv1/ssl_policies_client.go @@ -255,6 +255,7 @@ func (c *sslPoliciesRESTClient) AggregatedList(ctx context.Context, req *compute baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/aggregated/sslPolicies", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -348,6 +349,7 @@ func (c *sslPoliciesRESTClient) Delete(ctx context.Context, req *computepb.Delet baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/sslPolicies/%v", req.GetProject(), req.GetSslPolicy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -414,6 +416,11 @@ func (c *sslPoliciesRESTClient) Get(ctx context.Context, req *computepb.GetSslPo } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/sslPolicies/%v", req.GetProject(), req.GetSslPolicy()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "ssl_policy", url.QueryEscape(req.GetSslPolicy()))) @@ -475,6 +482,7 @@ func (c *sslPoliciesRESTClient) Insert(ctx context.Context, req *computepb.Inser baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/sslPolicies", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -555,6 +563,7 @@ func (c *sslPoliciesRESTClient) List(ctx context.Context, req *computepb.ListSsl baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/sslPolicies", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -638,6 +647,7 @@ func (c *sslPoliciesRESTClient) ListAvailableFeatures(ctx context.Context, req * baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/sslPolicies/listAvailableFeatures", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -717,6 +727,7 @@ func (c *sslPoliciesRESTClient) Patch(ctx context.Context, req *computepb.PatchS baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/sslPolicies/%v", req.GetProject(), req.GetSslPolicy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } diff --git a/compute/apiv1/subnetworks_client.go b/compute/apiv1/subnetworks_client.go index dd8c0f767a97..8f925847ba82 100644 --- a/compute/apiv1/subnetworks_client.go +++ b/compute/apiv1/subnetworks_client.go @@ -295,6 +295,7 @@ func (c *subnetworksRESTClient) AggregatedList(ctx context.Context, req *compute baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/aggregated/subnetworks", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -388,6 +389,7 @@ func (c *subnetworksRESTClient) Delete(ctx context.Context, req *computepb.Delet baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/subnetworks/%v", req.GetProject(), req.GetRegion(), req.GetSubnetwork()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -463,6 +465,7 @@ func (c *subnetworksRESTClient) ExpandIpCidrRange(ctx context.Context, req *comp baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/subnetworks/%v/expandIpCidrRange", req.GetProject(), req.GetRegion(), req.GetSubnetwork()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -530,6 +533,11 @@ func (c *subnetworksRESTClient) Get(ctx context.Context, req *computepb.GetSubne } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/subnetworks/%v", req.GetProject(), req.GetRegion(), req.GetSubnetwork()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "subnetwork", url.QueryEscape(req.GetSubnetwork()))) @@ -584,6 +592,7 @@ func (c *subnetworksRESTClient) GetIamPolicy(ctx context.Context, req *computepb baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/subnetworks/%v/getIamPolicy", req.GetProject(), req.GetRegion(), req.GetResource()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.OptionsRequestedPolicyVersion != nil { params.Add("optionsRequestedPolicyVersion", fmt.Sprintf("%v", req.GetOptionsRequestedPolicyVersion())) } @@ -651,6 +660,7 @@ func (c *subnetworksRESTClient) Insert(ctx context.Context, req *computepb.Inser baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/subnetworks", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -732,6 +742,7 @@ func (c *subnetworksRESTClient) List(ctx context.Context, req *computepb.ListSub baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/subnetworks", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -828,6 +839,7 @@ func (c *subnetworksRESTClient) ListUsable(ctx context.Context, req *computepb.L baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/aggregated/subnetworks/listUsable", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -918,6 +930,7 @@ func (c *subnetworksRESTClient) Patch(ctx context.Context, req *computepb.PatchS baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/subnetworks/%v", req.GetProject(), req.GetRegion(), req.GetSubnetwork()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.DrainTimeoutSeconds != nil { params.Add("drainTimeoutSeconds", fmt.Sprintf("%v", req.GetDrainTimeoutSeconds())) } @@ -995,6 +1008,11 @@ func (c *subnetworksRESTClient) SetIamPolicy(ctx context.Context, req *computepb } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/subnetworks/%v/setIamPolicy", req.GetProject(), req.GetRegion(), req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "resource", url.QueryEscape(req.GetResource()))) @@ -1056,6 +1074,7 @@ func (c *subnetworksRESTClient) SetPrivateIpGoogleAccess(ctx context.Context, re baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/subnetworks/%v/setPrivateIpGoogleAccess", req.GetProject(), req.GetRegion(), req.GetSubnetwork()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -1130,6 +1149,11 @@ func (c *subnetworksRESTClient) TestIamPermissions(ctx context.Context, req *com } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/subnetworks/%v/testIamPermissions", req.GetProject(), req.GetRegion(), req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "resource", url.QueryEscape(req.GetResource()))) diff --git a/compute/apiv1/target_grpc_proxies_client.go b/compute/apiv1/target_grpc_proxies_client.go index a92824ccc894..85f7213c9aad 100644 --- a/compute/apiv1/target_grpc_proxies_client.go +++ b/compute/apiv1/target_grpc_proxies_client.go @@ -225,6 +225,7 @@ func (c *targetGrpcProxiesRESTClient) Delete(ctx context.Context, req *computepb baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/targetGrpcProxies/%v", req.GetProject(), req.GetTargetGrpcProxy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -291,6 +292,11 @@ func (c *targetGrpcProxiesRESTClient) Get(ctx context.Context, req *computepb.Ge } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/targetGrpcProxies/%v", req.GetProject(), req.GetTargetGrpcProxy()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "target_grpc_proxy", url.QueryEscape(req.GetTargetGrpcProxy()))) @@ -352,6 +358,7 @@ func (c *targetGrpcProxiesRESTClient) Insert(ctx context.Context, req *computepb baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/targetGrpcProxies", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -432,6 +439,7 @@ func (c *targetGrpcProxiesRESTClient) List(ctx context.Context, req *computepb.L baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/targetGrpcProxies", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -522,6 +530,7 @@ func (c *targetGrpcProxiesRESTClient) Patch(ctx context.Context, req *computepb. baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/targetGrpcProxies/%v", req.GetProject(), req.GetTargetGrpcProxy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } diff --git a/compute/apiv1/target_http_proxies_client.go b/compute/apiv1/target_http_proxies_client.go index a21f4d760d5d..c97dde5cdf5c 100644 --- a/compute/apiv1/target_http_proxies_client.go +++ b/compute/apiv1/target_http_proxies_client.go @@ -255,6 +255,7 @@ func (c *targetHttpProxiesRESTClient) AggregatedList(ctx context.Context, req *c baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/aggregated/targetHttpProxies", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -348,6 +349,7 @@ func (c *targetHttpProxiesRESTClient) Delete(ctx context.Context, req *computepb baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/targetHttpProxies/%v", req.GetProject(), req.GetTargetHttpProxy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -414,6 +416,11 @@ func (c *targetHttpProxiesRESTClient) Get(ctx context.Context, req *computepb.Ge } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/targetHttpProxies/%v", req.GetProject(), req.GetTargetHttpProxy()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "target_http_proxy", url.QueryEscape(req.GetTargetHttpProxy()))) @@ -475,6 +482,7 @@ func (c *targetHttpProxiesRESTClient) Insert(ctx context.Context, req *computepb baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/targetHttpProxies", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -555,6 +563,7 @@ func (c *targetHttpProxiesRESTClient) List(ctx context.Context, req *computepb.L baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/targetHttpProxies", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -645,6 +654,7 @@ func (c *targetHttpProxiesRESTClient) Patch(ctx context.Context, req *computepb. baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/targetHttpProxies/%v", req.GetProject(), req.GetTargetHttpProxy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -719,6 +729,7 @@ func (c *targetHttpProxiesRESTClient) SetUrlMap(ctx context.Context, req *comput baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/targetHttpProxies/%v/setUrlMap", req.GetProject(), req.GetTargetHttpProxy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } diff --git a/compute/apiv1/target_https_proxies_client.go b/compute/apiv1/target_https_proxies_client.go index 743dc860b074..842ea6094d3d 100644 --- a/compute/apiv1/target_https_proxies_client.go +++ b/compute/apiv1/target_https_proxies_client.go @@ -287,6 +287,7 @@ func (c *targetHttpsProxiesRESTClient) AggregatedList(ctx context.Context, req * baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/aggregated/targetHttpsProxies", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -380,6 +381,7 @@ func (c *targetHttpsProxiesRESTClient) Delete(ctx context.Context, req *computep baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/targetHttpsProxies/%v", req.GetProject(), req.GetTargetHttpsProxy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -446,6 +448,11 @@ func (c *targetHttpsProxiesRESTClient) Get(ctx context.Context, req *computepb.G } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/targetHttpsProxies/%v", req.GetProject(), req.GetTargetHttpsProxy()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "target_https_proxy", url.QueryEscape(req.GetTargetHttpsProxy()))) @@ -507,6 +514,7 @@ func (c *targetHttpsProxiesRESTClient) Insert(ctx context.Context, req *computep baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/targetHttpsProxies", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -587,6 +595,7 @@ func (c *targetHttpsProxiesRESTClient) List(ctx context.Context, req *computepb. baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/targetHttpsProxies", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -677,6 +686,7 @@ func (c *targetHttpsProxiesRESTClient) Patch(ctx context.Context, req *computepb baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/targetHttpsProxies/%v", req.GetProject(), req.GetTargetHttpsProxy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -751,6 +761,7 @@ func (c *targetHttpsProxiesRESTClient) SetCertificateMap(ctx context.Context, re baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/targetHttpsProxies/%v/setCertificateMap", req.GetProject(), req.GetTargetHttpsProxy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -825,6 +836,7 @@ func (c *targetHttpsProxiesRESTClient) SetQuicOverride(ctx context.Context, req baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/targetHttpsProxies/%v/setQuicOverride", req.GetProject(), req.GetTargetHttpsProxy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -899,6 +911,7 @@ func (c *targetHttpsProxiesRESTClient) SetSslCertificates(ctx context.Context, r baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/targetHttpsProxies/%v/setSslCertificates", req.GetProject(), req.GetTargetHttpsProxy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -973,6 +986,7 @@ func (c *targetHttpsProxiesRESTClient) SetSslPolicy(ctx context.Context, req *co baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/targetHttpsProxies/%v/setSslPolicy", req.GetProject(), req.GetTargetHttpsProxy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -1047,6 +1061,7 @@ func (c *targetHttpsProxiesRESTClient) SetUrlMap(ctx context.Context, req *compu baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/targetHttpsProxies/%v/setUrlMap", req.GetProject(), req.GetTargetHttpsProxy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } diff --git a/compute/apiv1/target_instances_client.go b/compute/apiv1/target_instances_client.go index eca1a208573d..df3185c96562 100644 --- a/compute/apiv1/target_instances_client.go +++ b/compute/apiv1/target_instances_client.go @@ -239,6 +239,7 @@ func (c *targetInstancesRESTClient) AggregatedList(ctx context.Context, req *com baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/aggregated/targetInstances", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -332,6 +333,7 @@ func (c *targetInstancesRESTClient) Delete(ctx context.Context, req *computepb.D baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/targetInstances/%v", req.GetProject(), req.GetZone(), req.GetTargetInstance()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -399,6 +401,11 @@ func (c *targetInstancesRESTClient) Get(ctx context.Context, req *computepb.GetT } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/targetInstances/%v", req.GetProject(), req.GetZone(), req.GetTargetInstance()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "zone", url.QueryEscape(req.GetZone()), "target_instance", url.QueryEscape(req.GetTargetInstance()))) @@ -460,6 +467,7 @@ func (c *targetInstancesRESTClient) Insert(ctx context.Context, req *computepb.I baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/targetInstances", req.GetProject(), req.GetZone()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -541,6 +549,7 @@ func (c *targetInstancesRESTClient) List(ctx context.Context, req *computepb.Lis baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/targetInstances", req.GetProject(), req.GetZone()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/compute/apiv1/target_pools_client.go b/compute/apiv1/target_pools_client.go index 050fef761e76..70cd00288692 100644 --- a/compute/apiv1/target_pools_client.go +++ b/compute/apiv1/target_pools_client.go @@ -281,6 +281,7 @@ func (c *targetPoolsRESTClient) AddHealthCheck(ctx context.Context, req *compute baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/targetPools/%v/addHealthCheck", req.GetProject(), req.GetRegion(), req.GetTargetPool()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -356,6 +357,7 @@ func (c *targetPoolsRESTClient) AddInstance(ctx context.Context, req *computepb. baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/targetPools/%v/addInstance", req.GetProject(), req.GetRegion(), req.GetTargetPool()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -437,6 +439,7 @@ func (c *targetPoolsRESTClient) AggregatedList(ctx context.Context, req *compute baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/aggregated/targetPools", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -530,6 +533,7 @@ func (c *targetPoolsRESTClient) Delete(ctx context.Context, req *computepb.Delet baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/targetPools/%v", req.GetProject(), req.GetRegion(), req.GetTargetPool()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -597,6 +601,11 @@ func (c *targetPoolsRESTClient) Get(ctx context.Context, req *computepb.GetTarge } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/targetPools/%v", req.GetProject(), req.GetRegion(), req.GetTargetPool()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "target_pool", url.QueryEscape(req.GetTargetPool()))) @@ -657,6 +666,11 @@ func (c *targetPoolsRESTClient) GetHealth(ctx context.Context, req *computepb.Ge } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/targetPools/%v/getHealth", req.GetProject(), req.GetRegion(), req.GetTargetPool()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "target_pool", url.QueryEscape(req.GetTargetPool()))) @@ -718,6 +732,7 @@ func (c *targetPoolsRESTClient) Insert(ctx context.Context, req *computepb.Inser baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/targetPools", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -799,6 +814,7 @@ func (c *targetPoolsRESTClient) List(ctx context.Context, req *computepb.ListTar baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/targetPools", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -889,6 +905,7 @@ func (c *targetPoolsRESTClient) RemoveHealthCheck(ctx context.Context, req *comp baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/targetPools/%v/removeHealthCheck", req.GetProject(), req.GetRegion(), req.GetTargetPool()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -964,6 +981,7 @@ func (c *targetPoolsRESTClient) RemoveInstance(ctx context.Context, req *compute baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/targetPools/%v/removeInstance", req.GetProject(), req.GetRegion(), req.GetTargetPool()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -1039,6 +1057,7 @@ func (c *targetPoolsRESTClient) SetBackup(ctx context.Context, req *computepb.Se baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/targetPools/%v/setBackup", req.GetProject(), req.GetRegion(), req.GetTargetPool()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.FailoverRatio != nil { params.Add("failoverRatio", fmt.Sprintf("%v", req.GetFailoverRatio())) } diff --git a/compute/apiv1/target_ssl_proxies_client.go b/compute/apiv1/target_ssl_proxies_client.go index 2d00d93f4b32..770fc0ba686a 100644 --- a/compute/apiv1/target_ssl_proxies_client.go +++ b/compute/apiv1/target_ssl_proxies_client.go @@ -257,6 +257,7 @@ func (c *targetSslProxiesRESTClient) Delete(ctx context.Context, req *computepb. baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/targetSslProxies/%v", req.GetProject(), req.GetTargetSslProxy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -323,6 +324,11 @@ func (c *targetSslProxiesRESTClient) Get(ctx context.Context, req *computepb.Get } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/targetSslProxies/%v", req.GetProject(), req.GetTargetSslProxy()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "target_ssl_proxy", url.QueryEscape(req.GetTargetSslProxy()))) @@ -384,6 +390,7 @@ func (c *targetSslProxiesRESTClient) Insert(ctx context.Context, req *computepb. baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/targetSslProxies", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -464,6 +471,7 @@ func (c *targetSslProxiesRESTClient) List(ctx context.Context, req *computepb.Li baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/targetSslProxies", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -554,6 +562,7 @@ func (c *targetSslProxiesRESTClient) SetBackendService(ctx context.Context, req baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/targetSslProxies/%v/setBackendService", req.GetProject(), req.GetTargetSslProxy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -628,6 +637,7 @@ func (c *targetSslProxiesRESTClient) SetCertificateMap(ctx context.Context, req baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/targetSslProxies/%v/setCertificateMap", req.GetProject(), req.GetTargetSslProxy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -702,6 +712,7 @@ func (c *targetSslProxiesRESTClient) SetProxyHeader(ctx context.Context, req *co baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/targetSslProxies/%v/setProxyHeader", req.GetProject(), req.GetTargetSslProxy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -776,6 +787,7 @@ func (c *targetSslProxiesRESTClient) SetSslCertificates(ctx context.Context, req baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/targetSslProxies/%v/setSslCertificates", req.GetProject(), req.GetTargetSslProxy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -850,6 +862,7 @@ func (c *targetSslProxiesRESTClient) SetSslPolicy(ctx context.Context, req *comp baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/targetSslProxies/%v/setSslPolicy", req.GetProject(), req.GetTargetSslProxy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } diff --git a/compute/apiv1/target_tcp_proxies_client.go b/compute/apiv1/target_tcp_proxies_client.go index 3fd2fc7dc1c8..7ebf735e8208 100644 --- a/compute/apiv1/target_tcp_proxies_client.go +++ b/compute/apiv1/target_tcp_proxies_client.go @@ -255,6 +255,7 @@ func (c *targetTcpProxiesRESTClient) AggregatedList(ctx context.Context, req *co baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/aggregated/targetTcpProxies", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -348,6 +349,7 @@ func (c *targetTcpProxiesRESTClient) Delete(ctx context.Context, req *computepb. baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/targetTcpProxies/%v", req.GetProject(), req.GetTargetTcpProxy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -414,6 +416,11 @@ func (c *targetTcpProxiesRESTClient) Get(ctx context.Context, req *computepb.Get } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/targetTcpProxies/%v", req.GetProject(), req.GetTargetTcpProxy()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "target_tcp_proxy", url.QueryEscape(req.GetTargetTcpProxy()))) @@ -475,6 +482,7 @@ func (c *targetTcpProxiesRESTClient) Insert(ctx context.Context, req *computepb. baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/targetTcpProxies", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -555,6 +563,7 @@ func (c *targetTcpProxiesRESTClient) List(ctx context.Context, req *computepb.Li baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/targetTcpProxies", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -645,6 +654,7 @@ func (c *targetTcpProxiesRESTClient) SetBackendService(ctx context.Context, req baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/targetTcpProxies/%v/setBackendService", req.GetProject(), req.GetTargetTcpProxy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -719,6 +729,7 @@ func (c *targetTcpProxiesRESTClient) SetProxyHeader(ctx context.Context, req *co baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/targetTcpProxies/%v/setProxyHeader", req.GetProject(), req.GetTargetTcpProxy()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } diff --git a/compute/apiv1/target_vpn_gateways_client.go b/compute/apiv1/target_vpn_gateways_client.go index 5107b14e9ec0..a7825090e0ae 100644 --- a/compute/apiv1/target_vpn_gateways_client.go +++ b/compute/apiv1/target_vpn_gateways_client.go @@ -247,6 +247,7 @@ func (c *targetVpnGatewaysRESTClient) AggregatedList(ctx context.Context, req *c baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/aggregated/targetVpnGateways", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -340,6 +341,7 @@ func (c *targetVpnGatewaysRESTClient) Delete(ctx context.Context, req *computepb baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/targetVpnGateways/%v", req.GetProject(), req.GetRegion(), req.GetTargetVpnGateway()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -407,6 +409,11 @@ func (c *targetVpnGatewaysRESTClient) Get(ctx context.Context, req *computepb.Ge } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/targetVpnGateways/%v", req.GetProject(), req.GetRegion(), req.GetTargetVpnGateway()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "target_vpn_gateway", url.QueryEscape(req.GetTargetVpnGateway()))) @@ -468,6 +475,7 @@ func (c *targetVpnGatewaysRESTClient) Insert(ctx context.Context, req *computepb baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/targetVpnGateways", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -549,6 +557,7 @@ func (c *targetVpnGatewaysRESTClient) List(ctx context.Context, req *computepb.L baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/targetVpnGateways", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -639,6 +648,7 @@ func (c *targetVpnGatewaysRESTClient) SetLabels(ctx context.Context, req *comput baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/targetVpnGateways/%v/setLabels", req.GetProject(), req.GetRegion(), req.GetResource()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } diff --git a/compute/apiv1/url_maps_client.go b/compute/apiv1/url_maps_client.go index cb6d43616104..84a59b7c050b 100644 --- a/compute/apiv1/url_maps_client.go +++ b/compute/apiv1/url_maps_client.go @@ -271,6 +271,7 @@ func (c *urlMapsRESTClient) AggregatedList(ctx context.Context, req *computepb.A baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/aggregated/urlMaps", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -364,6 +365,7 @@ func (c *urlMapsRESTClient) Delete(ctx context.Context, req *computepb.DeleteUrl baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/urlMaps/%v", req.GetProject(), req.GetUrlMap()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -430,6 +432,11 @@ func (c *urlMapsRESTClient) Get(ctx context.Context, req *computepb.GetUrlMapReq } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/urlMaps/%v", req.GetProject(), req.GetUrlMap()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "url_map", url.QueryEscape(req.GetUrlMap()))) @@ -491,6 +498,7 @@ func (c *urlMapsRESTClient) Insert(ctx context.Context, req *computepb.InsertUrl baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/urlMaps", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -565,6 +573,7 @@ func (c *urlMapsRESTClient) InvalidateCache(ctx context.Context, req *computepb. baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/urlMaps/%v/invalidateCache", req.GetProject(), req.GetUrlMap()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -645,6 +654,7 @@ func (c *urlMapsRESTClient) List(ctx context.Context, req *computepb.ListUrlMaps baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/urlMaps", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -735,6 +745,7 @@ func (c *urlMapsRESTClient) Patch(ctx context.Context, req *computepb.PatchUrlMa baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/urlMaps/%v", req.GetProject(), req.GetUrlMap()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -809,6 +820,7 @@ func (c *urlMapsRESTClient) Update(ctx context.Context, req *computepb.UpdateUrl baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/urlMaps/%v", req.GetProject(), req.GetUrlMap()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -882,6 +894,11 @@ func (c *urlMapsRESTClient) Validate(ctx context.Context, req *computepb.Validat } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/global/urlMaps/%v/validate", req.GetProject(), req.GetUrlMap()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "url_map", url.QueryEscape(req.GetUrlMap()))) diff --git a/compute/apiv1/vpn_gateways_client.go b/compute/apiv1/vpn_gateways_client.go index 47c39f113f94..aa255f9e5259 100644 --- a/compute/apiv1/vpn_gateways_client.go +++ b/compute/apiv1/vpn_gateways_client.go @@ -263,6 +263,7 @@ func (c *vpnGatewaysRESTClient) AggregatedList(ctx context.Context, req *compute baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/aggregated/vpnGateways", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -356,6 +357,7 @@ func (c *vpnGatewaysRESTClient) Delete(ctx context.Context, req *computepb.Delet baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/vpnGateways/%v", req.GetProject(), req.GetRegion(), req.GetVpnGateway()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -423,6 +425,11 @@ func (c *vpnGatewaysRESTClient) Get(ctx context.Context, req *computepb.GetVpnGa } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/vpnGateways/%v", req.GetProject(), req.GetRegion(), req.GetVpnGateway()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "vpn_gateway", url.QueryEscape(req.GetVpnGateway()))) @@ -476,6 +483,11 @@ func (c *vpnGatewaysRESTClient) GetStatus(ctx context.Context, req *computepb.Ge } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/vpnGateways/%v/getStatus", req.GetProject(), req.GetRegion(), req.GetVpnGateway()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "vpn_gateway", url.QueryEscape(req.GetVpnGateway()))) @@ -537,6 +549,7 @@ func (c *vpnGatewaysRESTClient) Insert(ctx context.Context, req *computepb.Inser baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/vpnGateways", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -618,6 +631,7 @@ func (c *vpnGatewaysRESTClient) List(ctx context.Context, req *computepb.ListVpn baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/vpnGateways", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -708,6 +722,7 @@ func (c *vpnGatewaysRESTClient) SetLabels(ctx context.Context, req *computepb.Se baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/vpnGateways/%v/setLabels", req.GetProject(), req.GetRegion(), req.GetResource()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -782,6 +797,11 @@ func (c *vpnGatewaysRESTClient) TestIamPermissions(ctx context.Context, req *com } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/vpnGateways/%v/testIamPermissions", req.GetProject(), req.GetRegion(), req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "resource", url.QueryEscape(req.GetResource()))) diff --git a/compute/apiv1/vpn_tunnels_client.go b/compute/apiv1/vpn_tunnels_client.go index 4ce061065622..d7c66d4a0c79 100644 --- a/compute/apiv1/vpn_tunnels_client.go +++ b/compute/apiv1/vpn_tunnels_client.go @@ -247,6 +247,7 @@ func (c *vpnTunnelsRESTClient) AggregatedList(ctx context.Context, req *computep baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/aggregated/vpnTunnels", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -340,6 +341,7 @@ func (c *vpnTunnelsRESTClient) Delete(ctx context.Context, req *computepb.Delete baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/vpnTunnels/%v", req.GetProject(), req.GetRegion(), req.GetVpnTunnel()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -407,6 +409,11 @@ func (c *vpnTunnelsRESTClient) Get(ctx context.Context, req *computepb.GetVpnTun } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/vpnTunnels/%v", req.GetProject(), req.GetRegion(), req.GetVpnTunnel()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "region", url.QueryEscape(req.GetRegion()), "vpn_tunnel", url.QueryEscape(req.GetVpnTunnel()))) @@ -468,6 +475,7 @@ func (c *vpnTunnelsRESTClient) Insert(ctx context.Context, req *computepb.Insert baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/vpnTunnels", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -549,6 +557,7 @@ func (c *vpnTunnelsRESTClient) List(ctx context.Context, req *computepb.ListVpnT baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/vpnTunnels", req.GetProject(), req.GetRegion()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -639,6 +648,7 @@ func (c *vpnTunnelsRESTClient) SetLabels(ctx context.Context, req *computepb.Set baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/regions/%v/vpnTunnels/%v/setLabels", req.GetProject(), req.GetRegion(), req.GetResource()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.RequestId != nil { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } diff --git a/compute/apiv1/zone_operations_client.go b/compute/apiv1/zone_operations_client.go index 73e4314abc5e..e20e96a849bd 100644 --- a/compute/apiv1/zone_operations_client.go +++ b/compute/apiv1/zone_operations_client.go @@ -199,6 +199,11 @@ func (c *zoneOperationsRESTClient) Delete(ctx context.Context, req *computepb.De } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/operations/%v", req.GetProject(), req.GetZone(), req.GetOperation()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "zone", url.QueryEscape(req.GetZone()), "operation", url.QueryEscape(req.GetOperation()))) @@ -252,6 +257,11 @@ func (c *zoneOperationsRESTClient) Get(ctx context.Context, req *computepb.GetZo } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/operations/%v", req.GetProject(), req.GetZone(), req.GetOperation()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "zone", url.QueryEscape(req.GetZone()), "operation", url.QueryEscape(req.GetOperation()))) @@ -319,6 +329,7 @@ func (c *zoneOperationsRESTClient) List(ctx context.Context, req *computepb.List baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/operations", req.GetProject(), req.GetZone()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -401,6 +412,11 @@ func (c *zoneOperationsRESTClient) Wait(ctx context.Context, req *computepb.Wait } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v/operations/%v/wait", req.GetProject(), req.GetZone(), req.GetOperation()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "zone", url.QueryEscape(req.GetZone()), "operation", url.QueryEscape(req.GetOperation()))) diff --git a/compute/apiv1/zones_client.go b/compute/apiv1/zones_client.go index 317a69741a3c..d35896c500b8 100644 --- a/compute/apiv1/zones_client.go +++ b/compute/apiv1/zones_client.go @@ -183,6 +183,11 @@ func (c *zonesRESTClient) Get(ctx context.Context, req *computepb.GetZoneRequest } baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones/%v", req.GetProject(), req.GetZone()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project", url.QueryEscape(req.GetProject()), "zone", url.QueryEscape(req.GetZone()))) @@ -250,6 +255,7 @@ func (c *zonesRESTClient) List(ctx context.Context, req *computepb.ListZonesRequ baseUrl.Path += fmt.Sprintf("/compute/v1/projects/%v/zones", req.GetProject()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req != nil && req.Filter != nil { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/contactcenterinsights/apiv1/contact_center_insights_client.go b/contactcenterinsights/apiv1/contact_center_insights_client.go index 82c5897b05b5..fdb77eece2a1 100644 --- a/contactcenterinsights/apiv1/contact_center_insights_client.go +++ b/contactcenterinsights/apiv1/contact_center_insights_client.go @@ -17,9 +17,12 @@ package contactcenterinsights import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,14 +30,17 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -505,6 +511,381 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + CreateConversation: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UpdateConversation: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetConversation: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListConversations: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeleteConversation: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateAnalysis: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetAnalysis: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListAnalyses: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeleteAnalysis: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ExportInsightsData: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateIssueModel: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UpdateIssueModel: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetIssueModel: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListIssueModels: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeleteIssueModel: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeployIssueModel: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UndeployIssueModel: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetIssue: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListIssues: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UpdateIssue: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CalculateIssueModelStats: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreatePhraseMatcher: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetPhraseMatcher: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListPhraseMatchers: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeletePhraseMatcher: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UpdatePhraseMatcher: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CalculateStats: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetSettings: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UpdateSettings: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateView: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetView: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListViews: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UpdateView: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeleteView: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CancelOperation: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetOperation: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListOperations: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + } +} + // internalClient is an interface that defines the methods available from Contact Center AI Insights API. type internalClient interface { Close() error @@ -555,443 +936,1580 @@ type internalClient interface { ListOperations(context.Context, *longrunningpb.ListOperationsRequest, ...gax.CallOption) *OperationIterator } -// Client is a client for interacting with Contact Center AI Insights API. -// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. -// -// An API that lets users analyze and explore their business conversation data. -type Client struct { - // The internal transport-dependent client. - internalClient internalClient +// Client is a client for interacting with Contact Center AI Insights API. +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// An API that lets users analyze and explore their business conversation data. +type Client struct { + // The internal transport-dependent client. + internalClient internalClient + + // The call options for this service. + CallOptions *CallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Client) Close() error { + return c.internalClient.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 *Client) setGoogleClientInfo(keyval ...string) { + c.internalClient.setGoogleClientInfo(keyval...) +} + +// Connection returns a connection to the API service. +// +// Deprecated: Connections are now pooled so this method does not always +// return the same resource. +func (c *Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateConversation creates a conversation. +func (c *Client) CreateConversation(ctx context.Context, req *contactcenterinsightspb.CreateConversationRequest, opts ...gax.CallOption) (*contactcenterinsightspb.Conversation, error) { + return c.internalClient.CreateConversation(ctx, req, opts...) +} + +// UpdateConversation updates a conversation. +func (c *Client) UpdateConversation(ctx context.Context, req *contactcenterinsightspb.UpdateConversationRequest, opts ...gax.CallOption) (*contactcenterinsightspb.Conversation, error) { + return c.internalClient.UpdateConversation(ctx, req, opts...) +} + +// GetConversation gets a conversation. +func (c *Client) GetConversation(ctx context.Context, req *contactcenterinsightspb.GetConversationRequest, opts ...gax.CallOption) (*contactcenterinsightspb.Conversation, error) { + return c.internalClient.GetConversation(ctx, req, opts...) +} + +// ListConversations lists conversations. +func (c *Client) ListConversations(ctx context.Context, req *contactcenterinsightspb.ListConversationsRequest, opts ...gax.CallOption) *ConversationIterator { + return c.internalClient.ListConversations(ctx, req, opts...) +} + +// DeleteConversation deletes a conversation. +func (c *Client) DeleteConversation(ctx context.Context, req *contactcenterinsightspb.DeleteConversationRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteConversation(ctx, req, opts...) +} + +// CreateAnalysis creates an analysis. The long running operation is done when the analysis +// has completed. +func (c *Client) CreateAnalysis(ctx context.Context, req *contactcenterinsightspb.CreateAnalysisRequest, opts ...gax.CallOption) (*CreateAnalysisOperation, error) { + return c.internalClient.CreateAnalysis(ctx, req, opts...) +} + +// CreateAnalysisOperation returns a new CreateAnalysisOperation from a given name. +// The name must be that of a previously created CreateAnalysisOperation, possibly from a different process. +func (c *Client) CreateAnalysisOperation(name string) *CreateAnalysisOperation { + return c.internalClient.CreateAnalysisOperation(name) +} + +// GetAnalysis gets an analysis. +func (c *Client) GetAnalysis(ctx context.Context, req *contactcenterinsightspb.GetAnalysisRequest, opts ...gax.CallOption) (*contactcenterinsightspb.Analysis, error) { + return c.internalClient.GetAnalysis(ctx, req, opts...) +} + +// ListAnalyses lists analyses. +func (c *Client) ListAnalyses(ctx context.Context, req *contactcenterinsightspb.ListAnalysesRequest, opts ...gax.CallOption) *AnalysisIterator { + return c.internalClient.ListAnalyses(ctx, req, opts...) +} + +// DeleteAnalysis deletes an analysis. +func (c *Client) DeleteAnalysis(ctx context.Context, req *contactcenterinsightspb.DeleteAnalysisRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteAnalysis(ctx, req, opts...) +} + +// ExportInsightsData export insights data to a destination defined in the request body. +func (c *Client) ExportInsightsData(ctx context.Context, req *contactcenterinsightspb.ExportInsightsDataRequest, opts ...gax.CallOption) (*ExportInsightsDataOperation, error) { + return c.internalClient.ExportInsightsData(ctx, req, opts...) +} + +// ExportInsightsDataOperation returns a new ExportInsightsDataOperation from a given name. +// The name must be that of a previously created ExportInsightsDataOperation, possibly from a different process. +func (c *Client) ExportInsightsDataOperation(name string) *ExportInsightsDataOperation { + return c.internalClient.ExportInsightsDataOperation(name) +} + +// CreateIssueModel creates an issue model. +func (c *Client) CreateIssueModel(ctx context.Context, req *contactcenterinsightspb.CreateIssueModelRequest, opts ...gax.CallOption) (*CreateIssueModelOperation, error) { + return c.internalClient.CreateIssueModel(ctx, req, opts...) +} + +// CreateIssueModelOperation returns a new CreateIssueModelOperation from a given name. +// The name must be that of a previously created CreateIssueModelOperation, possibly from a different process. +func (c *Client) CreateIssueModelOperation(name string) *CreateIssueModelOperation { + return c.internalClient.CreateIssueModelOperation(name) +} + +// UpdateIssueModel updates an issue model. +func (c *Client) UpdateIssueModel(ctx context.Context, req *contactcenterinsightspb.UpdateIssueModelRequest, opts ...gax.CallOption) (*contactcenterinsightspb.IssueModel, error) { + return c.internalClient.UpdateIssueModel(ctx, req, opts...) +} + +// GetIssueModel gets an issue model. +func (c *Client) GetIssueModel(ctx context.Context, req *contactcenterinsightspb.GetIssueModelRequest, opts ...gax.CallOption) (*contactcenterinsightspb.IssueModel, error) { + return c.internalClient.GetIssueModel(ctx, req, opts...) +} + +// ListIssueModels lists issue models. +func (c *Client) ListIssueModels(ctx context.Context, req *contactcenterinsightspb.ListIssueModelsRequest, opts ...gax.CallOption) (*contactcenterinsightspb.ListIssueModelsResponse, error) { + return c.internalClient.ListIssueModels(ctx, req, opts...) +} + +// DeleteIssueModel deletes an issue model. +func (c *Client) DeleteIssueModel(ctx context.Context, req *contactcenterinsightspb.DeleteIssueModelRequest, opts ...gax.CallOption) (*DeleteIssueModelOperation, error) { + return c.internalClient.DeleteIssueModel(ctx, req, opts...) +} + +// DeleteIssueModelOperation returns a new DeleteIssueModelOperation from a given name. +// The name must be that of a previously created DeleteIssueModelOperation, possibly from a different process. +func (c *Client) DeleteIssueModelOperation(name string) *DeleteIssueModelOperation { + return c.internalClient.DeleteIssueModelOperation(name) +} + +// DeployIssueModel deploys an issue model. Returns an error if a model is already deployed. +// An issue model can only be used in analysis after it has been deployed. +func (c *Client) DeployIssueModel(ctx context.Context, req *contactcenterinsightspb.DeployIssueModelRequest, opts ...gax.CallOption) (*DeployIssueModelOperation, error) { + return c.internalClient.DeployIssueModel(ctx, req, opts...) +} + +// DeployIssueModelOperation returns a new DeployIssueModelOperation from a given name. +// The name must be that of a previously created DeployIssueModelOperation, possibly from a different process. +func (c *Client) DeployIssueModelOperation(name string) *DeployIssueModelOperation { + return c.internalClient.DeployIssueModelOperation(name) +} + +// UndeployIssueModel undeploys an issue model. +// An issue model can not be used in analysis after it has been undeployed. +func (c *Client) UndeployIssueModel(ctx context.Context, req *contactcenterinsightspb.UndeployIssueModelRequest, opts ...gax.CallOption) (*UndeployIssueModelOperation, error) { + return c.internalClient.UndeployIssueModel(ctx, req, opts...) +} + +// UndeployIssueModelOperation returns a new UndeployIssueModelOperation from a given name. +// The name must be that of a previously created UndeployIssueModelOperation, possibly from a different process. +func (c *Client) UndeployIssueModelOperation(name string) *UndeployIssueModelOperation { + return c.internalClient.UndeployIssueModelOperation(name) +} + +// GetIssue gets an issue. +func (c *Client) GetIssue(ctx context.Context, req *contactcenterinsightspb.GetIssueRequest, opts ...gax.CallOption) (*contactcenterinsightspb.Issue, error) { + return c.internalClient.GetIssue(ctx, req, opts...) +} + +// ListIssues lists issues. +func (c *Client) ListIssues(ctx context.Context, req *contactcenterinsightspb.ListIssuesRequest, opts ...gax.CallOption) (*contactcenterinsightspb.ListIssuesResponse, error) { + return c.internalClient.ListIssues(ctx, req, opts...) +} + +// UpdateIssue updates an issue. +func (c *Client) UpdateIssue(ctx context.Context, req *contactcenterinsightspb.UpdateIssueRequest, opts ...gax.CallOption) (*contactcenterinsightspb.Issue, error) { + return c.internalClient.UpdateIssue(ctx, req, opts...) +} + +// CalculateIssueModelStats gets an issue model’s statistics. +func (c *Client) CalculateIssueModelStats(ctx context.Context, req *contactcenterinsightspb.CalculateIssueModelStatsRequest, opts ...gax.CallOption) (*contactcenterinsightspb.CalculateIssueModelStatsResponse, error) { + return c.internalClient.CalculateIssueModelStats(ctx, req, opts...) +} + +// CreatePhraseMatcher creates a phrase matcher. +func (c *Client) CreatePhraseMatcher(ctx context.Context, req *contactcenterinsightspb.CreatePhraseMatcherRequest, opts ...gax.CallOption) (*contactcenterinsightspb.PhraseMatcher, error) { + return c.internalClient.CreatePhraseMatcher(ctx, req, opts...) +} + +// GetPhraseMatcher gets a phrase matcher. +func (c *Client) GetPhraseMatcher(ctx context.Context, req *contactcenterinsightspb.GetPhraseMatcherRequest, opts ...gax.CallOption) (*contactcenterinsightspb.PhraseMatcher, error) { + return c.internalClient.GetPhraseMatcher(ctx, req, opts...) +} + +// ListPhraseMatchers lists phrase matchers. +func (c *Client) ListPhraseMatchers(ctx context.Context, req *contactcenterinsightspb.ListPhraseMatchersRequest, opts ...gax.CallOption) *PhraseMatcherIterator { + return c.internalClient.ListPhraseMatchers(ctx, req, opts...) +} + +// DeletePhraseMatcher deletes a phrase matcher. +func (c *Client) DeletePhraseMatcher(ctx context.Context, req *contactcenterinsightspb.DeletePhraseMatcherRequest, opts ...gax.CallOption) error { + return c.internalClient.DeletePhraseMatcher(ctx, req, opts...) +} + +// UpdatePhraseMatcher updates a phrase matcher. +func (c *Client) UpdatePhraseMatcher(ctx context.Context, req *contactcenterinsightspb.UpdatePhraseMatcherRequest, opts ...gax.CallOption) (*contactcenterinsightspb.PhraseMatcher, error) { + return c.internalClient.UpdatePhraseMatcher(ctx, req, opts...) +} + +// CalculateStats gets conversation statistics. +func (c *Client) CalculateStats(ctx context.Context, req *contactcenterinsightspb.CalculateStatsRequest, opts ...gax.CallOption) (*contactcenterinsightspb.CalculateStatsResponse, error) { + return c.internalClient.CalculateStats(ctx, req, opts...) +} + +// GetSettings gets project-level settings. +func (c *Client) GetSettings(ctx context.Context, req *contactcenterinsightspb.GetSettingsRequest, opts ...gax.CallOption) (*contactcenterinsightspb.Settings, error) { + return c.internalClient.GetSettings(ctx, req, opts...) +} + +// UpdateSettings updates project-level settings. +func (c *Client) UpdateSettings(ctx context.Context, req *contactcenterinsightspb.UpdateSettingsRequest, opts ...gax.CallOption) (*contactcenterinsightspb.Settings, error) { + return c.internalClient.UpdateSettings(ctx, req, opts...) +} + +// CreateView creates a view. +func (c *Client) CreateView(ctx context.Context, req *contactcenterinsightspb.CreateViewRequest, opts ...gax.CallOption) (*contactcenterinsightspb.View, error) { + return c.internalClient.CreateView(ctx, req, opts...) +} + +// GetView gets a view. +func (c *Client) GetView(ctx context.Context, req *contactcenterinsightspb.GetViewRequest, opts ...gax.CallOption) (*contactcenterinsightspb.View, error) { + return c.internalClient.GetView(ctx, req, opts...) +} + +// ListViews lists views. +func (c *Client) ListViews(ctx context.Context, req *contactcenterinsightspb.ListViewsRequest, opts ...gax.CallOption) *ViewIterator { + return c.internalClient.ListViews(ctx, req, opts...) +} + +// UpdateView updates a view. +func (c *Client) UpdateView(ctx context.Context, req *contactcenterinsightspb.UpdateViewRequest, opts ...gax.CallOption) (*contactcenterinsightspb.View, error) { + return c.internalClient.UpdateView(ctx, req, opts...) +} + +// DeleteView deletes a view. +func (c *Client) DeleteView(ctx context.Context, req *contactcenterinsightspb.DeleteViewRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteView(ctx, req, opts...) +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *Client) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + return c.internalClient.CancelOperation(ctx, req, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *Client) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + return c.internalClient.GetOperation(ctx, req, opts...) +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *Client) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + return c.internalClient.ListOperations(ctx, req, opts...) +} + +// gRPCClient is a client for interacting with Contact Center AI Insights API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gRPCClient struct { + // Connection pool of gRPC connections to the service. + connPool gtransport.ConnPool + + // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE + disableDeadlines bool + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions + + // The gRPC API client. + client contactcenterinsightspb.ContactCenterInsightsClient + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + operationsClient longrunningpb.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD +} + +// NewClient creates a new contact center insights client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. +// +// An API that lets users analyze and explore their business conversation data. +func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := defaultGRPCClientOptions() + if newClientHook != nil { + hookOpts, err := newClientHook(ctx, clientHookParams{}) + if err != nil { + return nil, err + } + clientOpts = append(clientOpts, hookOpts...) + } + + disableDeadlines, err := checkDisableDeadlines() + if err != nil { + return nil, err + } + + connPool, err := gtransport.DialPool(ctx, append(clientOpts, opts...)...) + if err != nil { + return nil, err + } + client := Client{CallOptions: defaultCallOptions()} + + c := &gRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, + client: contactcenterinsightspb.NewContactCenterInsightsClient(connPool), + CallOptions: &client.CallOptions, + operationsClient: longrunningpb.NewOperationsClient(connPool), + } + c.setGoogleClientInfo() + + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + if err != nil { + // This error "should not happen", since we are just reusing old connection pool + // and never actually need to dial. + // If this does happen, we could leak connp. However, we cannot close conn: + // If the user invoked the constructor with option.WithGRPCConn, + // we would close a connection that's still in use. + // TODO: investigate error conditions. + return nil, err + } + c.LROClient = &client.LROClient + return &client, nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: Connections are now pooled so this method does not always +// return the same resource. +func (c *gRPCClient) Connection() *grpc.ClientConn { + return c.connPool.Conn() +} + +// 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 *gRPCClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "grpc", grpc.Version) + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gRPCClient) Close() error { + return c.connPool.Close() +} + +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new contact center insights rest client. +// +// An API that lets users analyze and explore their business conversation data. +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://contactcenterinsights.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://contactcenterinsights.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://contactcenterinsights.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} +func (c *gRPCClient) CreateConversation(ctx context.Context, req *contactcenterinsightspb.CreateConversationRequest, opts ...gax.CallOption) (*contactcenterinsightspb.Conversation, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).CreateConversation[0:len((*c.CallOptions).CreateConversation):len((*c.CallOptions).CreateConversation)], opts...) + var resp *contactcenterinsightspb.Conversation + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.client.CreateConversation(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *gRPCClient) UpdateConversation(ctx context.Context, req *contactcenterinsightspb.UpdateConversationRequest, opts ...gax.CallOption) (*contactcenterinsightspb.Conversation, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "conversation.name", url.QueryEscape(req.GetConversation().GetName()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).UpdateConversation[0:len((*c.CallOptions).UpdateConversation):len((*c.CallOptions).UpdateConversation)], opts...) + var resp *contactcenterinsightspb.Conversation + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.client.UpdateConversation(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *gRPCClient) GetConversation(ctx context.Context, req *contactcenterinsightspb.GetConversationRequest, opts ...gax.CallOption) (*contactcenterinsightspb.Conversation, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).GetConversation[0:len((*c.CallOptions).GetConversation):len((*c.CallOptions).GetConversation)], opts...) + var resp *contactcenterinsightspb.Conversation + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.client.GetConversation(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *gRPCClient) ListConversations(ctx context.Context, req *contactcenterinsightspb.ListConversationsRequest, opts ...gax.CallOption) *ConversationIterator { + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).ListConversations[0:len((*c.CallOptions).ListConversations):len((*c.CallOptions).ListConversations)], opts...) + it := &ConversationIterator{} + req = proto.Clone(req).(*contactcenterinsightspb.ListConversationsRequest) + it.InternalFetch = func(pageSize int, pageToken string) ([]*contactcenterinsightspb.Conversation, string, error) { + resp := &contactcenterinsightspb.ListConversationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.client.ListConversations(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, "", err + } + + it.Response = resp + return resp.GetConversations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +func (c *gRPCClient) DeleteConversation(ctx context.Context, req *contactcenterinsightspb.DeleteConversationRequest, opts ...gax.CallOption) error { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).DeleteConversation[0:len((*c.CallOptions).DeleteConversation):len((*c.CallOptions).DeleteConversation)], opts...) + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + _, err = c.client.DeleteConversation(ctx, req, settings.GRPC...) + return err + }, opts...) + return err +} + +func (c *gRPCClient) CreateAnalysis(ctx context.Context, req *contactcenterinsightspb.CreateAnalysisRequest, opts ...gax.CallOption) (*CreateAnalysisOperation, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).CreateAnalysis[0:len((*c.CallOptions).CreateAnalysis):len((*c.CallOptions).CreateAnalysis)], opts...) + var resp *longrunningpb.Operation + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.client.CreateAnalysis(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return &CreateAnalysisOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + }, nil +} + +func (c *gRPCClient) GetAnalysis(ctx context.Context, req *contactcenterinsightspb.GetAnalysisRequest, opts ...gax.CallOption) (*contactcenterinsightspb.Analysis, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).GetAnalysis[0:len((*c.CallOptions).GetAnalysis):len((*c.CallOptions).GetAnalysis)], opts...) + var resp *contactcenterinsightspb.Analysis + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.client.GetAnalysis(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *gRPCClient) ListAnalyses(ctx context.Context, req *contactcenterinsightspb.ListAnalysesRequest, opts ...gax.CallOption) *AnalysisIterator { + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).ListAnalyses[0:len((*c.CallOptions).ListAnalyses):len((*c.CallOptions).ListAnalyses)], opts...) + it := &AnalysisIterator{} + req = proto.Clone(req).(*contactcenterinsightspb.ListAnalysesRequest) + it.InternalFetch = func(pageSize int, pageToken string) ([]*contactcenterinsightspb.Analysis, string, error) { + resp := &contactcenterinsightspb.ListAnalysesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.client.ListAnalyses(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, "", err + } + + it.Response = resp + return resp.GetAnalyses(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +func (c *gRPCClient) DeleteAnalysis(ctx context.Context, req *contactcenterinsightspb.DeleteAnalysisRequest, opts ...gax.CallOption) error { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) - // The call options for this service. - CallOptions *CallOptions + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).DeleteAnalysis[0:len((*c.CallOptions).DeleteAnalysis):len((*c.CallOptions).DeleteAnalysis)], opts...) + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + _, err = c.client.DeleteAnalysis(ctx, req, settings.GRPC...) + return err + }, opts...) + return err +} - // LROClient is used internally to handle long-running operations. - // It is exposed so that its CallOptions can be modified if required. - // Users should not Close this client. - LROClient *lroauto.OperationsClient +func (c *gRPCClient) ExportInsightsData(ctx context.Context, req *contactcenterinsightspb.ExportInsightsDataRequest, opts ...gax.CallOption) (*ExportInsightsDataOperation, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).ExportInsightsData[0:len((*c.CallOptions).ExportInsightsData):len((*c.CallOptions).ExportInsightsData)], opts...) + var resp *longrunningpb.Operation + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.client.ExportInsightsData(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return &ExportInsightsDataOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + }, nil } -// Wrapper methods routed to the internal client. +func (c *gRPCClient) CreateIssueModel(ctx context.Context, req *contactcenterinsightspb.CreateIssueModelRequest, opts ...gax.CallOption) (*CreateIssueModelOperation, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.internalClient.Close() + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).CreateIssueModel[0:len((*c.CallOptions).CreateIssueModel):len((*c.CallOptions).CreateIssueModel)], opts...) + var resp *longrunningpb.Operation + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.client.CreateIssueModel(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return &CreateIssueModelOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + }, nil +} + +func (c *gRPCClient) UpdateIssueModel(ctx context.Context, req *contactcenterinsightspb.UpdateIssueModelRequest, opts ...gax.CallOption) (*contactcenterinsightspb.IssueModel, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "issue_model.name", url.QueryEscape(req.GetIssueModel().GetName()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).UpdateIssueModel[0:len((*c.CallOptions).UpdateIssueModel):len((*c.CallOptions).UpdateIssueModel)], opts...) + var resp *contactcenterinsightspb.IssueModel + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.client.UpdateIssueModel(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *gRPCClient) GetIssueModel(ctx context.Context, req *contactcenterinsightspb.GetIssueModelRequest, opts ...gax.CallOption) (*contactcenterinsightspb.IssueModel, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).GetIssueModel[0:len((*c.CallOptions).GetIssueModel):len((*c.CallOptions).GetIssueModel)], opts...) + var resp *contactcenterinsightspb.IssueModel + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.client.GetIssueModel(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *gRPCClient) ListIssueModels(ctx context.Context, req *contactcenterinsightspb.ListIssueModelsRequest, opts ...gax.CallOption) (*contactcenterinsightspb.ListIssueModelsResponse, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).ListIssueModels[0:len((*c.CallOptions).ListIssueModels):len((*c.CallOptions).ListIssueModels)], opts...) + var resp *contactcenterinsightspb.ListIssueModelsResponse + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.client.ListIssueModels(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *gRPCClient) DeleteIssueModel(ctx context.Context, req *contactcenterinsightspb.DeleteIssueModelRequest, opts ...gax.CallOption) (*DeleteIssueModelOperation, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).DeleteIssueModel[0:len((*c.CallOptions).DeleteIssueModel):len((*c.CallOptions).DeleteIssueModel)], opts...) + var resp *longrunningpb.Operation + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.client.DeleteIssueModel(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return &DeleteIssueModelOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + }, nil +} + +func (c *gRPCClient) DeployIssueModel(ctx context.Context, req *contactcenterinsightspb.DeployIssueModelRequest, opts ...gax.CallOption) (*DeployIssueModelOperation, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).DeployIssueModel[0:len((*c.CallOptions).DeployIssueModel):len((*c.CallOptions).DeployIssueModel)], opts...) + var resp *longrunningpb.Operation + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.client.DeployIssueModel(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return &DeployIssueModelOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + }, nil +} + +func (c *gRPCClient) UndeployIssueModel(ctx context.Context, req *contactcenterinsightspb.UndeployIssueModelRequest, opts ...gax.CallOption) (*UndeployIssueModelOperation, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).UndeployIssueModel[0:len((*c.CallOptions).UndeployIssueModel):len((*c.CallOptions).UndeployIssueModel)], opts...) + var resp *longrunningpb.Operation + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.client.UndeployIssueModel(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return &UndeployIssueModelOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + }, nil +} + +func (c *gRPCClient) GetIssue(ctx context.Context, req *contactcenterinsightspb.GetIssueRequest, opts ...gax.CallOption) (*contactcenterinsightspb.Issue, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).GetIssue[0:len((*c.CallOptions).GetIssue):len((*c.CallOptions).GetIssue)], opts...) + var resp *contactcenterinsightspb.Issue + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.client.GetIssue(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return resp, nil } -// 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 *Client) setGoogleClientInfo(keyval ...string) { - c.internalClient.setGoogleClientInfo(keyval...) -} +func (c *gRPCClient) ListIssues(ctx context.Context, req *contactcenterinsightspb.ListIssuesRequest, opts ...gax.CallOption) (*contactcenterinsightspb.ListIssuesResponse, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) -// Connection returns a connection to the API service. -// -// Deprecated: Connections are now pooled so this method does not always -// return the same resource. -func (c *Client) Connection() *grpc.ClientConn { - return c.internalClient.Connection() + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).ListIssues[0:len((*c.CallOptions).ListIssues):len((*c.CallOptions).ListIssues)], opts...) + var resp *contactcenterinsightspb.ListIssuesResponse + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.client.ListIssues(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return resp, nil } -// CreateConversation creates a conversation. -func (c *Client) CreateConversation(ctx context.Context, req *contactcenterinsightspb.CreateConversationRequest, opts ...gax.CallOption) (*contactcenterinsightspb.Conversation, error) { - return c.internalClient.CreateConversation(ctx, req, opts...) -} +func (c *gRPCClient) UpdateIssue(ctx context.Context, req *contactcenterinsightspb.UpdateIssueRequest, opts ...gax.CallOption) (*contactcenterinsightspb.Issue, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "issue.name", url.QueryEscape(req.GetIssue().GetName()))) -// UpdateConversation updates a conversation. -func (c *Client) UpdateConversation(ctx context.Context, req *contactcenterinsightspb.UpdateConversationRequest, opts ...gax.CallOption) (*contactcenterinsightspb.Conversation, error) { - return c.internalClient.UpdateConversation(ctx, req, opts...) + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).UpdateIssue[0:len((*c.CallOptions).UpdateIssue):len((*c.CallOptions).UpdateIssue)], opts...) + var resp *contactcenterinsightspb.Issue + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.client.UpdateIssue(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return resp, nil } -// GetConversation gets a conversation. -func (c *Client) GetConversation(ctx context.Context, req *contactcenterinsightspb.GetConversationRequest, opts ...gax.CallOption) (*contactcenterinsightspb.Conversation, error) { - return c.internalClient.GetConversation(ctx, req, opts...) -} +func (c *gRPCClient) CalculateIssueModelStats(ctx context.Context, req *contactcenterinsightspb.CalculateIssueModelStatsRequest, opts ...gax.CallOption) (*contactcenterinsightspb.CalculateIssueModelStatsResponse, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "issue_model", url.QueryEscape(req.GetIssueModel()))) -// ListConversations lists conversations. -func (c *Client) ListConversations(ctx context.Context, req *contactcenterinsightspb.ListConversationsRequest, opts ...gax.CallOption) *ConversationIterator { - return c.internalClient.ListConversations(ctx, req, opts...) + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).CalculateIssueModelStats[0:len((*c.CallOptions).CalculateIssueModelStats):len((*c.CallOptions).CalculateIssueModelStats)], opts...) + var resp *contactcenterinsightspb.CalculateIssueModelStatsResponse + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.client.CalculateIssueModelStats(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return resp, nil } -// DeleteConversation deletes a conversation. -func (c *Client) DeleteConversation(ctx context.Context, req *contactcenterinsightspb.DeleteConversationRequest, opts ...gax.CallOption) error { - return c.internalClient.DeleteConversation(ctx, req, opts...) -} +func (c *gRPCClient) CreatePhraseMatcher(ctx context.Context, req *contactcenterinsightspb.CreatePhraseMatcherRequest, opts ...gax.CallOption) (*contactcenterinsightspb.PhraseMatcher, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) -// CreateAnalysis creates an analysis. The long running operation is done when the analysis -// has completed. -func (c *Client) CreateAnalysis(ctx context.Context, req *contactcenterinsightspb.CreateAnalysisRequest, opts ...gax.CallOption) (*CreateAnalysisOperation, error) { - return c.internalClient.CreateAnalysis(ctx, req, opts...) + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).CreatePhraseMatcher[0:len((*c.CallOptions).CreatePhraseMatcher):len((*c.CallOptions).CreatePhraseMatcher)], opts...) + var resp *contactcenterinsightspb.PhraseMatcher + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.client.CreatePhraseMatcher(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return resp, nil } -// CreateAnalysisOperation returns a new CreateAnalysisOperation from a given name. -// The name must be that of a previously created CreateAnalysisOperation, possibly from a different process. -func (c *Client) CreateAnalysisOperation(name string) *CreateAnalysisOperation { - return c.internalClient.CreateAnalysisOperation(name) -} +func (c *gRPCClient) GetPhraseMatcher(ctx context.Context, req *contactcenterinsightspb.GetPhraseMatcherRequest, opts ...gax.CallOption) (*contactcenterinsightspb.PhraseMatcher, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) -// GetAnalysis gets an analysis. -func (c *Client) GetAnalysis(ctx context.Context, req *contactcenterinsightspb.GetAnalysisRequest, opts ...gax.CallOption) (*contactcenterinsightspb.Analysis, error) { - return c.internalClient.GetAnalysis(ctx, req, opts...) + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).GetPhraseMatcher[0:len((*c.CallOptions).GetPhraseMatcher):len((*c.CallOptions).GetPhraseMatcher)], opts...) + var resp *contactcenterinsightspb.PhraseMatcher + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.client.GetPhraseMatcher(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return resp, nil } -// ListAnalyses lists analyses. -func (c *Client) ListAnalyses(ctx context.Context, req *contactcenterinsightspb.ListAnalysesRequest, opts ...gax.CallOption) *AnalysisIterator { - return c.internalClient.ListAnalyses(ctx, req, opts...) -} +func (c *gRPCClient) ListPhraseMatchers(ctx context.Context, req *contactcenterinsightspb.ListPhraseMatchersRequest, opts ...gax.CallOption) *PhraseMatcherIterator { + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) -// DeleteAnalysis deletes an analysis. -func (c *Client) DeleteAnalysis(ctx context.Context, req *contactcenterinsightspb.DeleteAnalysisRequest, opts ...gax.CallOption) error { - return c.internalClient.DeleteAnalysis(ctx, req, opts...) -} + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).ListPhraseMatchers[0:len((*c.CallOptions).ListPhraseMatchers):len((*c.CallOptions).ListPhraseMatchers)], opts...) + it := &PhraseMatcherIterator{} + req = proto.Clone(req).(*contactcenterinsightspb.ListPhraseMatchersRequest) + it.InternalFetch = func(pageSize int, pageToken string) ([]*contactcenterinsightspb.PhraseMatcher, string, error) { + resp := &contactcenterinsightspb.ListPhraseMatchersResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.client.ListPhraseMatchers(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, "", err + } -// ExportInsightsData export insights data to a destination defined in the request body. -func (c *Client) ExportInsightsData(ctx context.Context, req *contactcenterinsightspb.ExportInsightsDataRequest, opts ...gax.CallOption) (*ExportInsightsDataOperation, error) { - return c.internalClient.ExportInsightsData(ctx, req, opts...) -} + it.Response = resp + return resp.GetPhraseMatchers(), resp.GetNextPageToken(), 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 + } -// ExportInsightsDataOperation returns a new ExportInsightsDataOperation from a given name. -// The name must be that of a previously created ExportInsightsDataOperation, possibly from a different process. -func (c *Client) ExportInsightsDataOperation(name string) *ExportInsightsDataOperation { - return c.internalClient.ExportInsightsDataOperation(name) -} + it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() -// CreateIssueModel creates an issue model. -func (c *Client) CreateIssueModel(ctx context.Context, req *contactcenterinsightspb.CreateIssueModelRequest, opts ...gax.CallOption) (*CreateIssueModelOperation, error) { - return c.internalClient.CreateIssueModel(ctx, req, opts...) + return it } -// CreateIssueModelOperation returns a new CreateIssueModelOperation from a given name. -// The name must be that of a previously created CreateIssueModelOperation, possibly from a different process. -func (c *Client) CreateIssueModelOperation(name string) *CreateIssueModelOperation { - return c.internalClient.CreateIssueModelOperation(name) -} +func (c *gRPCClient) DeletePhraseMatcher(ctx context.Context, req *contactcenterinsightspb.DeletePhraseMatcherRequest, opts ...gax.CallOption) error { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) -// UpdateIssueModel updates an issue model. -func (c *Client) UpdateIssueModel(ctx context.Context, req *contactcenterinsightspb.UpdateIssueModelRequest, opts ...gax.CallOption) (*contactcenterinsightspb.IssueModel, error) { - return c.internalClient.UpdateIssueModel(ctx, req, opts...) + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).DeletePhraseMatcher[0:len((*c.CallOptions).DeletePhraseMatcher):len((*c.CallOptions).DeletePhraseMatcher)], opts...) + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + _, err = c.client.DeletePhraseMatcher(ctx, req, settings.GRPC...) + return err + }, opts...) + return err } -// GetIssueModel gets an issue model. -func (c *Client) GetIssueModel(ctx context.Context, req *contactcenterinsightspb.GetIssueModelRequest, opts ...gax.CallOption) (*contactcenterinsightspb.IssueModel, error) { - return c.internalClient.GetIssueModel(ctx, req, opts...) -} +func (c *gRPCClient) UpdatePhraseMatcher(ctx context.Context, req *contactcenterinsightspb.UpdatePhraseMatcherRequest, opts ...gax.CallOption) (*contactcenterinsightspb.PhraseMatcher, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "phrase_matcher.name", url.QueryEscape(req.GetPhraseMatcher().GetName()))) -// ListIssueModels lists issue models. -func (c *Client) ListIssueModels(ctx context.Context, req *contactcenterinsightspb.ListIssueModelsRequest, opts ...gax.CallOption) (*contactcenterinsightspb.ListIssueModelsResponse, error) { - return c.internalClient.ListIssueModels(ctx, req, opts...) + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).UpdatePhraseMatcher[0:len((*c.CallOptions).UpdatePhraseMatcher):len((*c.CallOptions).UpdatePhraseMatcher)], opts...) + var resp *contactcenterinsightspb.PhraseMatcher + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.client.UpdatePhraseMatcher(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return resp, nil } -// DeleteIssueModel deletes an issue model. -func (c *Client) DeleteIssueModel(ctx context.Context, req *contactcenterinsightspb.DeleteIssueModelRequest, opts ...gax.CallOption) (*DeleteIssueModelOperation, error) { - return c.internalClient.DeleteIssueModel(ctx, req, opts...) -} +func (c *gRPCClient) CalculateStats(ctx context.Context, req *contactcenterinsightspb.CalculateStatsRequest, opts ...gax.CallOption) (*contactcenterinsightspb.CalculateStatsResponse, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "location", url.QueryEscape(req.GetLocation()))) -// DeleteIssueModelOperation returns a new DeleteIssueModelOperation from a given name. -// The name must be that of a previously created DeleteIssueModelOperation, possibly from a different process. -func (c *Client) DeleteIssueModelOperation(name string) *DeleteIssueModelOperation { - return c.internalClient.DeleteIssueModelOperation(name) + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).CalculateStats[0:len((*c.CallOptions).CalculateStats):len((*c.CallOptions).CalculateStats)], opts...) + var resp *contactcenterinsightspb.CalculateStatsResponse + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.client.CalculateStats(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return resp, nil } -// DeployIssueModel deploys an issue model. Returns an error if a model is already deployed. -// An issue model can only be used in analysis after it has been deployed. -func (c *Client) DeployIssueModel(ctx context.Context, req *contactcenterinsightspb.DeployIssueModelRequest, opts ...gax.CallOption) (*DeployIssueModelOperation, error) { - return c.internalClient.DeployIssueModel(ctx, req, opts...) -} +func (c *gRPCClient) GetSettings(ctx context.Context, req *contactcenterinsightspb.GetSettingsRequest, opts ...gax.CallOption) (*contactcenterinsightspb.Settings, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) -// DeployIssueModelOperation returns a new DeployIssueModelOperation from a given name. -// The name must be that of a previously created DeployIssueModelOperation, possibly from a different process. -func (c *Client) DeployIssueModelOperation(name string) *DeployIssueModelOperation { - return c.internalClient.DeployIssueModelOperation(name) + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).GetSettings[0:len((*c.CallOptions).GetSettings):len((*c.CallOptions).GetSettings)], opts...) + var resp *contactcenterinsightspb.Settings + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.client.GetSettings(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return resp, nil } -// UndeployIssueModel undeploys an issue model. -// An issue model can not be used in analysis after it has been undeployed. -func (c *Client) UndeployIssueModel(ctx context.Context, req *contactcenterinsightspb.UndeployIssueModelRequest, opts ...gax.CallOption) (*UndeployIssueModelOperation, error) { - return c.internalClient.UndeployIssueModel(ctx, req, opts...) -} +func (c *gRPCClient) UpdateSettings(ctx context.Context, req *contactcenterinsightspb.UpdateSettingsRequest, opts ...gax.CallOption) (*contactcenterinsightspb.Settings, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "settings.name", url.QueryEscape(req.GetSettings().GetName()))) -// UndeployIssueModelOperation returns a new UndeployIssueModelOperation from a given name. -// The name must be that of a previously created UndeployIssueModelOperation, possibly from a different process. -func (c *Client) UndeployIssueModelOperation(name string) *UndeployIssueModelOperation { - return c.internalClient.UndeployIssueModelOperation(name) + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).UpdateSettings[0:len((*c.CallOptions).UpdateSettings):len((*c.CallOptions).UpdateSettings)], opts...) + var resp *contactcenterinsightspb.Settings + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.client.UpdateSettings(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return resp, nil } -// GetIssue gets an issue. -func (c *Client) GetIssue(ctx context.Context, req *contactcenterinsightspb.GetIssueRequest, opts ...gax.CallOption) (*contactcenterinsightspb.Issue, error) { - return c.internalClient.GetIssue(ctx, req, opts...) -} +func (c *gRPCClient) CreateView(ctx context.Context, req *contactcenterinsightspb.CreateViewRequest, opts ...gax.CallOption) (*contactcenterinsightspb.View, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) -// ListIssues lists issues. -func (c *Client) ListIssues(ctx context.Context, req *contactcenterinsightspb.ListIssuesRequest, opts ...gax.CallOption) (*contactcenterinsightspb.ListIssuesResponse, error) { - return c.internalClient.ListIssues(ctx, req, opts...) + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).CreateView[0:len((*c.CallOptions).CreateView):len((*c.CallOptions).CreateView)], opts...) + var resp *contactcenterinsightspb.View + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.client.CreateView(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return resp, nil } -// UpdateIssue updates an issue. -func (c *Client) UpdateIssue(ctx context.Context, req *contactcenterinsightspb.UpdateIssueRequest, opts ...gax.CallOption) (*contactcenterinsightspb.Issue, error) { - return c.internalClient.UpdateIssue(ctx, req, opts...) -} +func (c *gRPCClient) GetView(ctx context.Context, req *contactcenterinsightspb.GetViewRequest, opts ...gax.CallOption) (*contactcenterinsightspb.View, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) -// CalculateIssueModelStats gets an issue model’s statistics. -func (c *Client) CalculateIssueModelStats(ctx context.Context, req *contactcenterinsightspb.CalculateIssueModelStatsRequest, opts ...gax.CallOption) (*contactcenterinsightspb.CalculateIssueModelStatsResponse, error) { - return c.internalClient.CalculateIssueModelStats(ctx, req, opts...) + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).GetView[0:len((*c.CallOptions).GetView):len((*c.CallOptions).GetView)], opts...) + var resp *contactcenterinsightspb.View + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.client.GetView(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return resp, nil } -// CreatePhraseMatcher creates a phrase matcher. -func (c *Client) CreatePhraseMatcher(ctx context.Context, req *contactcenterinsightspb.CreatePhraseMatcherRequest, opts ...gax.CallOption) (*contactcenterinsightspb.PhraseMatcher, error) { - return c.internalClient.CreatePhraseMatcher(ctx, req, opts...) -} +func (c *gRPCClient) ListViews(ctx context.Context, req *contactcenterinsightspb.ListViewsRequest, opts ...gax.CallOption) *ViewIterator { + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) -// GetPhraseMatcher gets a phrase matcher. -func (c *Client) GetPhraseMatcher(ctx context.Context, req *contactcenterinsightspb.GetPhraseMatcherRequest, opts ...gax.CallOption) (*contactcenterinsightspb.PhraseMatcher, error) { - return c.internalClient.GetPhraseMatcher(ctx, req, opts...) -} + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).ListViews[0:len((*c.CallOptions).ListViews):len((*c.CallOptions).ListViews)], opts...) + it := &ViewIterator{} + req = proto.Clone(req).(*contactcenterinsightspb.ListViewsRequest) + it.InternalFetch = func(pageSize int, pageToken string) ([]*contactcenterinsightspb.View, string, error) { + resp := &contactcenterinsightspb.ListViewsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.client.ListViews(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, "", err + } -// ListPhraseMatchers lists phrase matchers. -func (c *Client) ListPhraseMatchers(ctx context.Context, req *contactcenterinsightspb.ListPhraseMatchersRequest, opts ...gax.CallOption) *PhraseMatcherIterator { - return c.internalClient.ListPhraseMatchers(ctx, req, opts...) -} + it.Response = resp + return resp.GetViews(), resp.GetNextPageToken(), 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 + } -// DeletePhraseMatcher deletes a phrase matcher. -func (c *Client) DeletePhraseMatcher(ctx context.Context, req *contactcenterinsightspb.DeletePhraseMatcherRequest, opts ...gax.CallOption) error { - return c.internalClient.DeletePhraseMatcher(ctx, req, opts...) -} + it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() -// UpdatePhraseMatcher updates a phrase matcher. -func (c *Client) UpdatePhraseMatcher(ctx context.Context, req *contactcenterinsightspb.UpdatePhraseMatcherRequest, opts ...gax.CallOption) (*contactcenterinsightspb.PhraseMatcher, error) { - return c.internalClient.UpdatePhraseMatcher(ctx, req, opts...) + return it } -// CalculateStats gets conversation statistics. -func (c *Client) CalculateStats(ctx context.Context, req *contactcenterinsightspb.CalculateStatsRequest, opts ...gax.CallOption) (*contactcenterinsightspb.CalculateStatsResponse, error) { - return c.internalClient.CalculateStats(ctx, req, opts...) -} +func (c *gRPCClient) UpdateView(ctx context.Context, req *contactcenterinsightspb.UpdateViewRequest, opts ...gax.CallOption) (*contactcenterinsightspb.View, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "view.name", url.QueryEscape(req.GetView().GetName()))) -// GetSettings gets project-level settings. -func (c *Client) GetSettings(ctx context.Context, req *contactcenterinsightspb.GetSettingsRequest, opts ...gax.CallOption) (*contactcenterinsightspb.Settings, error) { - return c.internalClient.GetSettings(ctx, req, opts...) + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).UpdateView[0:len((*c.CallOptions).UpdateView):len((*c.CallOptions).UpdateView)], opts...) + var resp *contactcenterinsightspb.View + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.client.UpdateView(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return resp, nil } -// UpdateSettings updates project-level settings. -func (c *Client) UpdateSettings(ctx context.Context, req *contactcenterinsightspb.UpdateSettingsRequest, opts ...gax.CallOption) (*contactcenterinsightspb.Settings, error) { - return c.internalClient.UpdateSettings(ctx, req, opts...) +func (c *gRPCClient) DeleteView(ctx context.Context, req *contactcenterinsightspb.DeleteViewRequest, opts ...gax.CallOption) error { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).DeleteView[0:len((*c.CallOptions).DeleteView):len((*c.CallOptions).DeleteView)], opts...) + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + _, err = c.client.DeleteView(ctx, req, settings.GRPC...) + return err + }, opts...) + return err } -// CreateView creates a view. -func (c *Client) CreateView(ctx context.Context, req *contactcenterinsightspb.CreateViewRequest, opts ...gax.CallOption) (*contactcenterinsightspb.View, error) { - return c.internalClient.CreateView(ctx, req, opts...) +func (c *gRPCClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + 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 } -// GetView gets a view. -func (c *Client) GetView(ctx context.Context, req *contactcenterinsightspb.GetViewRequest, opts ...gax.CallOption) (*contactcenterinsightspb.View, error) { - return c.internalClient.GetView(ctx, req, opts...) -} +func (c *gRPCClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) -// ListViews lists views. -func (c *Client) ListViews(ctx context.Context, req *contactcenterinsightspb.ListViewsRequest, opts ...gax.CallOption) *ViewIterator { - return c.internalClient.ListViews(ctx, req, opts...) + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + 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 } -// UpdateView updates a view. -func (c *Client) UpdateView(ctx context.Context, req *contactcenterinsightspb.UpdateViewRequest, opts ...gax.CallOption) (*contactcenterinsightspb.View, error) { - return c.internalClient.UpdateView(ctx, req, opts...) -} +func (c *gRPCClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) -// DeleteView deletes a view. -func (c *Client) DeleteView(ctx context.Context, req *contactcenterinsightspb.DeleteViewRequest, opts ...gax.CallOption) error { - return c.internalClient.DeleteView(ctx, req, opts...) -} + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).ListOperations[0:len((*c.CallOptions).ListOperations):len((*c.CallOptions).ListOperations)], opts...) + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + 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 + } -// CancelOperation is a utility method from google.longrunning.Operations. -func (c *Client) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { - return c.internalClient.CancelOperation(ctx, req, opts...) -} + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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 + } -// GetOperation is a utility method from google.longrunning.Operations. -func (c *Client) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { - return c.internalClient.GetOperation(ctx, req, opts...) -} + it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() -// ListOperations is a utility method from google.longrunning.Operations. -func (c *Client) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { - return c.internalClient.ListOperations(ctx, req, opts...) + return it } -// gRPCClient is a client for interacting with Contact Center AI Insights API over gRPC transport. -// -// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. -type gRPCClient struct { - // Connection pool of gRPC connections to the service. - connPool gtransport.ConnPool +// CreateConversation creates a conversation. +func (c *restClient) CreateConversation(ctx context.Context, req *contactcenterinsightspb.CreateConversationRequest, opts ...gax.CallOption) (*contactcenterinsightspb.Conversation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetConversation() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } - // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE - disableDeadlines bool + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/conversations", req.GetParent()) - // Points back to the CallOptions field of the containing Client - CallOptions **CallOptions + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetConversationId() != "" { + params.Add("conversationId", fmt.Sprintf("%v", req.GetConversationId())) + } - // The gRPC API client. - client contactcenterinsightspb.ContactCenterInsightsClient + baseUrl.RawQuery = params.Encode() - // LROClient is used internally to handle long-running operations. - // It is exposed so that its CallOptions can be modified if required. - // Users should not Close this client. - LROClient **lroauto.OperationsClient + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) - operationsClient longrunningpb.OperationsClient + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateConversation[0:len((*c.CallOptions).CreateConversation):len((*c.CallOptions).CreateConversation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &contactcenterinsightspb.Conversation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers - // The x-goog-* metadata to be sent with each request. - xGoogMetadata metadata.MD -} + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() -// NewClient creates a new contact center insights client based on gRPC. -// The returned client must be Closed when it is done being used to clean up its underlying connections. -// -// An API that lets users analyze and explore their business conversation data. -func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultGRPCClientOptions() - if newClientHook != nil { - hookOpts, err := newClientHook(ctx, clientHookParams{}) + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) if err != nil { - return nil, err + return err } - clientOpts = append(clientOpts, hookOpts...) + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e } + return resp, nil +} - disableDeadlines, err := checkDisableDeadlines() +// UpdateConversation updates a conversation. +func (c *restClient) UpdateConversation(ctx context.Context, req *contactcenterinsightspb.UpdateConversationRequest, opts ...gax.CallOption) (*contactcenterinsightspb.Conversation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetConversation() + jsonReq, err := m.Marshal(body) if err != nil { return nil, err } - connPool, err := gtransport.DialPool(ctx, append(clientOpts, opts...)...) + baseUrl, err := url.Parse(c.endpoint) if err != nil { return nil, err } - client := Client{CallOptions: defaultCallOptions()} + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetConversation().GetName()) - c := &gRPCClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - client: contactcenterinsightspb.NewContactCenterInsightsClient(connPool), - CallOptions: &client.CallOptions, - operationsClient: longrunningpb.NewOperationsClient(connPool), + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) } - c.setGoogleClientInfo() - client.internalClient = c + baseUrl.RawQuery = params.Encode() - client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) - if err != nil { - // This error "should not happen", since we are just reusing old connection pool - // and never actually need to dial. - // If this does happen, we could leak connp. However, we cannot close conn: - // If the user invoked the constructor with option.WithGRPCConn, - // we would close a connection that's still in use. - // TODO: investigate error conditions. - return nil, err - } - c.LROClient = &client.LROClient - return &client, nil -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "conversation.name", url.QueryEscape(req.GetConversation().GetName()))) -// Connection returns a connection to the API service. -// -// Deprecated: Connections are now pooled so this method does not always -// return the same resource. -func (c *gRPCClient) Connection() *grpc.ClientConn { - return c.connPool.Conn() -} + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateConversation[0:len((*c.CallOptions).UpdateConversation):len((*c.CallOptions).UpdateConversation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &contactcenterinsightspb.Conversation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers -// 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 *gRPCClient) setGoogleClientInfo(keyval ...string) { - kv := append([]string{"gl-go", versionGo()}, keyval...) - kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "grpc", grpc.Version) - c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) -} + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *gRPCClient) Close() error { - return c.connPool.Close() -} + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } -func (c *gRPCClient) CreateConversation(ctx context.Context, req *contactcenterinsightspb.CreateConversationRequest, opts ...gax.CallOption) (*contactcenterinsightspb.Conversation, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx - } - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).CreateConversation[0:len((*c.CallOptions).CreateConversation):len((*c.CallOptions).CreateConversation)], opts...) - var resp *contactcenterinsightspb.Conversation - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.client.CreateConversation(ctx, req, settings.GRPC...) - return err + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil }, opts...) - if err != nil { - return nil, err + if e != nil { + return nil, e } return resp, nil } -func (c *gRPCClient) UpdateConversation(ctx context.Context, req *contactcenterinsightspb.UpdateConversationRequest, opts ...gax.CallOption) (*contactcenterinsightspb.Conversation, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx - } - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "conversation.name", url.QueryEscape(req.GetConversation().GetName()))) - - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).UpdateConversation[0:len((*c.CallOptions).UpdateConversation):len((*c.CallOptions).UpdateConversation)], opts...) - var resp *contactcenterinsightspb.Conversation - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.client.UpdateConversation(ctx, req, settings.GRPC...) - return err - }, opts...) +// GetConversation gets a conversation. +func (c *restClient) GetConversation(ctx context.Context, req *contactcenterinsightspb.GetConversationRequest, opts ...gax.CallOption) (*contactcenterinsightspb.Conversation, error) { + baseUrl, err := url.Parse(c.endpoint) if err != nil { return nil, err } - return resp, nil -} + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetView() != 0 { + params.Add("view", fmt.Sprintf("%v", req.GetView())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetConversation[0:len((*c.CallOptions).GetConversation):len((*c.CallOptions).GetConversation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &contactcenterinsightspb.Conversation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() -func (c *gRPCClient) GetConversation(ctx context.Context, req *contactcenterinsightspb.GetConversationRequest, opts ...gax.CallOption) (*contactcenterinsightspb.Conversation, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx - } - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).GetConversation[0:len((*c.CallOptions).GetConversation):len((*c.CallOptions).GetConversation)], opts...) - var resp *contactcenterinsightspb.Conversation - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.client.GetConversation(ctx, req, settings.GRPC...) - return err + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil }, opts...) - if err != nil { - return nil, err + if e != nil { + return nil, e } return resp, nil } -func (c *gRPCClient) ListConversations(ctx context.Context, req *contactcenterinsightspb.ListConversationsRequest, opts ...gax.CallOption) *ConversationIterator { - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) - - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).ListConversations[0:len((*c.CallOptions).ListConversations):len((*c.CallOptions).ListConversations)], opts...) +// ListConversations lists conversations. +func (c *restClient) ListConversations(ctx context.Context, req *contactcenterinsightspb.ListConversationsRequest, opts ...gax.CallOption) *ConversationIterator { it := &ConversationIterator{} req = proto.Clone(req).(*contactcenterinsightspb.ListConversationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} it.InternalFetch = func(pageSize int, pageToken string) ([]*contactcenterinsightspb.Conversation, string, error) { resp := &contactcenterinsightspb.ListConversationsResponse{} if pageToken != "" { @@ -1002,18 +2520,69 @@ func (c *gRPCClient) ListConversations(ctx context.Context, req *contactcenterin } else if pageSize != 0 { req.PageSize = int32(pageSize) } - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.client.ListConversations(ctx, req, settings.GRPC...) - return err - }, opts...) + baseUrl, err := url.Parse(c.endpoint) if err != nil { return nil, "", err } + baseUrl.Path += fmt.Sprintf("/v1/%v/conversations", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + if req.GetView() != 0 { + params.Add("view", fmt.Sprintf("%v", req.GetView())) + } + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } it.Response = resp return resp.GetConversations(), resp.GetNextPageToken(), nil } + fetch := func(pageSize int, pageToken string) (string, error) { items, nextPageToken, err := it.InternalFetch(pageSize, pageToken) if err != nil { @@ -1030,77 +2599,182 @@ func (c *gRPCClient) ListConversations(ctx context.Context, req *contactcenterin return it } -func (c *gRPCClient) DeleteConversation(ctx context.Context, req *contactcenterinsightspb.DeleteConversationRequest, opts ...gax.CallOption) error { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx +// DeleteConversation deletes a conversation. +func (c *restClient) DeleteConversation(ctx context.Context, req *contactcenterinsightspb.DeleteConversationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetForce() { + params.Add("force", fmt.Sprintf("%v", req.GetForce())) } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).DeleteConversation[0:len((*c.CallOptions).DeleteConversation):len((*c.CallOptions).DeleteConversation)], opts...) - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - _, err = c.client.DeleteConversation(ctx, req, settings.GRPC...) - return err + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) }, opts...) - return err } -func (c *gRPCClient) CreateAnalysis(ctx context.Context, req *contactcenterinsightspb.CreateAnalysisRequest, opts ...gax.CallOption) (*CreateAnalysisOperation, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx +// CreateAnalysis creates an analysis. The long running operation is done when the analysis +// has completed. +func (c *restClient) CreateAnalysis(ctx context.Context, req *contactcenterinsightspb.CreateAnalysisRequest, opts ...gax.CallOption) (*CreateAnalysisOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetAnalysis() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err } - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).CreateAnalysis[0:len((*c.CallOptions).CreateAnalysis):len((*c.CallOptions).CreateAnalysis)], opts...) - var resp *longrunningpb.Operation - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.client.CreateAnalysis(ctx, req, settings.GRPC...) - return err - }, opts...) + baseUrl, err := url.Parse(c.endpoint) if err != nil { return nil, err } + baseUrl.Path += fmt.Sprintf("/v1/%v/analyses", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) return &CreateAnalysisOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, }, nil } -func (c *gRPCClient) GetAnalysis(ctx context.Context, req *contactcenterinsightspb.GetAnalysisRequest, opts ...gax.CallOption) (*contactcenterinsightspb.Analysis, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx +// GetAnalysis gets an analysis. +func (c *restClient) GetAnalysis(ctx context.Context, req *contactcenterinsightspb.GetAnalysisRequest, opts ...gax.CallOption) (*contactcenterinsightspb.Analysis, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) opts = append((*c.CallOptions).GetAnalysis[0:len((*c.CallOptions).GetAnalysis):len((*c.CallOptions).GetAnalysis)], opts...) - var resp *contactcenterinsightspb.Analysis - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.client.GetAnalysis(ctx, req, settings.GRPC...) - return err + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &contactcenterinsightspb.Analysis{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil }, opts...) - if err != nil { - return nil, err + if e != nil { + return nil, e } return resp, nil } -func (c *gRPCClient) ListAnalyses(ctx context.Context, req *contactcenterinsightspb.ListAnalysesRequest, opts ...gax.CallOption) *AnalysisIterator { - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) - - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).ListAnalyses[0:len((*c.CallOptions).ListAnalyses):len((*c.CallOptions).ListAnalyses)], opts...) +// ListAnalyses lists analyses. +func (c *restClient) ListAnalyses(ctx context.Context, req *contactcenterinsightspb.ListAnalysesRequest, opts ...gax.CallOption) *AnalysisIterator { it := &AnalysisIterator{} req = proto.Clone(req).(*contactcenterinsightspb.ListAnalysesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} it.InternalFetch = func(pageSize int, pageToken string) ([]*contactcenterinsightspb.Analysis, string, error) { resp := &contactcenterinsightspb.ListAnalysesResponse{} if pageToken != "" { @@ -1111,18 +2785,66 @@ func (c *gRPCClient) ListAnalyses(ctx context.Context, req *contactcenterinsight } else if pageSize != 0 { req.PageSize = int32(pageSize) } - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.client.ListAnalyses(ctx, req, settings.GRPC...) - return err - }, opts...) + baseUrl, err := url.Parse(c.endpoint) if err != nil { return nil, "", err } + baseUrl.Path += fmt.Sprintf("/v1/%v/analyses", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } it.Response = resp return resp.GetAnalyses(), resp.GetNextPageToken(), nil } + fetch := func(pageSize int, pageToken string) (string, error) { items, nextPageToken, err := it.InternalFetch(pageSize, pageToken) if err != nil { @@ -1139,349 +2861,945 @@ func (c *gRPCClient) ListAnalyses(ctx context.Context, req *contactcenterinsight return it } -func (c *gRPCClient) DeleteAnalysis(ctx context.Context, req *contactcenterinsightspb.DeleteAnalysisRequest, opts ...gax.CallOption) error { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx +// DeleteAnalysis deletes an analysis. +func (c *restClient) DeleteAnalysis(ctx context.Context, req *contactcenterinsightspb.DeleteAnalysisRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).DeleteAnalysis[0:len((*c.CallOptions).DeleteAnalysis):len((*c.CallOptions).DeleteAnalysis)], opts...) - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - _, err = c.client.DeleteAnalysis(ctx, req, settings.GRPC...) - return err + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) }, opts...) - return err } -func (c *gRPCClient) ExportInsightsData(ctx context.Context, req *contactcenterinsightspb.ExportInsightsDataRequest, opts ...gax.CallOption) (*ExportInsightsDataOperation, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx - } - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) +// ExportInsightsData export insights data to a destination defined in the request body. +func (c *restClient) ExportInsightsData(ctx context.Context, req *contactcenterinsightspb.ExportInsightsDataRequest, opts ...gax.CallOption) (*ExportInsightsDataOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/insightsdata:export", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &ExportInsightsDataOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// CreateIssueModel creates an issue model. +func (c *restClient) CreateIssueModel(ctx context.Context, req *contactcenterinsightspb.CreateIssueModelRequest, opts ...gax.CallOption) (*CreateIssueModelOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetIssueModel() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/issueModels", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).ExportInsightsData[0:len((*c.CallOptions).ExportInsightsData):len((*c.CallOptions).ExportInsightsData)], opts...) - var resp *longrunningpb.Operation - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.client.ExportInsightsData(ctx, req, settings.GRPC...) - return err + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil }, opts...) - if err != nil { - return nil, err + if e != nil { + return nil, e } - return &ExportInsightsDataOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, resp), + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateIssueModelOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, }, nil } -func (c *gRPCClient) CreateIssueModel(ctx context.Context, req *contactcenterinsightspb.CreateIssueModelRequest, opts ...gax.CallOption) (*CreateIssueModelOperation, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx +// UpdateIssueModel updates an issue model. +func (c *restClient) UpdateIssueModel(ctx context.Context, req *contactcenterinsightspb.UpdateIssueModelRequest, opts ...gax.CallOption) (*contactcenterinsightspb.IssueModel, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetIssueModel() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err } - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).CreateIssueModel[0:len((*c.CallOptions).CreateIssueModel):len((*c.CallOptions).CreateIssueModel)], opts...) - var resp *longrunningpb.Operation - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.client.CreateIssueModel(ctx, req, settings.GRPC...) - return err - }, opts...) + baseUrl, err := url.Parse(c.endpoint) if err != nil { return nil, err } - return &CreateIssueModelOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, resp), - }, nil -} + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetIssueModel().GetName()) -func (c *gRPCClient) UpdateIssueModel(ctx context.Context, req *contactcenterinsightspb.UpdateIssueModelRequest, opts ...gax.CallOption) (*contactcenterinsightspb.IssueModel, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "issue_model.name", url.QueryEscape(req.GetIssueModel().GetName()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) opts = append((*c.CallOptions).UpdateIssueModel[0:len((*c.CallOptions).UpdateIssueModel):len((*c.CallOptions).UpdateIssueModel)], opts...) - var resp *contactcenterinsightspb.IssueModel - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.client.UpdateIssueModel(ctx, req, settings.GRPC...) - return err + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &contactcenterinsightspb.IssueModel{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil }, opts...) - if err != nil { - return nil, err + if e != nil { + return nil, e } return resp, nil } -func (c *gRPCClient) GetIssueModel(ctx context.Context, req *contactcenterinsightspb.GetIssueModelRequest, opts ...gax.CallOption) (*contactcenterinsightspb.IssueModel, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx +// GetIssueModel gets an issue model. +func (c *restClient) GetIssueModel(ctx context.Context, req *contactcenterinsightspb.GetIssueModelRequest, opts ...gax.CallOption) (*contactcenterinsightspb.IssueModel, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) opts = append((*c.CallOptions).GetIssueModel[0:len((*c.CallOptions).GetIssueModel):len((*c.CallOptions).GetIssueModel)], opts...) - var resp *contactcenterinsightspb.IssueModel - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.client.GetIssueModel(ctx, req, settings.GRPC...) - return err + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &contactcenterinsightspb.IssueModel{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil }, opts...) - if err != nil { - return nil, err + if e != nil { + return nil, e } return resp, nil } -func (c *gRPCClient) ListIssueModels(ctx context.Context, req *contactcenterinsightspb.ListIssueModelsRequest, opts ...gax.CallOption) (*contactcenterinsightspb.ListIssueModelsResponse, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx +// ListIssueModels lists issue models. +func (c *restClient) ListIssueModels(ctx context.Context, req *contactcenterinsightspb.ListIssueModelsRequest, opts ...gax.CallOption) (*contactcenterinsightspb.ListIssueModelsResponse, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err } + baseUrl.Path += fmt.Sprintf("/v1/%v/issueModels", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) opts = append((*c.CallOptions).ListIssueModels[0:len((*c.CallOptions).ListIssueModels):len((*c.CallOptions).ListIssueModels)], opts...) - var resp *contactcenterinsightspb.ListIssueModelsResponse - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.client.ListIssueModels(ctx, req, settings.GRPC...) - return err + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &contactcenterinsightspb.ListIssueModelsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil }, opts...) - if err != nil { - return nil, err + if e != nil { + return nil, e } return resp, nil } -func (c *gRPCClient) DeleteIssueModel(ctx context.Context, req *contactcenterinsightspb.DeleteIssueModelRequest, opts ...gax.CallOption) (*DeleteIssueModelOperation, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx +// DeleteIssueModel deletes an issue model. +func (c *restClient) DeleteIssueModel(ctx context.Context, req *contactcenterinsightspb.DeleteIssueModelRequest, opts ...gax.CallOption) (*DeleteIssueModelOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).DeleteIssueModel[0:len((*c.CallOptions).DeleteIssueModel):len((*c.CallOptions).DeleteIssueModel)], opts...) - var resp *longrunningpb.Operation - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.client.DeleteIssueModel(ctx, req, settings.GRPC...) - return err + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil }, opts...) - if err != nil { - return nil, err + if e != nil { + return nil, e } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) return &DeleteIssueModelOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, }, nil } -func (c *gRPCClient) DeployIssueModel(ctx context.Context, req *contactcenterinsightspb.DeployIssueModelRequest, opts ...gax.CallOption) (*DeployIssueModelOperation, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx +// DeployIssueModel deploys an issue model. Returns an error if a model is already deployed. +// An issue model can only be used in analysis after it has been deployed. +func (c *restClient) DeployIssueModel(ctx context.Context, req *contactcenterinsightspb.DeployIssueModelRequest, opts ...gax.CallOption) (*DeployIssueModelOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err } - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).DeployIssueModel[0:len((*c.CallOptions).DeployIssueModel):len((*c.CallOptions).DeployIssueModel)], opts...) - var resp *longrunningpb.Operation - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.client.DeployIssueModel(ctx, req, settings.GRPC...) - return err - }, opts...) + baseUrl, err := url.Parse(c.endpoint) if err != nil { return nil, err } + baseUrl.Path += fmt.Sprintf("/v1/%v:deploy", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) return &DeployIssueModelOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, }, nil } -func (c *gRPCClient) UndeployIssueModel(ctx context.Context, req *contactcenterinsightspb.UndeployIssueModelRequest, opts ...gax.CallOption) (*UndeployIssueModelOperation, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx +// UndeployIssueModel undeploys an issue model. +// An issue model can not be used in analysis after it has been undeployed. +func (c *restClient) UndeployIssueModel(ctx context.Context, req *contactcenterinsightspb.UndeployIssueModelRequest, opts ...gax.CallOption) (*UndeployIssueModelOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err } + baseUrl.Path += fmt.Sprintf("/v1/%v:undeploy", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).UndeployIssueModel[0:len((*c.CallOptions).UndeployIssueModel):len((*c.CallOptions).UndeployIssueModel)], opts...) - var resp *longrunningpb.Operation - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.client.UndeployIssueModel(ctx, req, settings.GRPC...) - return err + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil }, opts...) - if err != nil { - return nil, err + if e != nil { + return nil, e } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) return &UndeployIssueModelOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, }, nil } -func (c *gRPCClient) GetIssue(ctx context.Context, req *contactcenterinsightspb.GetIssueRequest, opts ...gax.CallOption) (*contactcenterinsightspb.Issue, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx +// GetIssue gets an issue. +func (c *restClient) GetIssue(ctx context.Context, req *contactcenterinsightspb.GetIssueRequest, opts ...gax.CallOption) (*contactcenterinsightspb.Issue, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) opts = append((*c.CallOptions).GetIssue[0:len((*c.CallOptions).GetIssue):len((*c.CallOptions).GetIssue)], opts...) - var resp *contactcenterinsightspb.Issue - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.client.GetIssue(ctx, req, settings.GRPC...) - return err + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &contactcenterinsightspb.Issue{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil }, opts...) - if err != nil { - return nil, err + if e != nil { + return nil, e } return resp, nil } -func (c *gRPCClient) ListIssues(ctx context.Context, req *contactcenterinsightspb.ListIssuesRequest, opts ...gax.CallOption) (*contactcenterinsightspb.ListIssuesResponse, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx +// ListIssues lists issues. +func (c *restClient) ListIssues(ctx context.Context, req *contactcenterinsightspb.ListIssuesRequest, opts ...gax.CallOption) (*contactcenterinsightspb.ListIssuesResponse, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err } + baseUrl.Path += fmt.Sprintf("/v1/%v/issues", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) opts = append((*c.CallOptions).ListIssues[0:len((*c.CallOptions).ListIssues):len((*c.CallOptions).ListIssues)], opts...) - var resp *contactcenterinsightspb.ListIssuesResponse - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.client.ListIssues(ctx, req, settings.GRPC...) - return err + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &contactcenterinsightspb.ListIssuesResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil }, opts...) - if err != nil { - return nil, err + if e != nil { + return nil, e } return resp, nil } -func (c *gRPCClient) UpdateIssue(ctx context.Context, req *contactcenterinsightspb.UpdateIssueRequest, opts ...gax.CallOption) (*contactcenterinsightspb.Issue, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx +// UpdateIssue updates an issue. +func (c *restClient) UpdateIssue(ctx context.Context, req *contactcenterinsightspb.UpdateIssueRequest, opts ...gax.CallOption) (*contactcenterinsightspb.Issue, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetIssue() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetIssue().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "issue.name", url.QueryEscape(req.GetIssue().GetName()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) opts = append((*c.CallOptions).UpdateIssue[0:len((*c.CallOptions).UpdateIssue):len((*c.CallOptions).UpdateIssue)], opts...) - var resp *contactcenterinsightspb.Issue - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.client.UpdateIssue(ctx, req, settings.GRPC...) - return err + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &contactcenterinsightspb.Issue{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil }, opts...) - if err != nil { - return nil, err + if e != nil { + return nil, e } return resp, nil } -func (c *gRPCClient) CalculateIssueModelStats(ctx context.Context, req *contactcenterinsightspb.CalculateIssueModelStatsRequest, opts ...gax.CallOption) (*contactcenterinsightspb.CalculateIssueModelStatsResponse, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx +// CalculateIssueModelStats gets an issue model’s statistics. +func (c *restClient) CalculateIssueModelStats(ctx context.Context, req *contactcenterinsightspb.CalculateIssueModelStatsRequest, opts ...gax.CallOption) (*contactcenterinsightspb.CalculateIssueModelStatsResponse, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err } + baseUrl.Path += fmt.Sprintf("/v1/%v:calculateIssueModelStats", req.GetIssueModel()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "issue_model", url.QueryEscape(req.GetIssueModel()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) opts = append((*c.CallOptions).CalculateIssueModelStats[0:len((*c.CallOptions).CalculateIssueModelStats):len((*c.CallOptions).CalculateIssueModelStats)], opts...) - var resp *contactcenterinsightspb.CalculateIssueModelStatsResponse - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.client.CalculateIssueModelStats(ctx, req, settings.GRPC...) - return err + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &contactcenterinsightspb.CalculateIssueModelStatsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil }, opts...) - if err != nil { - return nil, err + if e != nil { + return nil, e } return resp, nil } -func (c *gRPCClient) CreatePhraseMatcher(ctx context.Context, req *contactcenterinsightspb.CreatePhraseMatcherRequest, opts ...gax.CallOption) (*contactcenterinsightspb.PhraseMatcher, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx +// CreatePhraseMatcher creates a phrase matcher. +func (c *restClient) CreatePhraseMatcher(ctx context.Context, req *contactcenterinsightspb.CreatePhraseMatcherRequest, opts ...gax.CallOption) (*contactcenterinsightspb.PhraseMatcher, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetPhraseMatcher() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err } + baseUrl.Path += fmt.Sprintf("/v1/%v/phraseMatchers", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) opts = append((*c.CallOptions).CreatePhraseMatcher[0:len((*c.CallOptions).CreatePhraseMatcher):len((*c.CallOptions).CreatePhraseMatcher)], opts...) - var resp *contactcenterinsightspb.PhraseMatcher - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.client.CreatePhraseMatcher(ctx, req, settings.GRPC...) - return err + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &contactcenterinsightspb.PhraseMatcher{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil }, opts...) - if err != nil { - return nil, err + if e != nil { + return nil, e } return resp, nil } -func (c *gRPCClient) GetPhraseMatcher(ctx context.Context, req *contactcenterinsightspb.GetPhraseMatcherRequest, opts ...gax.CallOption) (*contactcenterinsightspb.PhraseMatcher, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx +// GetPhraseMatcher gets a phrase matcher. +func (c *restClient) GetPhraseMatcher(ctx context.Context, req *contactcenterinsightspb.GetPhraseMatcherRequest, opts ...gax.CallOption) (*contactcenterinsightspb.PhraseMatcher, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).GetPhraseMatcher[0:len((*c.CallOptions).GetPhraseMatcher):len((*c.CallOptions).GetPhraseMatcher)], opts...) - var resp *contactcenterinsightspb.PhraseMatcher - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.client.GetPhraseMatcher(ctx, req, settings.GRPC...) - return err + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetPhraseMatcher[0:len((*c.CallOptions).GetPhraseMatcher):len((*c.CallOptions).GetPhraseMatcher)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &contactcenterinsightspb.PhraseMatcher{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil }, opts...) - if err != nil { - return nil, err + if e != nil { + return nil, e } return resp, nil } -func (c *gRPCClient) ListPhraseMatchers(ctx context.Context, req *contactcenterinsightspb.ListPhraseMatchersRequest, opts ...gax.CallOption) *PhraseMatcherIterator { - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) - - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).ListPhraseMatchers[0:len((*c.CallOptions).ListPhraseMatchers):len((*c.CallOptions).ListPhraseMatchers)], opts...) +// ListPhraseMatchers lists phrase matchers. +func (c *restClient) ListPhraseMatchers(ctx context.Context, req *contactcenterinsightspb.ListPhraseMatchersRequest, opts ...gax.CallOption) *PhraseMatcherIterator { it := &PhraseMatcherIterator{} req = proto.Clone(req).(*contactcenterinsightspb.ListPhraseMatchersRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} it.InternalFetch = func(pageSize int, pageToken string) ([]*contactcenterinsightspb.PhraseMatcher, string, error) { resp := &contactcenterinsightspb.ListPhraseMatchersResponse{} if pageToken != "" { @@ -1492,18 +3810,66 @@ func (c *gRPCClient) ListPhraseMatchers(ctx context.Context, req *contactcenteri } else if pageSize != 0 { req.PageSize = int32(pageSize) } - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.client.ListPhraseMatchers(ctx, req, settings.GRPC...) - return err - }, opts...) + baseUrl, err := url.Parse(c.endpoint) if err != nil { return nil, "", err } + baseUrl.Path += fmt.Sprintf("/v1/%v/phraseMatchers", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } it.Response = resp return resp.GetPhraseMatchers(), resp.GetNextPageToken(), nil } + fetch := func(pageSize int, pageToken string) (string, error) { items, nextPageToken, err := it.InternalFetch(pageSize, pageToken) if err != nil { @@ -1520,163 +3886,437 @@ func (c *gRPCClient) ListPhraseMatchers(ctx context.Context, req *contactcenteri return it } -func (c *gRPCClient) DeletePhraseMatcher(ctx context.Context, req *contactcenterinsightspb.DeletePhraseMatcherRequest, opts ...gax.CallOption) error { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx +// DeletePhraseMatcher deletes a phrase matcher. +func (c *restClient) DeletePhraseMatcher(ctx context.Context, req *contactcenterinsightspb.DeletePhraseMatcherRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).DeletePhraseMatcher[0:len((*c.CallOptions).DeletePhraseMatcher):len((*c.CallOptions).DeletePhraseMatcher)], opts...) - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - _, err = c.client.DeletePhraseMatcher(ctx, req, settings.GRPC...) - return err + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) }, opts...) - return err } -func (c *gRPCClient) UpdatePhraseMatcher(ctx context.Context, req *contactcenterinsightspb.UpdatePhraseMatcherRequest, opts ...gax.CallOption) (*contactcenterinsightspb.PhraseMatcher, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx +// UpdatePhraseMatcher updates a phrase matcher. +func (c *restClient) UpdatePhraseMatcher(ctx context.Context, req *contactcenterinsightspb.UpdatePhraseMatcherRequest, opts ...gax.CallOption) (*contactcenterinsightspb.PhraseMatcher, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetPhraseMatcher() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetPhraseMatcher().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "phrase_matcher.name", url.QueryEscape(req.GetPhraseMatcher().GetName()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) opts = append((*c.CallOptions).UpdatePhraseMatcher[0:len((*c.CallOptions).UpdatePhraseMatcher):len((*c.CallOptions).UpdatePhraseMatcher)], opts...) - var resp *contactcenterinsightspb.PhraseMatcher - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.client.UpdatePhraseMatcher(ctx, req, settings.GRPC...) - return err + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &contactcenterinsightspb.PhraseMatcher{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil }, opts...) - if err != nil { - return nil, err + if e != nil { + return nil, e } return resp, nil } -func (c *gRPCClient) CalculateStats(ctx context.Context, req *contactcenterinsightspb.CalculateStatsRequest, opts ...gax.CallOption) (*contactcenterinsightspb.CalculateStatsResponse, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx +// CalculateStats gets conversation statistics. +func (c *restClient) CalculateStats(ctx context.Context, req *contactcenterinsightspb.CalculateStatsRequest, opts ...gax.CallOption) (*contactcenterinsightspb.CalculateStatsResponse, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/conversations:calculateStats", req.GetLocation()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "location", url.QueryEscape(req.GetLocation()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) opts = append((*c.CallOptions).CalculateStats[0:len((*c.CallOptions).CalculateStats):len((*c.CallOptions).CalculateStats)], opts...) - var resp *contactcenterinsightspb.CalculateStatsResponse - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.client.CalculateStats(ctx, req, settings.GRPC...) - return err + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &contactcenterinsightspb.CalculateStatsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil }, opts...) - if err != nil { - return nil, err + if e != nil { + return nil, e } return resp, nil } -func (c *gRPCClient) GetSettings(ctx context.Context, req *contactcenterinsightspb.GetSettingsRequest, opts ...gax.CallOption) (*contactcenterinsightspb.Settings, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx +// GetSettings gets project-level settings. +func (c *restClient) GetSettings(ctx context.Context, req *contactcenterinsightspb.GetSettingsRequest, opts ...gax.CallOption) (*contactcenterinsightspb.Settings, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) opts = append((*c.CallOptions).GetSettings[0:len((*c.CallOptions).GetSettings):len((*c.CallOptions).GetSettings)], opts...) - var resp *contactcenterinsightspb.Settings - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.client.GetSettings(ctx, req, settings.GRPC...) - return err + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &contactcenterinsightspb.Settings{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil }, opts...) - if err != nil { - return nil, err + if e != nil { + return nil, e } return resp, nil } -func (c *gRPCClient) UpdateSettings(ctx context.Context, req *contactcenterinsightspb.UpdateSettingsRequest, opts ...gax.CallOption) (*contactcenterinsightspb.Settings, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx +// UpdateSettings updates project-level settings. +func (c *restClient) UpdateSettings(ctx context.Context, req *contactcenterinsightspb.UpdateSettingsRequest, opts ...gax.CallOption) (*contactcenterinsightspb.Settings, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetSettings() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetSettings().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "settings.name", url.QueryEscape(req.GetSettings().GetName()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) opts = append((*c.CallOptions).UpdateSettings[0:len((*c.CallOptions).UpdateSettings):len((*c.CallOptions).UpdateSettings)], opts...) - var resp *contactcenterinsightspb.Settings - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.client.UpdateSettings(ctx, req, settings.GRPC...) - return err + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &contactcenterinsightspb.Settings{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil }, opts...) - if err != nil { - return nil, err + if e != nil { + return nil, e } return resp, nil } -func (c *gRPCClient) CreateView(ctx context.Context, req *contactcenterinsightspb.CreateViewRequest, opts ...gax.CallOption) (*contactcenterinsightspb.View, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx +// CreateView creates a view. +func (c *restClient) CreateView(ctx context.Context, req *contactcenterinsightspb.CreateViewRequest, opts ...gax.CallOption) (*contactcenterinsightspb.View, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetView() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err } + baseUrl.Path += fmt.Sprintf("/v1/%v/views", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).CreateView[0:len((*c.CallOptions).CreateView):len((*c.CallOptions).CreateView)], opts...) - var resp *contactcenterinsightspb.View - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.client.CreateView(ctx, req, settings.GRPC...) - return err + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateView[0:len((*c.CallOptions).CreateView):len((*c.CallOptions).CreateView)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &contactcenterinsightspb.View{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil }, opts...) - if err != nil { - return nil, err + if e != nil { + return nil, e } return resp, nil } -func (c *gRPCClient) GetView(ctx context.Context, req *contactcenterinsightspb.GetViewRequest, opts ...gax.CallOption) (*contactcenterinsightspb.View, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx +// GetView gets a view. +func (c *restClient) GetView(ctx context.Context, req *contactcenterinsightspb.GetViewRequest, opts ...gax.CallOption) (*contactcenterinsightspb.View, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) opts = append((*c.CallOptions).GetView[0:len((*c.CallOptions).GetView):len((*c.CallOptions).GetView)], opts...) - var resp *contactcenterinsightspb.View - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.client.GetView(ctx, req, settings.GRPC...) - return err + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &contactcenterinsightspb.View{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil }, opts...) - if err != nil { - return nil, err + if e != nil { + return nil, e } return resp, nil } -func (c *gRPCClient) ListViews(ctx context.Context, req *contactcenterinsightspb.ListViewsRequest, opts ...gax.CallOption) *ViewIterator { - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) - - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).ListViews[0:len((*c.CallOptions).ListViews):len((*c.CallOptions).ListViews)], opts...) +// ListViews lists views. +func (c *restClient) ListViews(ctx context.Context, req *contactcenterinsightspb.ListViewsRequest, opts ...gax.CallOption) *ViewIterator { it := &ViewIterator{} req = proto.Clone(req).(*contactcenterinsightspb.ListViewsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} it.InternalFetch = func(pageSize int, pageToken string) ([]*contactcenterinsightspb.View, string, error) { resp := &contactcenterinsightspb.ListViewsResponse{} if pageToken != "" { @@ -1687,18 +4327,63 @@ func (c *gRPCClient) ListViews(ctx context.Context, req *contactcenterinsightspb } else if pageSize != 0 { req.PageSize = int32(pageSize) } - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.client.ListViews(ctx, req, settings.GRPC...) - return err - }, opts...) + baseUrl, err := url.Parse(c.endpoint) if err != nil { return nil, "", err } + baseUrl.Path += fmt.Sprintf("/v1/%v/views", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } it.Response = resp return resp.GetViews(), resp.GetNextPageToken(), nil } + fetch := func(pageSize int, pageToken string) (string, error) { items, nextPageToken, err := it.InternalFetch(pageSize, pageToken) if err != nil { @@ -1715,93 +4400,221 @@ func (c *gRPCClient) ListViews(ctx context.Context, req *contactcenterinsightspb return it } -func (c *gRPCClient) UpdateView(ctx context.Context, req *contactcenterinsightspb.UpdateViewRequest, opts ...gax.CallOption) (*contactcenterinsightspb.View, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx +// UpdateView updates a view. +func (c *restClient) UpdateView(ctx context.Context, req *contactcenterinsightspb.UpdateViewRequest, opts ...gax.CallOption) (*contactcenterinsightspb.View, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetView() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetView().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "view.name", url.QueryEscape(req.GetView().GetName()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) opts = append((*c.CallOptions).UpdateView[0:len((*c.CallOptions).UpdateView):len((*c.CallOptions).UpdateView)], opts...) - var resp *contactcenterinsightspb.View - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.client.UpdateView(ctx, req, settings.GRPC...) - return err + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &contactcenterinsightspb.View{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil }, opts...) - if err != nil { - return nil, err + if e != nil { + return nil, e } return resp, nil } -func (c *gRPCClient) DeleteView(ctx context.Context, req *contactcenterinsightspb.DeleteViewRequest, opts ...gax.CallOption) error { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx +// DeleteView deletes a view. +func (c *restClient) DeleteView(ctx context.Context, req *contactcenterinsightspb.DeleteViewRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).DeleteView[0:len((*c.CallOptions).DeleteView):len((*c.CallOptions).DeleteView)], opts...) - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - _, err = c.client.DeleteView(ctx, req, settings.GRPC...) - return err + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) }, opts...) - return err } -func (c *gRPCClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *restClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err } + baseUrl.Path += fmt.Sprintf("/v1/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - 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 + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) }, opts...) - return err } -func (c *gRPCClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx +// GetOperation is a utility method from google.longrunning.Operations. +func (c *restClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) 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 + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil }, opts...) - if err != nil { - return nil, err + if e != nil { + return nil, e } return resp, nil } -func (c *gRPCClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) - - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).ListOperations[0:len((*c.CallOptions).ListOperations):len((*c.CallOptions).ListOperations)], opts...) +// ListOperations is a utility method from google.longrunning.Operations. +func (c *restClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { it := &OperationIterator{} req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { resp := &longrunningpb.ListOperationsResponse{} if pageToken != "" { @@ -1812,18 +4625,66 @@ func (c *gRPCClient) ListOperations(ctx context.Context, req *longrunningpb.List } else if pageSize != 0 { 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...) + baseUrl, err := url.Parse(c.endpoint) if err != nil { return nil, "", err } + baseUrl.Path += fmt.Sprintf("/v1/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } it.Response = resp return resp.GetOperations(), resp.GetNextPageToken(), nil } + fetch := func(pageSize int, pageToken string) (string, error) { items, nextPageToken, err := it.InternalFetch(pageSize, pageToken) if err != nil { @@ -1842,7 +4703,8 @@ func (c *gRPCClient) ListOperations(ctx context.Context, req *longrunningpb.List // CreateAnalysisOperation manages a long-running operation from CreateAnalysis. type CreateAnalysisOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateAnalysisOperation returns a new CreateAnalysisOperation from a given name. @@ -1853,10 +4715,21 @@ func (c *gRPCClient) CreateAnalysisOperation(name string) *CreateAnalysisOperati } } +// CreateAnalysisOperation returns a new CreateAnalysisOperation from a given name. +// The name must be that of a previously created CreateAnalysisOperation, possibly from a different process. +func (c *restClient) CreateAnalysisOperation(name string) *CreateAnalysisOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateAnalysisOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateAnalysisOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*contactcenterinsightspb.Analysis, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp contactcenterinsightspb.Analysis if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1874,6 +4747,7 @@ func (op *CreateAnalysisOperation) Wait(ctx context.Context, opts ...gax.CallOpt // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateAnalysisOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*contactcenterinsightspb.Analysis, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp contactcenterinsightspb.Analysis if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1911,7 +4785,8 @@ func (op *CreateAnalysisOperation) Name() string { // CreateIssueModelOperation manages a long-running operation from CreateIssueModel. type CreateIssueModelOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateIssueModelOperation returns a new CreateIssueModelOperation from a given name. @@ -1922,10 +4797,21 @@ func (c *gRPCClient) CreateIssueModelOperation(name string) *CreateIssueModelOpe } } +// CreateIssueModelOperation returns a new CreateIssueModelOperation from a given name. +// The name must be that of a previously created CreateIssueModelOperation, possibly from a different process. +func (c *restClient) CreateIssueModelOperation(name string) *CreateIssueModelOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateIssueModelOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateIssueModelOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*contactcenterinsightspb.IssueModel, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp contactcenterinsightspb.IssueModel if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1943,6 +4829,7 @@ func (op *CreateIssueModelOperation) Wait(ctx context.Context, opts ...gax.CallO // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateIssueModelOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*contactcenterinsightspb.IssueModel, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp contactcenterinsightspb.IssueModel if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1980,7 +4867,8 @@ func (op *CreateIssueModelOperation) Name() string { // DeleteIssueModelOperation manages a long-running operation from DeleteIssueModel. type DeleteIssueModelOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteIssueModelOperation returns a new DeleteIssueModelOperation from a given name. @@ -1991,10 +4879,21 @@ func (c *gRPCClient) DeleteIssueModelOperation(name string) *DeleteIssueModelOpe } } +// DeleteIssueModelOperation returns a new DeleteIssueModelOperation from a given name. +// The name must be that of a previously created DeleteIssueModelOperation, possibly from a different process. +func (c *restClient) DeleteIssueModelOperation(name string) *DeleteIssueModelOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteIssueModelOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteIssueModelOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -2008,6 +4907,7 @@ func (op *DeleteIssueModelOperation) Wait(ctx context.Context, opts ...gax.CallO // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteIssueModelOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -2038,7 +4938,8 @@ func (op *DeleteIssueModelOperation) Name() string { // DeployIssueModelOperation manages a long-running operation from DeployIssueModel. type DeployIssueModelOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeployIssueModelOperation returns a new DeployIssueModelOperation from a given name. @@ -2049,10 +4950,21 @@ func (c *gRPCClient) DeployIssueModelOperation(name string) *DeployIssueModelOpe } } +// DeployIssueModelOperation returns a new DeployIssueModelOperation from a given name. +// The name must be that of a previously created DeployIssueModelOperation, possibly from a different process. +func (c *restClient) DeployIssueModelOperation(name string) *DeployIssueModelOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeployIssueModelOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeployIssueModelOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*contactcenterinsightspb.DeployIssueModelResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp contactcenterinsightspb.DeployIssueModelResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2070,6 +4982,7 @@ func (op *DeployIssueModelOperation) Wait(ctx context.Context, opts ...gax.CallO // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeployIssueModelOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*contactcenterinsightspb.DeployIssueModelResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp contactcenterinsightspb.DeployIssueModelResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2107,7 +5020,8 @@ func (op *DeployIssueModelOperation) Name() string { // ExportInsightsDataOperation manages a long-running operation from ExportInsightsData. type ExportInsightsDataOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // ExportInsightsDataOperation returns a new ExportInsightsDataOperation from a given name. @@ -2118,10 +5032,21 @@ func (c *gRPCClient) ExportInsightsDataOperation(name string) *ExportInsightsDat } } +// ExportInsightsDataOperation returns a new ExportInsightsDataOperation from a given name. +// The name must be that of a previously created ExportInsightsDataOperation, possibly from a different process. +func (c *restClient) ExportInsightsDataOperation(name string) *ExportInsightsDataOperation { + override := fmt.Sprintf("/v1/%s", name) + return &ExportInsightsDataOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *ExportInsightsDataOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*contactcenterinsightspb.ExportInsightsDataResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp contactcenterinsightspb.ExportInsightsDataResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2139,6 +5064,7 @@ func (op *ExportInsightsDataOperation) Wait(ctx context.Context, opts ...gax.Cal // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *ExportInsightsDataOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*contactcenterinsightspb.ExportInsightsDataResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp contactcenterinsightspb.ExportInsightsDataResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2176,7 +5102,8 @@ func (op *ExportInsightsDataOperation) Name() string { // UndeployIssueModelOperation manages a long-running operation from UndeployIssueModel. type UndeployIssueModelOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UndeployIssueModelOperation returns a new UndeployIssueModelOperation from a given name. @@ -2187,10 +5114,21 @@ func (c *gRPCClient) UndeployIssueModelOperation(name string) *UndeployIssueMode } } +// UndeployIssueModelOperation returns a new UndeployIssueModelOperation from a given name. +// The name must be that of a previously created UndeployIssueModelOperation, possibly from a different process. +func (c *restClient) UndeployIssueModelOperation(name string) *UndeployIssueModelOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UndeployIssueModelOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UndeployIssueModelOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*contactcenterinsightspb.UndeployIssueModelResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp contactcenterinsightspb.UndeployIssueModelResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2208,6 +5146,7 @@ func (op *UndeployIssueModelOperation) Wait(ctx context.Context, opts ...gax.Cal // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UndeployIssueModelOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*contactcenterinsightspb.UndeployIssueModelResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp contactcenterinsightspb.UndeployIssueModelResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/contactcenterinsights/apiv1/contact_center_insights_client_example_test.go b/contactcenterinsights/apiv1/contact_center_insights_client_example_test.go index 3a5b3f062cca..b29882e8b60f 100644 --- a/contactcenterinsights/apiv1/contact_center_insights_client_example_test.go +++ b/contactcenterinsights/apiv1/contact_center_insights_client_example_test.go @@ -42,6 +42,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := contactcenterinsights.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_CreateConversation() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/contactcenterinsights/apiv1/contactcenterinsightspb/contact_center_insights.pb.go b/contactcenterinsights/apiv1/contactcenterinsightspb/contact_center_insights.pb.go index aeb895877457..011207bcbcab 100644 --- a/contactcenterinsights/apiv1/contactcenterinsightspb/contact_center_insights.pb.go +++ b/contactcenterinsights/apiv1/contactcenterinsightspb/contact_center_insights.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/contactcenterinsights/v1/contact_center_insights.proto package contactcenterinsightspb @@ -1111,7 +1111,6 @@ type ExportInsightsDataRequest struct { // Exporter destination. // // Types that are assignable to Destination: - // // *ExportInsightsDataRequest_BigQueryDestination_ Destination isExportInsightsDataRequest_Destination `protobuf_oneof:"destination"` // Required. The parent resource to export data from. diff --git a/contactcenterinsights/apiv1/contactcenterinsightspb/resources.pb.go b/contactcenterinsights/apiv1/contactcenterinsightspb/resources.pb.go index e24f289fc3a3..fc4b07c4aaff 100644 --- a/contactcenterinsights/apiv1/contactcenterinsightspb/resources.pb.go +++ b/contactcenterinsights/apiv1/contactcenterinsightspb/resources.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/contactcenterinsights/v1/resources.proto package contactcenterinsightspb @@ -575,7 +575,6 @@ type Conversation struct { // Metadata that applies to the conversation. // // Types that are assignable to Metadata: - // // *Conversation_CallMetadata_ Metadata isConversation_Metadata `protobuf_oneof:"metadata"` // A time to live expiration setting, can be either a specified timestamp or a @@ -584,7 +583,6 @@ type Conversation struct { // the specified time. // // Types that are assignable to Expiration: - // // *Conversation_ExpireTime // *Conversation_Ttl Expiration isConversation_Expiration `protobuf_oneof:"expiration"` @@ -928,7 +926,6 @@ type ConversationDataSource struct { // The source of the conversation. // // Types that are assignable to Source: - // // *ConversationDataSource_GcsSource // *ConversationDataSource_DialogflowSource Source isConversationDataSource_Source `protobuf_oneof:"source"` @@ -1135,7 +1132,6 @@ type AnalysisResult struct { // Metadata discovered during analysis. // // Types that are assignable to Metadata: - // // *AnalysisResult_CallAnalysisMetadata_ Metadata isAnalysisResult_Metadata `protobuf_oneof:"metadata"` // The time at which the analysis ended. @@ -1401,7 +1397,6 @@ type CallAnnotation struct { // The data in the annotation. // // Types that are assignable to Data: - // // *CallAnnotation_InterruptionData // *CallAnnotation_SentimentData // *CallAnnotation_SilenceData @@ -1590,7 +1585,6 @@ type AnnotationBoundary struct { // A detailed boundary, which describes a more specific point. // // Types that are assignable to DetailedBoundary: - // // *AnnotationBoundary_WordIndex DetailedBoundary isAnnotationBoundary_DetailedBoundary `protobuf_oneof:"detailed_boundary"` // The index in the sequence of transcribed pieces of the conversation where @@ -2760,7 +2754,6 @@ type PhraseMatchRuleConfig struct { // The configuration of the phrase match rule. // // Types that are assignable to Config: - // // *PhraseMatchRuleConfig_ExactMatchConfig Config isPhraseMatchRuleConfig_Config `protobuf_oneof:"config"` } @@ -3004,7 +2997,6 @@ type RuntimeAnnotation struct { // The data in the annotation. // // Types that are assignable to Data: - // // *RuntimeAnnotation_ArticleSuggestion // *RuntimeAnnotation_FaqAnswer // *RuntimeAnnotation_SmartReply @@ -3673,7 +3665,6 @@ type ConversationParticipant struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Participant: - // // *ConversationParticipant_DialogflowParticipantName // *ConversationParticipant_UserId Participant isConversationParticipant_Participant `protobuf_oneof:"participant"` diff --git a/contactcenterinsights/apiv1/doc.go b/contactcenterinsights/apiv1/doc.go index e62ab6dbef95..c0d10ea8a342 100644 --- a/contactcenterinsights/apiv1/doc.go +++ b/contactcenterinsights/apiv1/doc.go @@ -78,6 +78,8 @@ package contactcenterinsights // import "cloud.google.com/go/contactcenterinsigh import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -166,3 +168,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/contactcenterinsights/apiv1/gapic_metadata.json b/contactcenterinsights/apiv1/gapic_metadata.json index 1943a9d4efc8..06511255077d 100644 --- a/contactcenterinsights/apiv1/gapic_metadata.json +++ b/contactcenterinsights/apiv1/gapic_metadata.json @@ -196,6 +196,196 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "CalculateIssueModelStats": { + "methods": [ + "CalculateIssueModelStats" + ] + }, + "CalculateStats": { + "methods": [ + "CalculateStats" + ] + }, + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "CreateAnalysis": { + "methods": [ + "CreateAnalysis" + ] + }, + "CreateConversation": { + "methods": [ + "CreateConversation" + ] + }, + "CreateIssueModel": { + "methods": [ + "CreateIssueModel" + ] + }, + "CreatePhraseMatcher": { + "methods": [ + "CreatePhraseMatcher" + ] + }, + "CreateView": { + "methods": [ + "CreateView" + ] + }, + "DeleteAnalysis": { + "methods": [ + "DeleteAnalysis" + ] + }, + "DeleteConversation": { + "methods": [ + "DeleteConversation" + ] + }, + "DeleteIssueModel": { + "methods": [ + "DeleteIssueModel" + ] + }, + "DeletePhraseMatcher": { + "methods": [ + "DeletePhraseMatcher" + ] + }, + "DeleteView": { + "methods": [ + "DeleteView" + ] + }, + "DeployIssueModel": { + "methods": [ + "DeployIssueModel" + ] + }, + "ExportInsightsData": { + "methods": [ + "ExportInsightsData" + ] + }, + "GetAnalysis": { + "methods": [ + "GetAnalysis" + ] + }, + "GetConversation": { + "methods": [ + "GetConversation" + ] + }, + "GetIssue": { + "methods": [ + "GetIssue" + ] + }, + "GetIssueModel": { + "methods": [ + "GetIssueModel" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "GetPhraseMatcher": { + "methods": [ + "GetPhraseMatcher" + ] + }, + "GetSettings": { + "methods": [ + "GetSettings" + ] + }, + "GetView": { + "methods": [ + "GetView" + ] + }, + "ListAnalyses": { + "methods": [ + "ListAnalyses" + ] + }, + "ListConversations": { + "methods": [ + "ListConversations" + ] + }, + "ListIssueModels": { + "methods": [ + "ListIssueModels" + ] + }, + "ListIssues": { + "methods": [ + "ListIssues" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "ListPhraseMatchers": { + "methods": [ + "ListPhraseMatchers" + ] + }, + "ListViews": { + "methods": [ + "ListViews" + ] + }, + "UndeployIssueModel": { + "methods": [ + "UndeployIssueModel" + ] + }, + "UpdateConversation": { + "methods": [ + "UpdateConversation" + ] + }, + "UpdateIssue": { + "methods": [ + "UpdateIssue" + ] + }, + "UpdateIssueModel": { + "methods": [ + "UpdateIssueModel" + ] + }, + "UpdatePhraseMatcher": { + "methods": [ + "UpdatePhraseMatcher" + ] + }, + "UpdateSettings": { + "methods": [ + "UpdateSettings" + ] + }, + "UpdateView": { + "methods": [ + "UpdateView" + ] + } + } } } } diff --git a/container/apiv1/cluster_manager_client.go b/container/apiv1/cluster_manager_client.go index c7a5a7773cdc..cc11c1b937f6 100644 --- a/container/apiv1/cluster_manager_client.go +++ b/container/apiv1/cluster_manager_client.go @@ -17,21 +17,27 @@ package container import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" containerpb "cloud.google.com/go/container/apiv1/containerpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -223,6 +229,134 @@ func defaultClusterManagerCallOptions() *ClusterManagerCallOptions { } } +func defaultClusterManagerRESTCallOptions() *ClusterManagerCallOptions { + return &ClusterManagerCallOptions{ + ListClusters: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + GetCluster: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + CreateCluster: []gax.CallOption{}, + UpdateCluster: []gax.CallOption{}, + UpdateNodePool: []gax.CallOption{}, + SetNodePoolAutoscaling: []gax.CallOption{}, + SetLoggingService: []gax.CallOption{}, + SetMonitoringService: []gax.CallOption{}, + SetAddonsConfig: []gax.CallOption{}, + SetLocations: []gax.CallOption{}, + UpdateMaster: []gax.CallOption{}, + SetMasterAuth: []gax.CallOption{}, + DeleteCluster: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + ListOperations: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + GetOperation: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + CancelOperation: []gax.CallOption{}, + GetServerConfig: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + GetJSONWebKeys: []gax.CallOption{}, + ListNodePools: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + GetNodePool: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + CreateNodePool: []gax.CallOption{}, + DeleteNodePool: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + CompleteNodePoolUpgrade: []gax.CallOption{}, + RollbackNodePoolUpgrade: []gax.CallOption{}, + SetNodePoolManagement: []gax.CallOption{}, + SetLabels: []gax.CallOption{}, + SetLegacyAbac: []gax.CallOption{}, + StartIPRotation: []gax.CallOption{}, + CompleteIPRotation: []gax.CallOption{}, + SetNodePoolSize: []gax.CallOption{}, + SetNetworkPolicy: []gax.CallOption{}, + SetMaintenancePolicy: []gax.CallOption{}, + ListUsableSubnetworks: []gax.CallOption{}, + } +} + // internalClusterManagerClient is an interface that defines the methods available from Kubernetes Engine API. type internalClusterManagerClient interface { Close() error @@ -580,6 +714,74 @@ func (c *clusterManagerGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type clusterManagerRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing ClusterManagerClient + CallOptions **ClusterManagerCallOptions +} + +// NewClusterManagerRESTClient creates a new cluster manager rest client. +// +// Google Kubernetes Engine Cluster Manager v1 +func NewClusterManagerRESTClient(ctx context.Context, opts ...option.ClientOption) (*ClusterManagerClient, error) { + clientOpts := append(defaultClusterManagerRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultClusterManagerRESTCallOptions() + c := &clusterManagerRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &ClusterManagerClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultClusterManagerRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://container.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://container.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://container.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *clusterManagerRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *clusterManagerRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *clusterManagerRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *clusterManagerGRPCClient) ListClusters(ctx context.Context, req *containerpb.ListClustersRequest, opts ...gax.CallOption) (*containerpb.ListClustersResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 20000*time.Millisecond) @@ -1311,6 +1513,2163 @@ func (c *clusterManagerGRPCClient) ListUsableSubnetworks(ctx context.Context, re return it } +// ListClusters lists all clusters owned by a project in either the specified zone or all +// zones. +func (c *clusterManagerRESTClient) ListClusters(ctx context.Context, req *containerpb.ListClustersRequest, opts ...gax.CallOption) (*containerpb.ListClustersResponse, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/clusters", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetProjectId() != "" { + params.Add("projectId", fmt.Sprintf("%v", req.GetProjectId())) + } + if req.GetZone() != "" { + params.Add("zone", fmt.Sprintf("%v", req.GetZone())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "parent", url.QueryEscape(req.GetParent()), "project_id", url.QueryEscape(req.GetProjectId()), "zone", url.QueryEscape(req.GetZone()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).ListClusters[0:len((*c.CallOptions).ListClusters):len((*c.CallOptions).ListClusters)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &containerpb.ListClustersResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetCluster gets the details of a specific cluster. +func (c *clusterManagerRESTClient) GetCluster(ctx context.Context, req *containerpb.GetClusterRequest, opts ...gax.CallOption) (*containerpb.Cluster, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetClusterId() != "" { + params.Add("clusterId", fmt.Sprintf("%v", req.GetClusterId())) + } + if req.GetProjectId() != "" { + params.Add("projectId", fmt.Sprintf("%v", req.GetProjectId())) + } + if req.GetZone() != "" { + params.Add("zone", fmt.Sprintf("%v", req.GetZone())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v&%s=%v", "name", url.QueryEscape(req.GetName()), "project_id", url.QueryEscape(req.GetProjectId()), "zone", url.QueryEscape(req.GetZone()), "cluster_id", url.QueryEscape(req.GetClusterId()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetCluster[0:len((*c.CallOptions).GetCluster):len((*c.CallOptions).GetCluster)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &containerpb.Cluster{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateCluster creates a cluster, consisting of the specified number and type of Google +// Compute Engine instances. +// +// By default, the cluster is created in the project’s +// default +// network (at https://cloud.google.com/compute/docs/networks-and-firewalls#networks). +// +// One firewall is added for the cluster. After cluster creation, +// the Kubelet creates routes for each node to allow the containers +// on that node to communicate with all other instances in the +// cluster. +// +// Finally, an entry is added to the project’s global metadata indicating +// which CIDR range the cluster is using. +func (c *clusterManagerRESTClient) CreateCluster(ctx context.Context, req *containerpb.CreateClusterRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/clusters", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "parent", url.QueryEscape(req.GetParent()), "project_id", url.QueryEscape(req.GetProjectId()), "zone", url.QueryEscape(req.GetZone()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateCluster[0:len((*c.CallOptions).CreateCluster):len((*c.CallOptions).CreateCluster)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &containerpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateCluster updates the settings of a specific cluster. +func (c *clusterManagerRESTClient) UpdateCluster(ctx context.Context, req *containerpb.UpdateClusterRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v&%s=%v", "name", url.QueryEscape(req.GetName()), "project_id", url.QueryEscape(req.GetProjectId()), "zone", url.QueryEscape(req.GetZone()), "cluster_id", url.QueryEscape(req.GetClusterId()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateCluster[0:len((*c.CallOptions).UpdateCluster):len((*c.CallOptions).UpdateCluster)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &containerpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PUT", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateNodePool updates the version and/or image type for the specified node pool. +func (c *clusterManagerRESTClient) UpdateNodePool(ctx context.Context, req *containerpb.UpdateNodePoolRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v&%s=%v&%s=%v", "name", url.QueryEscape(req.GetName()), "project_id", url.QueryEscape(req.GetProjectId()), "zone", url.QueryEscape(req.GetZone()), "cluster_id", url.QueryEscape(req.GetClusterId()), "node_pool_id", url.QueryEscape(req.GetNodePoolId()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateNodePool[0:len((*c.CallOptions).UpdateNodePool):len((*c.CallOptions).UpdateNodePool)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &containerpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PUT", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SetNodePoolAutoscaling sets the autoscaling settings for the specified node pool. +func (c *clusterManagerRESTClient) SetNodePoolAutoscaling(ctx context.Context, req *containerpb.SetNodePoolAutoscalingRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:setAutoscaling", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v&%s=%v&%s=%v", "name", url.QueryEscape(req.GetName()), "project_id", url.QueryEscape(req.GetProjectId()), "zone", url.QueryEscape(req.GetZone()), "cluster_id", url.QueryEscape(req.GetClusterId()), "node_pool_id", url.QueryEscape(req.GetNodePoolId()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetNodePoolAutoscaling[0:len((*c.CallOptions).SetNodePoolAutoscaling):len((*c.CallOptions).SetNodePoolAutoscaling)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &containerpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SetLoggingService sets the logging service for a specific cluster. +func (c *clusterManagerRESTClient) SetLoggingService(ctx context.Context, req *containerpb.SetLoggingServiceRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:setLogging", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v&%s=%v", "name", url.QueryEscape(req.GetName()), "project_id", url.QueryEscape(req.GetProjectId()), "zone", url.QueryEscape(req.GetZone()), "cluster_id", url.QueryEscape(req.GetClusterId()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetLoggingService[0:len((*c.CallOptions).SetLoggingService):len((*c.CallOptions).SetLoggingService)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &containerpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SetMonitoringService sets the monitoring service for a specific cluster. +func (c *clusterManagerRESTClient) SetMonitoringService(ctx context.Context, req *containerpb.SetMonitoringServiceRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:setMonitoring", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v&%s=%v", "name", url.QueryEscape(req.GetName()), "project_id", url.QueryEscape(req.GetProjectId()), "zone", url.QueryEscape(req.GetZone()), "cluster_id", url.QueryEscape(req.GetClusterId()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetMonitoringService[0:len((*c.CallOptions).SetMonitoringService):len((*c.CallOptions).SetMonitoringService)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &containerpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SetAddonsConfig sets the addons for a specific cluster. +func (c *clusterManagerRESTClient) SetAddonsConfig(ctx context.Context, req *containerpb.SetAddonsConfigRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:setAddons", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v&%s=%v", "name", url.QueryEscape(req.GetName()), "project_id", url.QueryEscape(req.GetProjectId()), "zone", url.QueryEscape(req.GetZone()), "cluster_id", url.QueryEscape(req.GetClusterId()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetAddonsConfig[0:len((*c.CallOptions).SetAddonsConfig):len((*c.CallOptions).SetAddonsConfig)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &containerpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SetLocations sets the locations for a specific cluster. +// Deprecated. Use +// projects.locations.clusters.update (at https://cloud.google.com/kubernetes-engine/docs/reference/rest/v1/projects.locations.clusters/update) +// instead. +// +// Deprecated: SetLocations may be removed in a future version. +func (c *clusterManagerRESTClient) SetLocations(ctx context.Context, req *containerpb.SetLocationsRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:setLocations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v&%s=%v", "name", url.QueryEscape(req.GetName()), "project_id", url.QueryEscape(req.GetProjectId()), "zone", url.QueryEscape(req.GetZone()), "cluster_id", url.QueryEscape(req.GetClusterId()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetLocations[0:len((*c.CallOptions).SetLocations):len((*c.CallOptions).SetLocations)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &containerpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateMaster updates the master for a specific cluster. +func (c *clusterManagerRESTClient) UpdateMaster(ctx context.Context, req *containerpb.UpdateMasterRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:updateMaster", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v&%s=%v", "name", url.QueryEscape(req.GetName()), "project_id", url.QueryEscape(req.GetProjectId()), "zone", url.QueryEscape(req.GetZone()), "cluster_id", url.QueryEscape(req.GetClusterId()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateMaster[0:len((*c.CallOptions).UpdateMaster):len((*c.CallOptions).UpdateMaster)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &containerpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SetMasterAuth sets master auth materials. Currently supports changing the admin password +// or a specific cluster, either via password generation or explicitly setting +// the password. +func (c *clusterManagerRESTClient) SetMasterAuth(ctx context.Context, req *containerpb.SetMasterAuthRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:setMasterAuth", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v&%s=%v", "name", url.QueryEscape(req.GetName()), "project_id", url.QueryEscape(req.GetProjectId()), "zone", url.QueryEscape(req.GetZone()), "cluster_id", url.QueryEscape(req.GetClusterId()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetMasterAuth[0:len((*c.CallOptions).SetMasterAuth):len((*c.CallOptions).SetMasterAuth)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &containerpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteCluster deletes the cluster, including the Kubernetes endpoint and all worker +// nodes. +// +// Firewalls and routes that were configured during cluster creation +// are also deleted. +// +// Other Google Compute Engine resources that might be in use by the cluster, +// such as load balancer resources, are not deleted if they weren’t present +// when the cluster was initially created. +func (c *clusterManagerRESTClient) DeleteCluster(ctx context.Context, req *containerpb.DeleteClusterRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetClusterId() != "" { + params.Add("clusterId", fmt.Sprintf("%v", req.GetClusterId())) + } + if req.GetProjectId() != "" { + params.Add("projectId", fmt.Sprintf("%v", req.GetProjectId())) + } + if req.GetZone() != "" { + params.Add("zone", fmt.Sprintf("%v", req.GetZone())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v&%s=%v", "name", url.QueryEscape(req.GetName()), "project_id", url.QueryEscape(req.GetProjectId()), "zone", url.QueryEscape(req.GetZone()), "cluster_id", url.QueryEscape(req.GetClusterId()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).DeleteCluster[0:len((*c.CallOptions).DeleteCluster):len((*c.CallOptions).DeleteCluster)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &containerpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations lists all operations in a project in a specific zone or all zones. +func (c *clusterManagerRESTClient) ListOperations(ctx context.Context, req *containerpb.ListOperationsRequest, opts ...gax.CallOption) (*containerpb.ListOperationsResponse, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/operations", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetProjectId() != "" { + params.Add("projectId", fmt.Sprintf("%v", req.GetProjectId())) + } + if req.GetZone() != "" { + params.Add("zone", fmt.Sprintf("%v", req.GetZone())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "parent", url.QueryEscape(req.GetParent()), "project_id", url.QueryEscape(req.GetProjectId()), "zone", url.QueryEscape(req.GetZone()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).ListOperations[0:len((*c.CallOptions).ListOperations):len((*c.CallOptions).ListOperations)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &containerpb.ListOperationsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetOperation gets the specified operation. +func (c *clusterManagerRESTClient) GetOperation(ctx context.Context, req *containerpb.GetOperationRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetOperationId() != "" { + params.Add("operationId", fmt.Sprintf("%v", req.GetOperationId())) + } + if req.GetProjectId() != "" { + params.Add("projectId", fmt.Sprintf("%v", req.GetProjectId())) + } + if req.GetZone() != "" { + params.Add("zone", fmt.Sprintf("%v", req.GetZone())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v&%s=%v", "name", url.QueryEscape(req.GetName()), "project_id", url.QueryEscape(req.GetProjectId()), "zone", url.QueryEscape(req.GetZone()), "operation_id", url.QueryEscape(req.GetOperationId()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &containerpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CancelOperation cancels the specified operation. +func (c *clusterManagerRESTClient) CancelOperation(ctx context.Context, req *containerpb.CancelOperationRequest, opts ...gax.CallOption) error { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v&%s=%v", "name", url.QueryEscape(req.GetName()), "project_id", url.QueryEscape(req.GetProjectId()), "zone", url.QueryEscape(req.GetZone()), "operation_id", url.QueryEscape(req.GetOperationId()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetServerConfig returns configuration info about the Google Kubernetes Engine service. +func (c *clusterManagerRESTClient) GetServerConfig(ctx context.Context, req *containerpb.GetServerConfigRequest, opts ...gax.CallOption) (*containerpb.ServerConfig, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/serverConfig", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetProjectId() != "" { + params.Add("projectId", fmt.Sprintf("%v", req.GetProjectId())) + } + if req.GetZone() != "" { + params.Add("zone", fmt.Sprintf("%v", req.GetZone())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "name", url.QueryEscape(req.GetName()), "project_id", url.QueryEscape(req.GetProjectId()), "zone", url.QueryEscape(req.GetZone()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetServerConfig[0:len((*c.CallOptions).GetServerConfig):len((*c.CallOptions).GetServerConfig)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &containerpb.ServerConfig{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetJSONWebKeys gets the public component of the cluster signing keys in +// JSON Web Key format. +// This API is not yet intended for general use, and is not available for all +// clusters. +func (c *clusterManagerRESTClient) GetJSONWebKeys(ctx context.Context, req *containerpb.GetJSONWebKeysRequest, opts ...gax.CallOption) (*containerpb.GetJSONWebKeysResponse, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/jwks", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetJSONWebKeys[0:len((*c.CallOptions).GetJSONWebKeys):len((*c.CallOptions).GetJSONWebKeys)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &containerpb.GetJSONWebKeysResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListNodePools lists the node pools for a cluster. +func (c *clusterManagerRESTClient) ListNodePools(ctx context.Context, req *containerpb.ListNodePoolsRequest, opts ...gax.CallOption) (*containerpb.ListNodePoolsResponse, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/nodePools", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetClusterId() != "" { + params.Add("clusterId", fmt.Sprintf("%v", req.GetClusterId())) + } + if req.GetProjectId() != "" { + params.Add("projectId", fmt.Sprintf("%v", req.GetProjectId())) + } + if req.GetZone() != "" { + params.Add("zone", fmt.Sprintf("%v", req.GetZone())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v&%s=%v", "parent", url.QueryEscape(req.GetParent()), "project_id", url.QueryEscape(req.GetProjectId()), "zone", url.QueryEscape(req.GetZone()), "cluster_id", url.QueryEscape(req.GetClusterId()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).ListNodePools[0:len((*c.CallOptions).ListNodePools):len((*c.CallOptions).ListNodePools)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &containerpb.ListNodePoolsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetNodePool retrieves the requested node pool. +func (c *clusterManagerRESTClient) GetNodePool(ctx context.Context, req *containerpb.GetNodePoolRequest, opts ...gax.CallOption) (*containerpb.NodePool, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetClusterId() != "" { + params.Add("clusterId", fmt.Sprintf("%v", req.GetClusterId())) + } + if req.GetNodePoolId() != "" { + params.Add("nodePoolId", fmt.Sprintf("%v", req.GetNodePoolId())) + } + if req.GetProjectId() != "" { + params.Add("projectId", fmt.Sprintf("%v", req.GetProjectId())) + } + if req.GetZone() != "" { + params.Add("zone", fmt.Sprintf("%v", req.GetZone())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v&%s=%v&%s=%v", "name", url.QueryEscape(req.GetName()), "project_id", url.QueryEscape(req.GetProjectId()), "zone", url.QueryEscape(req.GetZone()), "cluster_id", url.QueryEscape(req.GetClusterId()), "node_pool_id", url.QueryEscape(req.GetNodePoolId()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetNodePool[0:len((*c.CallOptions).GetNodePool):len((*c.CallOptions).GetNodePool)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &containerpb.NodePool{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateNodePool creates a node pool for a cluster. +func (c *clusterManagerRESTClient) CreateNodePool(ctx context.Context, req *containerpb.CreateNodePoolRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/nodePools", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v&%s=%v", "parent", url.QueryEscape(req.GetParent()), "project_id", url.QueryEscape(req.GetProjectId()), "zone", url.QueryEscape(req.GetZone()), "cluster_id", url.QueryEscape(req.GetClusterId()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateNodePool[0:len((*c.CallOptions).CreateNodePool):len((*c.CallOptions).CreateNodePool)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &containerpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteNodePool deletes a node pool from a cluster. +func (c *clusterManagerRESTClient) DeleteNodePool(ctx context.Context, req *containerpb.DeleteNodePoolRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetClusterId() != "" { + params.Add("clusterId", fmt.Sprintf("%v", req.GetClusterId())) + } + if req.GetNodePoolId() != "" { + params.Add("nodePoolId", fmt.Sprintf("%v", req.GetNodePoolId())) + } + if req.GetProjectId() != "" { + params.Add("projectId", fmt.Sprintf("%v", req.GetProjectId())) + } + if req.GetZone() != "" { + params.Add("zone", fmt.Sprintf("%v", req.GetZone())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v&%s=%v&%s=%v", "name", url.QueryEscape(req.GetName()), "project_id", url.QueryEscape(req.GetProjectId()), "zone", url.QueryEscape(req.GetZone()), "cluster_id", url.QueryEscape(req.GetClusterId()), "node_pool_id", url.QueryEscape(req.GetNodePoolId()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).DeleteNodePool[0:len((*c.CallOptions).DeleteNodePool):len((*c.CallOptions).DeleteNodePool)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &containerpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CompleteNodePoolUpgrade completeNodePoolUpgrade will signal an on-going node pool upgrade to +// complete. +func (c *clusterManagerRESTClient) CompleteNodePoolUpgrade(ctx context.Context, req *containerpb.CompleteNodePoolUpgradeRequest, opts ...gax.CallOption) error { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:completeUpgrade", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// RollbackNodePoolUpgrade rolls back a previously Aborted or Failed NodePool upgrade. +// This makes no changes if the last upgrade successfully completed. +func (c *clusterManagerRESTClient) RollbackNodePoolUpgrade(ctx context.Context, req *containerpb.RollbackNodePoolUpgradeRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:rollback", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v&%s=%v&%s=%v", "name", url.QueryEscape(req.GetName()), "project_id", url.QueryEscape(req.GetProjectId()), "zone", url.QueryEscape(req.GetZone()), "cluster_id", url.QueryEscape(req.GetClusterId()), "node_pool_id", url.QueryEscape(req.GetNodePoolId()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).RollbackNodePoolUpgrade[0:len((*c.CallOptions).RollbackNodePoolUpgrade):len((*c.CallOptions).RollbackNodePoolUpgrade)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &containerpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SetNodePoolManagement sets the NodeManagement options for a node pool. +func (c *clusterManagerRESTClient) SetNodePoolManagement(ctx context.Context, req *containerpb.SetNodePoolManagementRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:setManagement", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v&%s=%v&%s=%v", "name", url.QueryEscape(req.GetName()), "project_id", url.QueryEscape(req.GetProjectId()), "zone", url.QueryEscape(req.GetZone()), "cluster_id", url.QueryEscape(req.GetClusterId()), "node_pool_id", url.QueryEscape(req.GetNodePoolId()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetNodePoolManagement[0:len((*c.CallOptions).SetNodePoolManagement):len((*c.CallOptions).SetNodePoolManagement)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &containerpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SetLabels sets labels on a cluster. +func (c *clusterManagerRESTClient) SetLabels(ctx context.Context, req *containerpb.SetLabelsRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:setResourceLabels", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v&%s=%v", "name", url.QueryEscape(req.GetName()), "project_id", url.QueryEscape(req.GetProjectId()), "zone", url.QueryEscape(req.GetZone()), "cluster_id", url.QueryEscape(req.GetClusterId()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetLabels[0:len((*c.CallOptions).SetLabels):len((*c.CallOptions).SetLabels)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &containerpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SetLegacyAbac enables or disables the ABAC authorization mechanism on a cluster. +func (c *clusterManagerRESTClient) SetLegacyAbac(ctx context.Context, req *containerpb.SetLegacyAbacRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:setLegacyAbac", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v&%s=%v", "name", url.QueryEscape(req.GetName()), "project_id", url.QueryEscape(req.GetProjectId()), "zone", url.QueryEscape(req.GetZone()), "cluster_id", url.QueryEscape(req.GetClusterId()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetLegacyAbac[0:len((*c.CallOptions).SetLegacyAbac):len((*c.CallOptions).SetLegacyAbac)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &containerpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// StartIPRotation starts master IP rotation. +func (c *clusterManagerRESTClient) StartIPRotation(ctx context.Context, req *containerpb.StartIPRotationRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:startIpRotation", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v&%s=%v", "name", url.QueryEscape(req.GetName()), "project_id", url.QueryEscape(req.GetProjectId()), "zone", url.QueryEscape(req.GetZone()), "cluster_id", url.QueryEscape(req.GetClusterId()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).StartIPRotation[0:len((*c.CallOptions).StartIPRotation):len((*c.CallOptions).StartIPRotation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &containerpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CompleteIPRotation completes master IP rotation. +func (c *clusterManagerRESTClient) CompleteIPRotation(ctx context.Context, req *containerpb.CompleteIPRotationRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:completeIpRotation", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v&%s=%v", "name", url.QueryEscape(req.GetName()), "project_id", url.QueryEscape(req.GetProjectId()), "zone", url.QueryEscape(req.GetZone()), "cluster_id", url.QueryEscape(req.GetClusterId()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CompleteIPRotation[0:len((*c.CallOptions).CompleteIPRotation):len((*c.CallOptions).CompleteIPRotation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &containerpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SetNodePoolSize sets the size for a specific node pool. The new size will be used for all +// replicas, including future replicas created by modifying +// NodePool.locations. +func (c *clusterManagerRESTClient) SetNodePoolSize(ctx context.Context, req *containerpb.SetNodePoolSizeRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:setSize", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v&%s=%v&%s=%v", "name", url.QueryEscape(req.GetName()), "project_id", url.QueryEscape(req.GetProjectId()), "zone", url.QueryEscape(req.GetZone()), "cluster_id", url.QueryEscape(req.GetClusterId()), "node_pool_id", url.QueryEscape(req.GetNodePoolId()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetNodePoolSize[0:len((*c.CallOptions).SetNodePoolSize):len((*c.CallOptions).SetNodePoolSize)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &containerpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SetNetworkPolicy enables or disables Network Policy for a cluster. +func (c *clusterManagerRESTClient) SetNetworkPolicy(ctx context.Context, req *containerpb.SetNetworkPolicyRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:setNetworkPolicy", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v&%s=%v", "name", url.QueryEscape(req.GetName()), "project_id", url.QueryEscape(req.GetProjectId()), "zone", url.QueryEscape(req.GetZone()), "cluster_id", url.QueryEscape(req.GetClusterId()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetNetworkPolicy[0:len((*c.CallOptions).SetNetworkPolicy):len((*c.CallOptions).SetNetworkPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &containerpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SetMaintenancePolicy sets the maintenance policy for a cluster. +func (c *clusterManagerRESTClient) SetMaintenancePolicy(ctx context.Context, req *containerpb.SetMaintenancePolicyRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:setMaintenancePolicy", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v&%s=%v", "name", url.QueryEscape(req.GetName()), "project_id", url.QueryEscape(req.GetProjectId()), "zone", url.QueryEscape(req.GetZone()), "cluster_id", url.QueryEscape(req.GetClusterId()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetMaintenancePolicy[0:len((*c.CallOptions).SetMaintenancePolicy):len((*c.CallOptions).SetMaintenancePolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &containerpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListUsableSubnetworks lists subnetworks that are usable for creating clusters in a project. +func (c *clusterManagerRESTClient) ListUsableSubnetworks(ctx context.Context, req *containerpb.ListUsableSubnetworksRequest, opts ...gax.CallOption) *UsableSubnetworkIterator { + it := &UsableSubnetworkIterator{} + req = proto.Clone(req).(*containerpb.ListUsableSubnetworksRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*containerpb.UsableSubnetwork, string, error) { + resp := &containerpb.ListUsableSubnetworksResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/aggregated/usableSubnetworks", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetSubnetworks(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + // UsableSubnetworkIterator manages a stream of *containerpb.UsableSubnetwork. type UsableSubnetworkIterator struct { items []*containerpb.UsableSubnetwork diff --git a/container/apiv1/cluster_manager_client_example_test.go b/container/apiv1/cluster_manager_client_example_test.go index b8c98f78d8ce..978bb6373adb 100644 --- a/container/apiv1/cluster_manager_client_example_test.go +++ b/container/apiv1/cluster_manager_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewClusterManagerClient() { _ = c } +func ExampleNewClusterManagerRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := container.NewClusterManagerRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClusterManagerClient_ListClusters() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/container/apiv1/containerpb/cluster_service.pb.go b/container/apiv1/containerpb/cluster_service.pb.go index a6866a01c6e0..d12d147dcf40 100644 --- a/container/apiv1/containerpb/cluster_service.pb.go +++ b/container/apiv1/containerpb/cluster_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/container/v1/cluster_service.proto package containerpb @@ -2455,25 +2455,25 @@ type NodeConfig struct { // Additionally, to avoid ambiguity, keys must not conflict with any other // metadata keys for the project or be one of the reserved keys: // - // - "cluster-location" - // - "cluster-name" - // - "cluster-uid" - // - "configure-sh" - // - "containerd-configure-sh" - // - "enable-os-login" - // - "gci-ensure-gke-docker" - // - "gci-metrics-enabled" - // - "gci-update-strategy" - // - "instance-template" - // - "kube-env" - // - "startup-script" - // - "user-data" - // - "disable-address-manager" - // - "windows-startup-script-ps1" - // - "common-psm1" - // - "k8s-node-setup-psm1" - // - "install-ssh-psm1" - // - "user-profile-psm1" + // - "cluster-location" + // - "cluster-name" + // - "cluster-uid" + // - "configure-sh" + // - "containerd-configure-sh" + // - "enable-os-login" + // - "gci-ensure-gke-docker" + // - "gci-metrics-enabled" + // - "gci-update-strategy" + // - "instance-template" + // - "kube-env" + // - "startup-script" + // - "user-data" + // - "disable-address-manager" + // - "windows-startup-script-ps1" + // - "common-psm1" + // - "k8s-node-setup-psm1" + // - "install-ssh-psm1" + // - "user-profile-psm1" // // Values are free-form strings, and only have meaning as interpreted by // the image running in the instance. The only restriction placed on them is @@ -2551,6 +2551,7 @@ type NodeConfig struct { LinuxNodeConfig *LinuxNodeConfig `protobuf:"bytes,21,opt,name=linux_node_config,json=linuxNodeConfig,proto3" json:"linux_node_config,omitempty"` // Node kubelet configs. KubeletConfig *NodeKubeletConfig `protobuf:"bytes,22,opt,name=kubelet_config,json=kubeletConfig,proto3" json:"kubelet_config,omitempty"` + // // The Customer Managed Encryption Key used to encrypt the boot disk attached // to each node in the node pool. This should be of the form // projects/[KEY_PROJECT_ID]/locations/[LOCATION]/keyRings/[RING_NAME]/cryptoKeys/[KEY_NAME]. @@ -5114,9 +5115,9 @@ type Cluster struct { // // * `logging.googleapis.com/kubernetes` - The Cloud Logging // service with a Kubernetes-native resource model - // - `logging.googleapis.com` - The legacy Cloud Logging service (no longer - // available as of GKE 1.15). - // - `none` - no logs will be exported from the cluster. + // * `logging.googleapis.com` - The legacy Cloud Logging service (no longer + // available as of GKE 1.15). + // * `none` - no logs will be exported from the cluster. // // If left as an empty string,`logging.googleapis.com/kubernetes` will be // used for GKE 1.14+ or `logging.googleapis.com` for earlier versions. @@ -5126,9 +5127,9 @@ type Cluster struct { // // * "monitoring.googleapis.com/kubernetes" - The Cloud Monitoring // service with a Kubernetes-native resource model - // - `monitoring.googleapis.com` - The legacy Cloud Monitoring service (no - // longer available as of GKE 1.15). - // - `none` - No metrics will be exported from the cluster. + // * `monitoring.googleapis.com` - The legacy Cloud Monitoring service (no + // longer available as of GKE 1.15). + // * `none` - No metrics will be exported from the cluster. // // If left as an empty string,`monitoring.googleapis.com/kubernetes` will be // used for GKE 1.14+ or `monitoring.googleapis.com` for earlier versions. @@ -5988,9 +5989,9 @@ type ClusterUpdate struct { // // * "monitoring.googleapis.com/kubernetes" - The Cloud Monitoring // service with a Kubernetes-native resource model - // - `monitoring.googleapis.com` - The legacy Cloud Monitoring service (no - // longer available as of GKE 1.15). - // - `none` - No metrics will be exported from the cluster. + // * `monitoring.googleapis.com` - The legacy Cloud Monitoring service (no + // longer available as of GKE 1.15). + // * `none` - No metrics will be exported from the cluster. // // If left as an empty string,`monitoring.googleapis.com/kubernetes` will be // used for GKE 1.14+ or `monitoring.googleapis.com` for earlier versions. @@ -6043,9 +6044,9 @@ type ClusterUpdate struct { // // * `logging.googleapis.com/kubernetes` - The Cloud Logging // service with a Kubernetes-native resource model - // - `logging.googleapis.com` - The legacy Cloud Logging service (no longer - // available as of GKE 1.15). - // - `none` - no logs will be exported from the cluster. + // * `logging.googleapis.com` - The legacy Cloud Logging service (no longer + // available as of GKE 1.15). + // * `none` - no logs will be exported from the cluster. // // If left as an empty string,`logging.googleapis.com/kubernetes` will be // used for GKE 1.14+ or `logging.googleapis.com` for earlier versions. @@ -6615,14 +6616,11 @@ type OperationProgress struct { // Unset for single-stage operations. Status Operation_Status `protobuf:"varint,2,opt,name=status,proto3,enum=google.container.v1.Operation_Status" json:"status,omitempty"` // Progress metric bundle, for example: - // - // metrics: [{name: "nodes done", int_value: 15}, - // {name: "nodes total", int_value: 32}] - // + // metrics: [{name: "nodes done", int_value: 15}, + // {name: "nodes total", int_value: 32}] // or - // - // metrics: [{name: "progress", double_value: 0.56}, - // {name: "progress scale", double_value: 1.0}] + // metrics: [{name: "progress", double_value: 0.56}, + // {name: "progress scale", double_value: 1.0}] Metrics []*OperationProgress_Metric `protobuf:"bytes,3,rep,name=metrics,proto3" json:"metrics,omitempty"` // Substages of an operation or a stage. Stages []*OperationProgress `protobuf:"bytes,4,rep,name=stages,proto3" json:"stages,omitempty"` @@ -7395,9 +7393,9 @@ type SetLoggingServiceRequest struct { // // * `logging.googleapis.com/kubernetes` - The Cloud Logging // service with a Kubernetes-native resource model - // - `logging.googleapis.com` - The legacy Cloud Logging service (no longer - // available as of GKE 1.15). - // - `none` - no logs will be exported from the cluster. + // * `logging.googleapis.com` - The legacy Cloud Logging service (no longer + // available as of GKE 1.15). + // * `none` - no logs will be exported from the cluster. // // If left as an empty string,`logging.googleapis.com/kubernetes` will be // used for GKE 1.14+ or `logging.googleapis.com` for earlier versions. @@ -7506,9 +7504,9 @@ type SetMonitoringServiceRequest struct { // // * "monitoring.googleapis.com/kubernetes" - The Cloud Monitoring // service with a Kubernetes-native resource model - // - `monitoring.googleapis.com` - The legacy Cloud Monitoring service (no - // longer available as of GKE 1.15). - // - `none` - No metrics will be exported from the cluster. + // * `monitoring.googleapis.com` - The legacy Cloud Monitoring service (no + // longer available as of GKE 1.15). + // * `none` - No metrics will be exported from the cluster. // // If left as an empty string,`monitoring.googleapis.com/kubernetes` will be // used for GKE 1.14+ or `monitoring.googleapis.com` for earlier versions. @@ -9160,7 +9158,6 @@ type BlueGreenSettings struct { // The rollout policy controls the general rollout progress of blue-green. // // Types that are assignable to RolloutPolicy: - // // *BlueGreenSettings_StandardRolloutPolicy_ RolloutPolicy isBlueGreenSettings_RolloutPolicy `protobuf_oneof:"rollout_policy"` // Time needed after draining entire blue pool. After this period, blue pool @@ -9668,7 +9665,6 @@ type MaintenanceWindow struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Policy: - // // *MaintenanceWindow_DailyMaintenanceWindow // *MaintenanceWindow_RecurringWindow Policy isMaintenanceWindow_Policy `protobuf_oneof:"policy"` @@ -9764,7 +9760,6 @@ type TimeWindow struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Options: - // // *TimeWindow_MaintenanceExclusionOptions Options isTimeWindow_Options `protobuf_oneof:"options"` // The time that the window first starts. @@ -11789,7 +11784,7 @@ func (x *StatusCondition) GetCanonicalCode() code.Code { if x != nil { return x.CanonicalCode } - return code.Code_OK + return code.Code(0) } // NetworkConfig reports the relative names of network & subnetwork. @@ -14506,7 +14501,6 @@ type OperationProgress_Metric struct { // Strictly one of the values is required. // // Types that are assignable to Value: - // // *OperationProgress_Metric_IntValue // *OperationProgress_Metric_DoubleValue // *OperationProgress_Metric_StringValue @@ -14681,7 +14675,6 @@ type BlueGreenSettings_StandardRolloutPolicy struct { // Blue pool size to drain in a batch. // // Types that are assignable to UpdateBatchSize: - // // *BlueGreenSettings_StandardRolloutPolicy_BatchPercentage // *BlueGreenSettings_StandardRolloutPolicy_BatchNodeCount UpdateBatchSize isBlueGreenSettings_StandardRolloutPolicy_UpdateBatchSize `protobuf_oneof:"update_batch_size"` diff --git a/container/apiv1/doc.go b/container/apiv1/doc.go index 83acfc470e4e..9db2ddd4ee07 100644 --- a/container/apiv1/doc.go +++ b/container/apiv1/doc.go @@ -81,6 +81,8 @@ package container // import "cloud.google.com/go/container/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -169,3 +171,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/container/apiv1/gapic_metadata.json b/container/apiv1/gapic_metadata.json index dbb5c4ab80d1..5cc459f77f65 100644 --- a/container/apiv1/gapic_metadata.json +++ b/container/apiv1/gapic_metadata.json @@ -176,6 +176,176 @@ ] } } + }, + "rest": { + "libraryClient": "ClusterManagerClient", + "rpcs": { + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "CompleteIPRotation": { + "methods": [ + "CompleteIPRotation" + ] + }, + "CompleteNodePoolUpgrade": { + "methods": [ + "CompleteNodePoolUpgrade" + ] + }, + "CreateCluster": { + "methods": [ + "CreateCluster" + ] + }, + "CreateNodePool": { + "methods": [ + "CreateNodePool" + ] + }, + "DeleteCluster": { + "methods": [ + "DeleteCluster" + ] + }, + "DeleteNodePool": { + "methods": [ + "DeleteNodePool" + ] + }, + "GetCluster": { + "methods": [ + "GetCluster" + ] + }, + "GetJSONWebKeys": { + "methods": [ + "GetJSONWebKeys" + ] + }, + "GetNodePool": { + "methods": [ + "GetNodePool" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "GetServerConfig": { + "methods": [ + "GetServerConfig" + ] + }, + "ListClusters": { + "methods": [ + "ListClusters" + ] + }, + "ListNodePools": { + "methods": [ + "ListNodePools" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "ListUsableSubnetworks": { + "methods": [ + "ListUsableSubnetworks" + ] + }, + "RollbackNodePoolUpgrade": { + "methods": [ + "RollbackNodePoolUpgrade" + ] + }, + "SetAddonsConfig": { + "methods": [ + "SetAddonsConfig" + ] + }, + "SetLabels": { + "methods": [ + "SetLabels" + ] + }, + "SetLegacyAbac": { + "methods": [ + "SetLegacyAbac" + ] + }, + "SetLocations": { + "methods": [ + "SetLocations" + ] + }, + "SetLoggingService": { + "methods": [ + "SetLoggingService" + ] + }, + "SetMaintenancePolicy": { + "methods": [ + "SetMaintenancePolicy" + ] + }, + "SetMasterAuth": { + "methods": [ + "SetMasterAuth" + ] + }, + "SetMonitoringService": { + "methods": [ + "SetMonitoringService" + ] + }, + "SetNetworkPolicy": { + "methods": [ + "SetNetworkPolicy" + ] + }, + "SetNodePoolAutoscaling": { + "methods": [ + "SetNodePoolAutoscaling" + ] + }, + "SetNodePoolManagement": { + "methods": [ + "SetNodePoolManagement" + ] + }, + "SetNodePoolSize": { + "methods": [ + "SetNodePoolSize" + ] + }, + "StartIPRotation": { + "methods": [ + "StartIPRotation" + ] + }, + "UpdateCluster": { + "methods": [ + "UpdateCluster" + ] + }, + "UpdateMaster": { + "methods": [ + "UpdateMaster" + ] + }, + "UpdateNodePool": { + "methods": [ + "UpdateNodePool" + ] + } + } } } } diff --git a/containeranalysis/apiv1beta1/container_analysis_v1_beta1_client.go b/containeranalysis/apiv1beta1/container_analysis_v1_beta1_client.go index 3ce96b0969bc..15ecd388676d 100644 --- a/containeranalysis/apiv1beta1/container_analysis_v1_beta1_client.go +++ b/containeranalysis/apiv1beta1/container_analysis_v1_beta1_client.go @@ -589,6 +589,11 @@ func (c *containerAnalysisV1Beta1RESTClient) SetIamPolicy(ctx context.Context, r } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:setIamPolicy", req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) @@ -655,6 +660,11 @@ func (c *containerAnalysisV1Beta1RESTClient) GetIamPolicy(ctx context.Context, r } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:getIamPolicy", req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) @@ -720,6 +730,11 @@ func (c *containerAnalysisV1Beta1RESTClient) TestIamPermissions(ctx context.Cont } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:testIamPermissions", req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) @@ -773,6 +788,11 @@ func (c *containerAnalysisV1Beta1RESTClient) GetScanConfig(ctx context.Context, } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -840,6 +860,7 @@ func (c *containerAnalysisV1Beta1RESTClient) ListScanConfigs(ctx context.Context baseUrl.Path += fmt.Sprintf("/v1beta1/%v/scanConfigs", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) @@ -921,6 +942,11 @@ func (c *containerAnalysisV1Beta1RESTClient) UpdateScanConfig(ctx context.Contex } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) diff --git a/containeranalysis/apiv1beta1/containeranalysispb/containeranalysis.pb.go b/containeranalysis/apiv1beta1/containeranalysispb/containeranalysis.pb.go index 49005d7d79d9..26a13cdf425d 100644 --- a/containeranalysis/apiv1beta1/containeranalysispb/containeranalysis.pb.go +++ b/containeranalysis/apiv1beta1/containeranalysispb/containeranalysis.pb.go @@ -15,8 +15,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/devtools/containeranalysis/v1beta1/containeranalysis.proto package containeranalysispb diff --git a/containeranalysis/apiv1beta1/grafeas/grafeaspb/grafeas.pb.go b/containeranalysis/apiv1beta1/grafeas/grafeaspb/grafeas.pb.go index 28d681681319..4957ffa5ca48 100644 --- a/containeranalysis/apiv1beta1/grafeas/grafeaspb/grafeas.pb.go +++ b/containeranalysis/apiv1beta1/grafeas/grafeaspb/grafeas.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/devtools/containeranalysis/v1beta1/grafeas/grafeas.proto package grafeaspb @@ -80,7 +80,6 @@ type Occurrence struct { // resource. // // Types that are assignable to Details: - // // *Occurrence_Vulnerability // *Occurrence_Build // *Occurrence_DerivedImage @@ -148,7 +147,7 @@ func (x *Occurrence) GetKind() common.NoteKind { if x != nil { return x.Kind } - return common.NoteKind_NOTE_KIND_UNSPECIFIED + return common.NoteKind(0) } func (x *Occurrence) GetRemediation() string { @@ -382,7 +381,6 @@ type Note struct { // Required. Immutable. The type of analysis this note represents. // // Types that are assignable to Type: - // // *Note_Vulnerability // *Note_Build // *Note_BaseImage @@ -450,7 +448,7 @@ func (x *Note) GetKind() common.NoteKind { if x != nil { return x.Kind } - return common.NoteKind_NOTE_KIND_UNSPECIFIED + return common.NoteKind(0) } func (x *Note) GetRelatedUrl() []*common.RelatedUrl { @@ -1904,7 +1902,7 @@ func (x *VulnerabilityOccurrencesSummary_FixableTotalByDigest) GetSeverity() vul if x != nil { return x.Severity } - return vulnerability.Severity_SEVERITY_UNSPECIFIED + return vulnerability.Severity(0) } func (x *VulnerabilityOccurrencesSummary_FixableTotalByDigest) GetFixableCount() int64 { diff --git a/containeranalysis/apiv1beta1/grafeas_v1_beta1_client.go b/containeranalysis/apiv1beta1/grafeas_v1_beta1_client.go index c323ba8d95f4..7ffe0359c9cc 100644 --- a/containeranalysis/apiv1beta1/grafeas_v1_beta1_client.go +++ b/containeranalysis/apiv1beta1/grafeas_v1_beta1_client.go @@ -1027,6 +1027,11 @@ func (c *grafeasV1Beta1RESTClient) GetOccurrence(ctx context.Context, req *grafe } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1094,6 +1099,7 @@ func (c *grafeasV1Beta1RESTClient) ListOccurrences(ctx context.Context, req *gra baseUrl.Path += fmt.Sprintf("/v1beta1/%v/occurrences", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1172,6 +1178,11 @@ func (c *grafeasV1Beta1RESTClient) DeleteOccurrence(ctx context.Context, req *gr } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1214,6 +1225,11 @@ func (c *grafeasV1Beta1RESTClient) CreateOccurrence(ctx context.Context, req *gr } baseUrl.Path += fmt.Sprintf("/v1beta1/%v/occurrences", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1273,6 +1289,11 @@ func (c *grafeasV1Beta1RESTClient) BatchCreateOccurrences(ctx context.Context, r } baseUrl.Path += fmt.Sprintf("/v1beta1/%v/occurrences:batchCreate", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1334,6 +1355,7 @@ func (c *grafeasV1Beta1RESTClient) UpdateOccurrence(ctx context.Context, req *gr baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -1398,6 +1420,11 @@ func (c *grafeasV1Beta1RESTClient) GetOccurrenceNote(ctx context.Context, req *g } baseUrl.Path += fmt.Sprintf("/v1beta1/%v/notes", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1451,6 +1478,11 @@ func (c *grafeasV1Beta1RESTClient) GetNote(ctx context.Context, req *grafeaspb.G } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1518,6 +1550,7 @@ func (c *grafeasV1Beta1RESTClient) ListNotes(ctx context.Context, req *grafeaspb baseUrl.Path += fmt.Sprintf("/v1beta1/%v/notes", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1594,6 +1627,11 @@ func (c *grafeasV1Beta1RESTClient) DeleteNote(ctx context.Context, req *grafeasp } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1637,6 +1675,7 @@ func (c *grafeasV1Beta1RESTClient) CreateNote(ctx context.Context, req *grafeasp baseUrl.Path += fmt.Sprintf("/v1beta1/%v/notes", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetNoteId() != "" { params.Add("noteId", fmt.Sprintf("%v", req.GetNoteId())) } @@ -1702,6 +1741,11 @@ func (c *grafeasV1Beta1RESTClient) BatchCreateNotes(ctx context.Context, req *gr } baseUrl.Path += fmt.Sprintf("/v1beta1/%v/notes:batchCreate", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1763,6 +1807,7 @@ func (c *grafeasV1Beta1RESTClient) UpdateNote(ctx context.Context, req *grafeasp baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -1842,6 +1887,7 @@ func (c *grafeasV1Beta1RESTClient) ListNoteOccurrences(ctx context.Context, req baseUrl.Path += fmt.Sprintf("/v1beta1/%v/occurrences", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1919,6 +1965,7 @@ func (c *grafeasV1Beta1RESTClient) GetVulnerabilityOccurrencesSummary(ctx contex baseUrl.Path += fmt.Sprintf("/v1beta1/%v/occurrences:vulnerabilitySummary", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/datacatalog/apiv1/data_catalog_client.go b/datacatalog/apiv1/data_catalog_client.go index 0d9ec69395fa..0e71f95c882e 100644 --- a/datacatalog/apiv1/data_catalog_client.go +++ b/datacatalog/apiv1/data_catalog_client.go @@ -17,22 +17,28 @@ package datacatalog import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" datacatalogpb "cloud.google.com/go/datacatalog/apiv1/datacatalogpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" iampb "google.golang.org/genproto/googleapis/iam/v1" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -203,6 +209,115 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + SearchCatalog: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateEntryGroup: []gax.CallOption{}, + GetEntryGroup: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UpdateEntryGroup: []gax.CallOption{}, + DeleteEntryGroup: []gax.CallOption{}, + ListEntryGroups: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateEntry: []gax.CallOption{}, + UpdateEntry: []gax.CallOption{}, + DeleteEntry: []gax.CallOption{}, + GetEntry: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + LookupEntry: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListEntries: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ModifyEntryOverview: []gax.CallOption{}, + ModifyEntryContacts: []gax.CallOption{}, + CreateTagTemplate: []gax.CallOption{}, + GetTagTemplate: []gax.CallOption{}, + UpdateTagTemplate: []gax.CallOption{}, + DeleteTagTemplate: []gax.CallOption{}, + CreateTagTemplateField: []gax.CallOption{}, + UpdateTagTemplateField: []gax.CallOption{}, + RenameTagTemplateField: []gax.CallOption{}, + RenameTagTemplateFieldEnumValue: []gax.CallOption{}, + DeleteTagTemplateField: []gax.CallOption{}, + CreateTag: []gax.CallOption{}, + UpdateTag: []gax.CallOption{}, + DeleteTag: []gax.CallOption{}, + ListTags: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + StarEntry: []gax.CallOption{}, + UnstarEntry: []gax.CallOption{}, + SetIamPolicy: []gax.CallOption{}, + GetIamPolicy: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + TestIamPermissions: []gax.CallOption{}, + } +} + // internalClient is an interface that defines the methods available from Google Cloud Data Catalog API. type internalClient interface { Close() error @@ -720,6 +835,75 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new data catalog rest client. +// +// Data Catalog API service allows you to discover, understand, and manage +// your data. +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://datacatalog.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://datacatalog.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://datacatalog.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) SearchCatalog(ctx context.Context, req *datacatalogpb.SearchCatalogRequest, opts ...gax.CallOption) *SearchCatalogResultIterator { ctx = insertMetadata(ctx, c.xGoogMetadata) opts = append((*c.CallOptions).SearchCatalog[0:len((*c.CallOptions).SearchCatalog):len((*c.CallOptions).SearchCatalog)], opts...) @@ -1492,6 +1676,2281 @@ func (c *gRPCClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamP return resp, nil } +// SearchCatalog searches Data Catalog for multiple resources like entries and tags that +// match a query. +// +// This is a [Custom Method] +// (https://cloud.google.com/apis/design/custom_methods (at https://cloud.google.com/apis/design/custom_methods)) that doesn’t return +// all information on a resource, only its ID and high level fields. To get +// more information, you can subsequently call specific get methods. +// +// Note: Data Catalog search queries don’t guarantee full recall. Results +// that match your query might not be returned, even in subsequent +// result pages. Additionally, returned (and not returned) results can vary +// if you repeat search queries. +// +// For more information, see [Data Catalog search syntax] +// (https://cloud.google.com/data-catalog/docs/how-to/search-reference (at https://cloud.google.com/data-catalog/docs/how-to/search-reference)). +func (c *restClient) SearchCatalog(ctx context.Context, req *datacatalogpb.SearchCatalogRequest, opts ...gax.CallOption) *SearchCatalogResultIterator { + it := &SearchCatalogResultIterator{} + req = proto.Clone(req).(*datacatalogpb.SearchCatalogRequest) + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*datacatalogpb.SearchCatalogResult, string, error) { + resp := &datacatalogpb.SearchCatalogResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, "", err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/catalog:search") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetResults(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CreateEntryGroup creates an entry group. +// +// An entry group contains logically related entries together with Cloud +// Identity and Access Management (at /data-catalog/docs/concepts/iam) policies. +// These policies specify users who can create, edit, and view entries +// within entry groups. +// +// Data Catalog automatically creates entry groups with names that start with +// the @ symbol for the following resources: +// +// BigQuery entries (@bigquery) +// +// Pub/Sub topics (@pubsub) +// +// Dataproc Metastore services (@dataproc_metastore_{SERVICE_NAME_HASH}) +// +// You can create your own entry groups for Cloud Storage fileset entries +// and custom entries together with the corresponding IAM policies. +// User-created entry groups can’t contain the @ symbol, it is reserved +// for automatically created groups. +// +// Entry groups, like entries, can be searched. +// +// A maximum of 10,000 entry groups may be created per organization across all +// locations. +// +// You must enable the Data Catalog API in the project identified by +// the parent parameter. For more information, see Data Catalog resource +// project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project). +func (c *restClient) CreateEntryGroup(ctx context.Context, req *datacatalogpb.CreateEntryGroupRequest, opts ...gax.CallOption) (*datacatalogpb.EntryGroup, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetEntryGroup() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/entryGroups", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("entryGroupId", fmt.Sprintf("%v", req.GetEntryGroupId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateEntryGroup[0:len((*c.CallOptions).CreateEntryGroup):len((*c.CallOptions).CreateEntryGroup)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &datacatalogpb.EntryGroup{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetEntryGroup gets an entry group. +func (c *restClient) GetEntryGroup(ctx context.Context, req *datacatalogpb.GetEntryGroupRequest, opts ...gax.CallOption) (*datacatalogpb.EntryGroup, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetReadMask() != nil { + readMask, err := protojson.Marshal(req.GetReadMask()) + if err != nil { + return nil, err + } + params.Add("readMask", string(readMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetEntryGroup[0:len((*c.CallOptions).GetEntryGroup):len((*c.CallOptions).GetEntryGroup)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &datacatalogpb.EntryGroup{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateEntryGroup updates an entry group. +// +// You must enable the Data Catalog API in the project identified by +// the entry_group.name parameter. For more information, see Data Catalog +// resource +// project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project). +func (c *restClient) UpdateEntryGroup(ctx context.Context, req *datacatalogpb.UpdateEntryGroupRequest, opts ...gax.CallOption) (*datacatalogpb.EntryGroup, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetEntryGroup() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetEntryGroup().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "entry_group.name", url.QueryEscape(req.GetEntryGroup().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateEntryGroup[0:len((*c.CallOptions).UpdateEntryGroup):len((*c.CallOptions).UpdateEntryGroup)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &datacatalogpb.EntryGroup{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteEntryGroup deletes an entry group. +// +// You must enable the Data Catalog API in the project +// identified by the name parameter. For more information, see Data Catalog +// resource +// project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project). +func (c *restClient) DeleteEntryGroup(ctx context.Context, req *datacatalogpb.DeleteEntryGroupRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetForce() { + params.Add("force", fmt.Sprintf("%v", req.GetForce())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// ListEntryGroups lists entry groups. +func (c *restClient) ListEntryGroups(ctx context.Context, req *datacatalogpb.ListEntryGroupsRequest, opts ...gax.CallOption) *EntryGroupIterator { + it := &EntryGroupIterator{} + req = proto.Clone(req).(*datacatalogpb.ListEntryGroupsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*datacatalogpb.EntryGroup, string, error) { + resp := &datacatalogpb.ListEntryGroupsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/entryGroups", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetEntryGroups(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CreateEntry creates an entry. +// +// You can create entries only with ‘FILESET’, ‘CLUSTER’, ‘DATA_STREAM’, +// or custom types. Data Catalog automatically creates entries with other +// types during metadata ingestion from integrated systems. +// +// You must enable the Data Catalog API in the project identified by +// the parent parameter. For more information, see Data Catalog resource +// project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project). +// +// An entry group can have a maximum of 100,000 entries. +func (c *restClient) CreateEntry(ctx context.Context, req *datacatalogpb.CreateEntryRequest, opts ...gax.CallOption) (*datacatalogpb.Entry, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetEntry() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/entries", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("entryId", fmt.Sprintf("%v", req.GetEntryId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateEntry[0:len((*c.CallOptions).CreateEntry):len((*c.CallOptions).CreateEntry)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &datacatalogpb.Entry{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateEntry updates an existing entry. +// +// You must enable the Data Catalog API in the project identified by +// the entry.name parameter. For more information, see Data Catalog +// resource +// project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project). +func (c *restClient) UpdateEntry(ctx context.Context, req *datacatalogpb.UpdateEntryRequest, opts ...gax.CallOption) (*datacatalogpb.Entry, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetEntry() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetEntry().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "entry.name", url.QueryEscape(req.GetEntry().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateEntry[0:len((*c.CallOptions).UpdateEntry):len((*c.CallOptions).UpdateEntry)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &datacatalogpb.Entry{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteEntry deletes an existing entry. +// +// You can delete only the entries created by the +// CreateEntry +// method. +// +// You must enable the Data Catalog API in the project identified by +// the name parameter. For more information, see Data Catalog +// resource +// project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project). +func (c *restClient) DeleteEntry(ctx context.Context, req *datacatalogpb.DeleteEntryRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetEntry gets an entry. +func (c *restClient) GetEntry(ctx context.Context, req *datacatalogpb.GetEntryRequest, opts ...gax.CallOption) (*datacatalogpb.Entry, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetEntry[0:len((*c.CallOptions).GetEntry):len((*c.CallOptions).GetEntry)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &datacatalogpb.Entry{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// LookupEntry gets an entry by its target resource name. +// +// The resource name comes from the source Google Cloud Platform service. +func (c *restClient) LookupEntry(ctx context.Context, req *datacatalogpb.LookupEntryRequest, opts ...gax.CallOption) (*datacatalogpb.Entry, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/entries:lookup") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFullyQualifiedName() != "" { + params.Add("fullyQualifiedName", fmt.Sprintf("%v", req.GetFullyQualifiedName())) + } + if req.GetLinkedResource() != "" { + params.Add("linkedResource", fmt.Sprintf("%v", req.GetLinkedResource())) + } + if req.GetSqlResource() != "" { + params.Add("sqlResource", fmt.Sprintf("%v", req.GetSqlResource())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).LookupEntry[0:len((*c.CallOptions).LookupEntry):len((*c.CallOptions).LookupEntry)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &datacatalogpb.Entry{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListEntries lists entries. +// +// Note: Currently, this method can list only custom entries. +// To get a list of both custom and automatically created entries, use +// SearchCatalog. +func (c *restClient) ListEntries(ctx context.Context, req *datacatalogpb.ListEntriesRequest, opts ...gax.CallOption) *EntryIterator { + it := &EntryIterator{} + req = proto.Clone(req).(*datacatalogpb.ListEntriesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*datacatalogpb.Entry, string, error) { + resp := &datacatalogpb.ListEntriesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/entries", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + if req.GetReadMask() != nil { + readMask, err := protojson.Marshal(req.GetReadMask()) + if err != nil { + return nil, "", err + } + params.Add("readMask", string(readMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetEntries(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// ModifyEntryOverview modifies entry overview, part of the business context of an +// Entry. +// +// To call this method, you must have the datacatalog.entries.updateOverview +// IAM permission on the corresponding project. +func (c *restClient) ModifyEntryOverview(ctx context.Context, req *datacatalogpb.ModifyEntryOverviewRequest, opts ...gax.CallOption) (*datacatalogpb.EntryOverview, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:modifyEntryOverview", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).ModifyEntryOverview[0:len((*c.CallOptions).ModifyEntryOverview):len((*c.CallOptions).ModifyEntryOverview)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &datacatalogpb.EntryOverview{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ModifyEntryContacts modifies contacts, part of the business context of an +// Entry. +// +// To call this method, you must have the datacatalog.entries.updateContacts +// IAM permission on the corresponding project. +func (c *restClient) ModifyEntryContacts(ctx context.Context, req *datacatalogpb.ModifyEntryContactsRequest, opts ...gax.CallOption) (*datacatalogpb.Contacts, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:modifyEntryContacts", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).ModifyEntryContacts[0:len((*c.CallOptions).ModifyEntryContacts):len((*c.CallOptions).ModifyEntryContacts)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &datacatalogpb.Contacts{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateTagTemplate creates a tag template. +// +// You must enable the Data Catalog API in the project identified by the +// parent parameter. +// For more information, see [Data Catalog resource project] +// (https://cloud.google.com/data-catalog/docs/concepts/resource-project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project)). +func (c *restClient) CreateTagTemplate(ctx context.Context, req *datacatalogpb.CreateTagTemplateRequest, opts ...gax.CallOption) (*datacatalogpb.TagTemplate, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetTagTemplate() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/tagTemplates", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("tagTemplateId", fmt.Sprintf("%v", req.GetTagTemplateId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateTagTemplate[0:len((*c.CallOptions).CreateTagTemplate):len((*c.CallOptions).CreateTagTemplate)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &datacatalogpb.TagTemplate{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetTagTemplate gets a tag template. +func (c *restClient) GetTagTemplate(ctx context.Context, req *datacatalogpb.GetTagTemplateRequest, opts ...gax.CallOption) (*datacatalogpb.TagTemplate, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetTagTemplate[0:len((*c.CallOptions).GetTagTemplate):len((*c.CallOptions).GetTagTemplate)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &datacatalogpb.TagTemplate{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateTagTemplate updates a tag template. +// +// You can’t update template fields with this method. These fields are +// separate resources with their own create, update, and delete methods. +// +// You must enable the Data Catalog API in the project identified by +// the tag_template.name parameter. For more information, see Data Catalog +// resource +// project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project). +func (c *restClient) UpdateTagTemplate(ctx context.Context, req *datacatalogpb.UpdateTagTemplateRequest, opts ...gax.CallOption) (*datacatalogpb.TagTemplate, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetTagTemplate() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetTagTemplate().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "tag_template.name", url.QueryEscape(req.GetTagTemplate().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateTagTemplate[0:len((*c.CallOptions).UpdateTagTemplate):len((*c.CallOptions).UpdateTagTemplate)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &datacatalogpb.TagTemplate{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteTagTemplate deletes a tag template and all tags that use it. +// +// You must enable the Data Catalog API in the project identified by +// the name parameter. For more information, see Data Catalog resource +// project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project). +func (c *restClient) DeleteTagTemplate(ctx context.Context, req *datacatalogpb.DeleteTagTemplateRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("force", fmt.Sprintf("%v", req.GetForce())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// CreateTagTemplateField creates a field in a tag template. +// +// You must enable the Data Catalog API in the project identified by +// the parent parameter. For more information, see Data Catalog resource +// project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project). +func (c *restClient) CreateTagTemplateField(ctx context.Context, req *datacatalogpb.CreateTagTemplateFieldRequest, opts ...gax.CallOption) (*datacatalogpb.TagTemplateField, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetTagTemplateField() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/fields", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("tagTemplateFieldId", fmt.Sprintf("%v", req.GetTagTemplateFieldId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateTagTemplateField[0:len((*c.CallOptions).CreateTagTemplateField):len((*c.CallOptions).CreateTagTemplateField)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &datacatalogpb.TagTemplateField{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateTagTemplateField updates a field in a tag template. +// +// You can’t update the field type with this method. +// +// You must enable the Data Catalog API in the project +// identified by the name parameter. For more information, see Data Catalog +// resource +// project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project). +func (c *restClient) UpdateTagTemplateField(ctx context.Context, req *datacatalogpb.UpdateTagTemplateFieldRequest, opts ...gax.CallOption) (*datacatalogpb.TagTemplateField, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetTagTemplateField() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateTagTemplateField[0:len((*c.CallOptions).UpdateTagTemplateField):len((*c.CallOptions).UpdateTagTemplateField)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &datacatalogpb.TagTemplateField{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// RenameTagTemplateField renames a field in a tag template. +// +// You must enable the Data Catalog API in the project identified by the +// name parameter. For more information, see [Data Catalog resource project] +// (https://cloud.google.com/data-catalog/docs/concepts/resource-project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project)). +func (c *restClient) RenameTagTemplateField(ctx context.Context, req *datacatalogpb.RenameTagTemplateFieldRequest, opts ...gax.CallOption) (*datacatalogpb.TagTemplateField, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:rename", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).RenameTagTemplateField[0:len((*c.CallOptions).RenameTagTemplateField):len((*c.CallOptions).RenameTagTemplateField)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &datacatalogpb.TagTemplateField{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// RenameTagTemplateFieldEnumValue renames an enum value in a tag template. +// +// Within a single enum field, enum values must be unique. +func (c *restClient) RenameTagTemplateFieldEnumValue(ctx context.Context, req *datacatalogpb.RenameTagTemplateFieldEnumValueRequest, opts ...gax.CallOption) (*datacatalogpb.TagTemplateField, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:rename", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).RenameTagTemplateFieldEnumValue[0:len((*c.CallOptions).RenameTagTemplateFieldEnumValue):len((*c.CallOptions).RenameTagTemplateFieldEnumValue)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &datacatalogpb.TagTemplateField{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteTagTemplateField deletes a field in a tag template and all uses of this field from the tags +// based on this template. +// +// You must enable the Data Catalog API in the project identified by +// the name parameter. For more information, see Data Catalog resource +// project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project). +func (c *restClient) DeleteTagTemplateField(ctx context.Context, req *datacatalogpb.DeleteTagTemplateFieldRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("force", fmt.Sprintf("%v", req.GetForce())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// CreateTag creates a tag and assigns it to: +// +// An Entry if the method name is +// projects.locations.entryGroups.entries.tags.create. +// +// Or EntryGroupif the method +// name is projects.locations.entryGroups.tags.create. +// +// Note: The project identified by the parent parameter for the [tag] +// (https://cloud.google.com/data-catalog/docs/reference/rest/v1/projects.locations.entryGroups.entries.tags/create#path-parameters (at https://cloud.google.com/data-catalog/docs/reference/rest/v1/projects.locations.entryGroups.entries.tags/create#path-parameters)) +// and the [tag template] +// (https://cloud.google.com/data-catalog/docs/reference/rest/v1/projects.locations.tagTemplates/create#path-parameters (at https://cloud.google.com/data-catalog/docs/reference/rest/v1/projects.locations.tagTemplates/create#path-parameters)) +// used to create the tag must be in the same organization. +func (c *restClient) CreateTag(ctx context.Context, req *datacatalogpb.CreateTagRequest, opts ...gax.CallOption) (*datacatalogpb.Tag, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetTag() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/tags", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateTag[0:len((*c.CallOptions).CreateTag):len((*c.CallOptions).CreateTag)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &datacatalogpb.Tag{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateTag updates an existing tag. +func (c *restClient) UpdateTag(ctx context.Context, req *datacatalogpb.UpdateTagRequest, opts ...gax.CallOption) (*datacatalogpb.Tag, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetTag() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetTag().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "tag.name", url.QueryEscape(req.GetTag().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateTag[0:len((*c.CallOptions).UpdateTag):len((*c.CallOptions).UpdateTag)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &datacatalogpb.Tag{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteTag deletes a tag. +func (c *restClient) DeleteTag(ctx context.Context, req *datacatalogpb.DeleteTagRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// ListTags lists tags assigned to an Entry. +// The columns in the response are +// lowercased. +func (c *restClient) ListTags(ctx context.Context, req *datacatalogpb.ListTagsRequest, opts ...gax.CallOption) *TagIterator { + it := &TagIterator{} + req = proto.Clone(req).(*datacatalogpb.ListTagsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*datacatalogpb.Tag, string, error) { + resp := &datacatalogpb.ListTagsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/tags", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetTags(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// StarEntry marks an Entry as starred by +// the current user. Starring information is private to each user. +func (c *restClient) StarEntry(ctx context.Context, req *datacatalogpb.StarEntryRequest, opts ...gax.CallOption) (*datacatalogpb.StarEntryResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:star", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).StarEntry[0:len((*c.CallOptions).StarEntry):len((*c.CallOptions).StarEntry)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &datacatalogpb.StarEntryResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UnstarEntry marks an Entry as NOT starred by +// the current user. Starring information is private to each user. +func (c *restClient) UnstarEntry(ctx context.Context, req *datacatalogpb.UnstarEntryRequest, opts ...gax.CallOption) (*datacatalogpb.UnstarEntryResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:unstar", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UnstarEntry[0:len((*c.CallOptions).UnstarEntry):len((*c.CallOptions).UnstarEntry)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &datacatalogpb.UnstarEntryResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SetIamPolicy sets an access control policy for a resource. Replaces any existing +// policy. +// +// Supported resources are: +// +// Tag templates +// +// Entry groups +// +// Note: This method sets policies only within Data Catalog and can’t be +// used to manage policies in BigQuery, Pub/Sub, Dataproc Metastore, and any +// external Google Cloud Platform resources synced with the Data Catalog. +// +// To call this method, you must have the following Google IAM permissions: +// +// datacatalog.tagTemplates.setIamPolicy to set policies on tag +// templates. +// +// datacatalog.entryGroups.setIamPolicy to set policies on entry groups. +func (c *restClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:setIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetIamPolicy gets the access control policy for a resource. +// +// May return: +// +// ANOT_FOUND error if the resource doesn’t exist or you don’t have the +// permission to view it. +// +// An empty policy if the resource exists but doesn’t have a set policy. +// +// Supported resources are: +// +// Tag templates +// +// Entry groups +// +// Note: This method doesn’t get policies from Google Cloud Platform +// resources ingested into Data Catalog. +// +// To call this method, you must have the following Google IAM permissions: +// +// datacatalog.tagTemplates.getIamPolicy to get policies on tag +// templates. +// +// datacatalog.entryGroups.getIamPolicy to get policies on entry groups. +func (c *restClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:getIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// TestIamPermissions gets your permissions on a resource. +// +// Returns an empty set of permissions if the resource doesn’t exist. +// +// Supported resources are: +// +// Tag templates +// +// Entry groups +// +// Note: This method gets policies only within Data Catalog and can’t be +// used to get policies from BigQuery, Pub/Sub, Dataproc Metastore, and any +// external Google Cloud Platform resources ingested into Data Catalog. +// +// No Google IAM permissions are required to call this method. +func (c *restClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:testIamPermissions", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.TestIamPermissionsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + // EntryGroupIterator manages a stream of *datacatalogpb.EntryGroup. type EntryGroupIterator struct { items []*datacatalogpb.EntryGroup diff --git a/datacatalog/apiv1/data_catalog_client_example_test.go b/datacatalog/apiv1/data_catalog_client_example_test.go index e9b2efea9fda..f52239d50c29 100644 --- a/datacatalog/apiv1/data_catalog_client_example_test.go +++ b/datacatalog/apiv1/data_catalog_client_example_test.go @@ -42,6 +42,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := datacatalog.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_SearchCatalog() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/datacatalog/apiv1/datacatalogpb/bigquery.pb.go b/datacatalog/apiv1/datacatalogpb/bigquery.pb.go index 63d8a988d0d1..00ad7745df59 100644 --- a/datacatalog/apiv1/datacatalogpb/bigquery.pb.go +++ b/datacatalog/apiv1/datacatalogpb/bigquery.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/datacatalog/v1/bigquery.proto package datacatalogpb @@ -147,7 +147,6 @@ type BigQueryConnectionSpec struct { // The type of the BigQuery connection. ConnectionType BigQueryConnectionSpec_ConnectionType `protobuf:"varint,1,opt,name=connection_type,json=connectionType,proto3,enum=google.cloud.datacatalog.v1.BigQueryConnectionSpec_ConnectionType" json:"connection_type,omitempty"` // Types that are assignable to ConnectionSpec: - // // *BigQueryConnectionSpec_CloudSql ConnectionSpec isBigQueryConnectionSpec_ConnectionSpec `protobuf_oneof:"connection_spec"` // True if there are credentials attached to the BigQuery connection; false diff --git a/datacatalog/apiv1/datacatalogpb/common.pb.go b/datacatalog/apiv1/datacatalogpb/common.pb.go index 3e2007783d88..afa1f4c75282 100644 --- a/datacatalog/apiv1/datacatalogpb/common.pb.go +++ b/datacatalog/apiv1/datacatalogpb/common.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/datacatalog/v1/common.proto package datacatalogpb diff --git a/datacatalog/apiv1/datacatalogpb/data_source.pb.go b/datacatalog/apiv1/datacatalogpb/data_source.pb.go index 5f837b6d348d..b6a0a4916c15 100644 --- a/datacatalog/apiv1/datacatalogpb/data_source.pb.go +++ b/datacatalog/apiv1/datacatalogpb/data_source.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/datacatalog/v1/data_source.proto package datacatalogpb @@ -104,7 +104,6 @@ type DataSource struct { // Output only. Data Catalog entry name, if applicable. SourceEntry string `protobuf:"bytes,3,opt,name=source_entry,json=sourceEntry,proto3" json:"source_entry,omitempty"` // Types that are assignable to Properties: - // // *DataSource_StorageProperties Properties isDataSource_Properties `protobuf_oneof:"properties"` } @@ -197,22 +196,22 @@ type StorageProperties struct { // // Examples of a valid `file_pattern`: // - // - `gs://bucket_name/dir/*`: matches all files in the `bucket_name/dir` - // directory - // - `gs://bucket_name/dir/**`: matches all files in the `bucket_name/dir` - // and all subdirectories recursively - // - `gs://bucket_name/file*`: matches files prefixed by `file` in - // `bucket_name` - // - `gs://bucket_name/??.txt`: matches files with two characters followed by - // `.txt` in `bucket_name` - // - `gs://bucket_name/[aeiou].txt`: matches files that contain a single - // vowel character followed by `.txt` in - // `bucket_name` - // - `gs://bucket_name/[a-m].txt`: matches files that contain `a`, `b`, ... - // or `m` followed by `.txt` in `bucket_name` - // - `gs://bucket_name/a/*/b`: matches all files in `bucket_name` that match - // the `a/*/b` pattern, such as `a/c/b`, `a/d/b` - // - `gs://another_bucket/a.txt`: matches `gs://another_bucket/a.txt` + // * `gs://bucket_name/dir/*`: matches all files in the `bucket_name/dir` + // directory + // * `gs://bucket_name/dir/**`: matches all files in the `bucket_name/dir` + // and all subdirectories recursively + // * `gs://bucket_name/file*`: matches files prefixed by `file` in + // `bucket_name` + // * `gs://bucket_name/??.txt`: matches files with two characters followed by + // `.txt` in `bucket_name` + // * `gs://bucket_name/[aeiou].txt`: matches files that contain a single + // vowel character followed by `.txt` in + // `bucket_name` + // * `gs://bucket_name/[a-m].txt`: matches files that contain `a`, `b`, ... + // or `m` followed by `.txt` in `bucket_name` + // * `gs://bucket_name/a/*/b`: matches all files in `bucket_name` that match + // the `a/*/b` pattern, such as `a/c/b`, `a/d/b` + // * `gs://another_bucket/a.txt`: matches `gs://another_bucket/a.txt` FilePattern []string `protobuf:"bytes,1,rep,name=file_pattern,json=filePattern,proto3" json:"file_pattern,omitempty"` // File type in MIME format, for example, `text/plain`. FileType string `protobuf:"bytes,2,opt,name=file_type,json=fileType,proto3" json:"file_type,omitempty"` diff --git a/datacatalog/apiv1/datacatalogpb/datacatalog.pb.go b/datacatalog/apiv1/datacatalogpb/datacatalog.pb.go index bd32f489e123..b856c5b84268 100644 --- a/datacatalog/apiv1/datacatalogpb/datacatalog.pb.go +++ b/datacatalog/apiv1/datacatalogpb/datacatalog.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/datacatalog/v1/datacatalog.proto package datacatalogpb @@ -1159,7 +1159,6 @@ type LookupEntryRequest struct { // Google Cloud Platform resource. // // Types that are assignable to TargetName: - // // *LookupEntryRequest_LinkedResource // *LookupEntryRequest_SqlResource // *LookupEntryRequest_FullyQualifiedName @@ -1237,8 +1236,8 @@ type LookupEntryRequest_LinkedResource struct { // // Full names are case-sensitive. For example: // - // - `//bigquery.googleapis.com/projects/{PROJECT_ID}/datasets/{DATASET_ID}/tables/{TABLE_ID}` - // - `//pubsub.googleapis.com/projects/{PROJECT_ID}/topics/{TOPIC_ID}` + // * `//bigquery.googleapis.com/projects/{PROJECT_ID}/datasets/{DATASET_ID}/tables/{TABLE_ID}` + // * `//pubsub.googleapis.com/projects/{PROJECT_ID}/topics/{TOPIC_ID}` LinkedResource string `protobuf:"bytes,1,opt,name=linked_resource,json=linkedResource,proto3,oneof"` } @@ -1248,7 +1247,7 @@ type LookupEntryRequest_SqlResource struct { // Examples: // // * `pubsub.topic.{PROJECT_ID}.{TOPIC_ID}` - // * `pubsub.topic.{PROJECT_ID}.`\“{TOPIC.ID.SEPARATED.WITH.DOTS}`\` + // * `pubsub.topic.{PROJECT_ID}.`\``{TOPIC.ID.SEPARATED.WITH.DOTS}`\` // * `bigquery.table.{PROJECT_ID}.{DATASET_ID}.{TABLE_ID}` // * `bigquery.dataset.{PROJECT_ID}.{DATASET_ID}` // * `datacatalog.entry.{PROJECT_ID}.{LOCATION_ID}.{ENTRY_GROUP_ID}.{ENTRY_ID}` @@ -1266,11 +1265,11 @@ type LookupEntryRequest_FullyQualifiedName struct { // // * For non-regionalized resources: // - // `{SYSTEM}:{PROJECT}.{PATH_TO_RESOURCE_SEPARATED_WITH_DOTS}` + // `{SYSTEM}:{PROJECT}.{PATH_TO_RESOURCE_SEPARATED_WITH_DOTS}` // // * For regionalized resources: // - // `{SYSTEM}:{PROJECT}.{LOCATION_ID}.{PATH_TO_RESOURCE_SEPARATED_WITH_DOTS}` + // `{SYSTEM}:{PROJECT}.{LOCATION_ID}.{PATH_TO_RESOURCE_SEPARATED_WITH_DOTS}` // // Example for a DPMS table: // @@ -1327,15 +1326,17 @@ type Entry struct { // representing resources from synced systems. Settable only during creation // and read-only afterwards. Can be used for search and lookup of the entries. // + // + // // FQNs take two forms: // // * For non-regionalized resources: // - // `{SYSTEM}:{PROJECT}.{PATH_TO_RESOURCE_SEPARATED_WITH_DOTS}` + // `{SYSTEM}:{PROJECT}.{PATH_TO_RESOURCE_SEPARATED_WITH_DOTS}` // // * For regionalized resources: // - // `{SYSTEM}:{PROJECT}.{LOCATION_ID}.{PATH_TO_RESOURCE_SEPARATED_WITH_DOTS}` + // `{SYSTEM}:{PROJECT}.{LOCATION_ID}.{PATH_TO_RESOURCE_SEPARATED_WITH_DOTS}` // // Example for a DPMS table: // @@ -1344,21 +1345,18 @@ type Entry struct { // Required. Entry type. // // Types that are assignable to EntryType: - // // *Entry_Type // *Entry_UserSpecifiedType EntryType isEntry_EntryType `protobuf_oneof:"entry_type"` // The source system of the entry. // // Types that are assignable to System: - // // *Entry_IntegratedSystem // *Entry_UserSpecifiedSystem System isEntry_System `protobuf_oneof:"system"` // Type specification. // // Types that are assignable to TypeSpec: - // // *Entry_GcsFilesetSpec // *Entry_BigqueryTableSpec // *Entry_BigqueryDateShardedSpec @@ -1371,7 +1369,6 @@ type Entry struct { // of the legacy `type_spec`. // // Types that are assignable to Spec: - // // *Entry_DatabaseTableSpec // *Entry_DataSourceConnectionSpec // *Entry_RoutineSpec @@ -1955,7 +1952,6 @@ type RoutineSpec struct { // Contains fields specific to the source system. // // Types that are assignable to SystemSpec: - // // *RoutineSpec_BigqueryRoutineSpec SystemSpec isRoutineSpec_SystemSpec `protobuf_oneof:"system_spec"` } @@ -6049,10 +6045,10 @@ type DataCatalogClient interface { DeleteTagTemplateField(ctx context.Context, in *DeleteTagTemplateFieldRequest, opts ...grpc.CallOption) (*emptypb.Empty, error) // Creates a tag and assigns it to: // - // - An [Entry][google.cloud.datacatalog.v1.Entry] if the method name is - // `projects.locations.entryGroups.entries.tags.create`. - // - Or [EntryGroup][google.cloud.datacatalog.v1.EntryGroup]if the method - // name is `projects.locations.entryGroups.tags.create`. + // * An [Entry][google.cloud.datacatalog.v1.Entry] if the method name is + // `projects.locations.entryGroups.entries.tags.create`. + // * Or [EntryGroup][google.cloud.datacatalog.v1.EntryGroup]if the method + // name is `projects.locations.entryGroups.tags.create`. // // Note: The project identified by the `parent` parameter for the [tag] // (https://cloud.google.com/data-catalog/docs/reference/rest/v1/projects.locations.entryGroups.entries.tags/create#path-parameters) @@ -6088,17 +6084,17 @@ type DataCatalogClient interface { // // To call this method, you must have the following Google IAM permissions: // - // - `datacatalog.tagTemplates.setIamPolicy` to set policies on tag - // templates. - // - `datacatalog.entryGroups.setIamPolicy` to set policies on entry groups. + // - `datacatalog.tagTemplates.setIamPolicy` to set policies on tag + // templates. + // - `datacatalog.entryGroups.setIamPolicy` to set policies on entry groups. SetIamPolicy(ctx context.Context, in *v1.SetIamPolicyRequest, opts ...grpc.CallOption) (*v1.Policy, error) // Gets the access control policy for a resource. // // May return: // - // - A`NOT_FOUND` error if the resource doesn't exist or you don't have the - // permission to view it. - // - An empty policy if the resource exists but doesn't have a set policy. + // * A`NOT_FOUND` error if the resource doesn't exist or you don't have the + // permission to view it. + // * An empty policy if the resource exists but doesn't have a set policy. // // Supported resources are: // @@ -6110,9 +6106,9 @@ type DataCatalogClient interface { // // To call this method, you must have the following Google IAM permissions: // - // - `datacatalog.tagTemplates.getIamPolicy` to get policies on tag - // templates. - // - `datacatalog.entryGroups.getIamPolicy` to get policies on entry groups. + // - `datacatalog.tagTemplates.getIamPolicy` to get policies on tag + // templates. + // - `datacatalog.entryGroups.getIamPolicy` to get policies on entry groups. GetIamPolicy(ctx context.Context, in *v1.GetIamPolicyRequest, opts ...grpc.CallOption) (*v1.Policy, error) // Gets your permissions on a resource. // @@ -6604,10 +6600,10 @@ type DataCatalogServer interface { DeleteTagTemplateField(context.Context, *DeleteTagTemplateFieldRequest) (*emptypb.Empty, error) // Creates a tag and assigns it to: // - // - An [Entry][google.cloud.datacatalog.v1.Entry] if the method name is - // `projects.locations.entryGroups.entries.tags.create`. - // - Or [EntryGroup][google.cloud.datacatalog.v1.EntryGroup]if the method - // name is `projects.locations.entryGroups.tags.create`. + // * An [Entry][google.cloud.datacatalog.v1.Entry] if the method name is + // `projects.locations.entryGroups.entries.tags.create`. + // * Or [EntryGroup][google.cloud.datacatalog.v1.EntryGroup]if the method + // name is `projects.locations.entryGroups.tags.create`. // // Note: The project identified by the `parent` parameter for the [tag] // (https://cloud.google.com/data-catalog/docs/reference/rest/v1/projects.locations.entryGroups.entries.tags/create#path-parameters) @@ -6643,17 +6639,17 @@ type DataCatalogServer interface { // // To call this method, you must have the following Google IAM permissions: // - // - `datacatalog.tagTemplates.setIamPolicy` to set policies on tag - // templates. - // - `datacatalog.entryGroups.setIamPolicy` to set policies on entry groups. + // - `datacatalog.tagTemplates.setIamPolicy` to set policies on tag + // templates. + // - `datacatalog.entryGroups.setIamPolicy` to set policies on entry groups. SetIamPolicy(context.Context, *v1.SetIamPolicyRequest) (*v1.Policy, error) // Gets the access control policy for a resource. // // May return: // - // - A`NOT_FOUND` error if the resource doesn't exist or you don't have the - // permission to view it. - // - An empty policy if the resource exists but doesn't have a set policy. + // * A`NOT_FOUND` error if the resource doesn't exist or you don't have the + // permission to view it. + // * An empty policy if the resource exists but doesn't have a set policy. // // Supported resources are: // @@ -6665,9 +6661,9 @@ type DataCatalogServer interface { // // To call this method, you must have the following Google IAM permissions: // - // - `datacatalog.tagTemplates.getIamPolicy` to get policies on tag - // templates. - // - `datacatalog.entryGroups.getIamPolicy` to get policies on entry groups. + // - `datacatalog.tagTemplates.getIamPolicy` to get policies on tag + // templates. + // - `datacatalog.entryGroups.getIamPolicy` to get policies on entry groups. GetIamPolicy(context.Context, *v1.GetIamPolicyRequest) (*v1.Policy, error) // Gets your permissions on a resource. // diff --git a/datacatalog/apiv1/datacatalogpb/dataplex_spec.pb.go b/datacatalog/apiv1/datacatalogpb/dataplex_spec.pb.go index a7fe115dbf96..79d5a5e36fe6 100644 --- a/datacatalog/apiv1/datacatalogpb/dataplex_spec.pb.go +++ b/datacatalog/apiv1/datacatalogpb/dataplex_spec.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/datacatalog/v1/dataplex_spec.proto package datacatalogpb diff --git a/datacatalog/apiv1/datacatalogpb/gcs_fileset_spec.pb.go b/datacatalog/apiv1/datacatalogpb/gcs_fileset_spec.pb.go index 5d9aad4261aa..c6a0360c51fd 100644 --- a/datacatalog/apiv1/datacatalogpb/gcs_fileset_spec.pb.go +++ b/datacatalog/apiv1/datacatalogpb/gcs_fileset_spec.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/datacatalog/v1/gcs_fileset_spec.proto package datacatalogpb @@ -51,22 +51,22 @@ type GcsFilesetSpec struct { // // Examples of valid `file_patterns`: // - // - `gs://bucket_name/dir/*`: matches all files in `bucket_name/dir` - // directory - // - `gs://bucket_name/dir/**`: matches all files in `bucket_name/dir` - // and all subdirectories - // - `gs://bucket_name/file*`: matches files prefixed by `file` in - // `bucket_name` - // - `gs://bucket_name/??.txt`: matches files with two characters followed by - // `.txt` in `bucket_name` - // - `gs://bucket_name/[aeiou].txt`: matches files that contain a single - // vowel character followed by `.txt` in - // `bucket_name` - // - `gs://bucket_name/[a-m].txt`: matches files that contain `a`, `b`, ... - // or `m` followed by `.txt` in `bucket_name` - // - `gs://bucket_name/a/*/b`: matches all files in `bucket_name` that match - // the `a/*/b` pattern, such as `a/c/b`, `a/d/b` - // - `gs://another_bucket/a.txt`: matches `gs://another_bucket/a.txt` + // * `gs://bucket_name/dir/*`: matches all files in `bucket_name/dir` + // directory + // * `gs://bucket_name/dir/**`: matches all files in `bucket_name/dir` + // and all subdirectories + // * `gs://bucket_name/file*`: matches files prefixed by `file` in + // `bucket_name` + // * `gs://bucket_name/??.txt`: matches files with two characters followed by + // `.txt` in `bucket_name` + // * `gs://bucket_name/[aeiou].txt`: matches files that contain a single + // vowel character followed by `.txt` in + // `bucket_name` + // * `gs://bucket_name/[a-m].txt`: matches files that contain `a`, `b`, ... + // or `m` followed by `.txt` in `bucket_name` + // * `gs://bucket_name/a/*/b`: matches all files in `bucket_name` that match + // the `a/*/b` pattern, such as `a/c/b`, `a/d/b` + // * `gs://another_bucket/a.txt`: matches `gs://another_bucket/a.txt` // // You can combine wildcards to match complex sets of files, for example: // diff --git a/datacatalog/apiv1/datacatalogpb/physical_schema.pb.go b/datacatalog/apiv1/datacatalogpb/physical_schema.pb.go index 56c69c91e50f..277235563985 100644 --- a/datacatalog/apiv1/datacatalogpb/physical_schema.pb.go +++ b/datacatalog/apiv1/datacatalogpb/physical_schema.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/datacatalog/v1/physical_schema.proto package datacatalogpb @@ -43,7 +43,6 @@ type PhysicalSchema struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Schema: - // // *PhysicalSchema_Avro // *PhysicalSchema_Thrift // *PhysicalSchema_Protobuf diff --git a/datacatalog/apiv1/datacatalogpb/policytagmanager.pb.go b/datacatalog/apiv1/datacatalogpb/policytagmanager.pb.go index 508ae99602ec..c9b2a09623d9 100644 --- a/datacatalog/apiv1/datacatalogpb/policytagmanager.pb.go +++ b/datacatalog/apiv1/datacatalogpb/policytagmanager.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/datacatalog/v1/policytagmanager.proto package datacatalogpb @@ -1735,10 +1735,10 @@ type PolicyTagManagerClient interface { CreatePolicyTag(ctx context.Context, in *CreatePolicyTagRequest, opts ...grpc.CallOption) (*PolicyTag, error) // Deletes a policy tag together with the following: // - // - All of its descendant policy tags, if any - // - Policies associated with the policy tag and its descendants - // - References from BigQuery table schema of the policy tag and its - // descendants + // * All of its descendant policy tags, if any + // * Policies associated with the policy tag and its descendants + // * References from BigQuery table schema of the policy tag and its + // descendants DeletePolicyTag(ctx context.Context, in *DeletePolicyTagRequest, opts ...grpc.CallOption) (*emptypb.Empty, error) // Updates a policy tag, including its display // name, description, and parent policy tag. @@ -1903,10 +1903,10 @@ type PolicyTagManagerServer interface { CreatePolicyTag(context.Context, *CreatePolicyTagRequest) (*PolicyTag, error) // Deletes a policy tag together with the following: // - // - All of its descendant policy tags, if any - // - Policies associated with the policy tag and its descendants - // - References from BigQuery table schema of the policy tag and its - // descendants + // * All of its descendant policy tags, if any + // * Policies associated with the policy tag and its descendants + // * References from BigQuery table schema of the policy tag and its + // descendants DeletePolicyTag(context.Context, *DeletePolicyTagRequest) (*emptypb.Empty, error) // Updates a policy tag, including its display // name, description, and parent policy tag. diff --git a/datacatalog/apiv1/datacatalogpb/policytagmanagerserialization.pb.go b/datacatalog/apiv1/datacatalogpb/policytagmanagerserialization.pb.go index f7bb25f6c33d..b95b25174afa 100644 --- a/datacatalog/apiv1/datacatalogpb/policytagmanagerserialization.pb.go +++ b/datacatalog/apiv1/datacatalogpb/policytagmanagerserialization.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/datacatalog/v1/policytagmanagerserialization.proto package datacatalogpb @@ -272,7 +272,6 @@ type ImportTaxonomiesRequest struct { // Source taxonomies to import. // // Types that are assignable to Source: - // // *ImportTaxonomiesRequest_InlineSource // *ImportTaxonomiesRequest_CrossRegionalSource Source isImportTaxonomiesRequest_Source `protobuf_oneof:"source"` @@ -519,7 +518,6 @@ type ExportTaxonomiesRequest struct { // Required. Export destination for taxonomies. // // Types that are assignable to Destination: - // // *ExportTaxonomiesRequest_SerializedTaxonomies Destination isExportTaxonomiesRequest_Destination `protobuf_oneof:"destination"` } @@ -1041,11 +1039,11 @@ type PolicyTagManagerSerializationClient interface { // // This operation automatically does the following: // - // - Deletes the existing policy tags that are missing from the - // `SerializedPolicyTag`. - // - Creates policy tags that don't have resource names. They are considered - // new. - // - Updates policy tags with valid resources names accordingly. + // - Deletes the existing policy tags that are missing from the + // `SerializedPolicyTag`. + // - Creates policy tags that don't have resource names. They are considered + // new. + // - Updates policy tags with valid resources names accordingly. ReplaceTaxonomy(ctx context.Context, in *ReplaceTaxonomyRequest, opts ...grpc.CallOption) (*Taxonomy, error) // Creates new taxonomies (including their policy tags) in a given project // by importing from inlined or cross-regional sources. @@ -1110,11 +1108,11 @@ type PolicyTagManagerSerializationServer interface { // // This operation automatically does the following: // - // - Deletes the existing policy tags that are missing from the - // `SerializedPolicyTag`. - // - Creates policy tags that don't have resource names. They are considered - // new. - // - Updates policy tags with valid resources names accordingly. + // - Deletes the existing policy tags that are missing from the + // `SerializedPolicyTag`. + // - Creates policy tags that don't have resource names. They are considered + // new. + // - Updates policy tags with valid resources names accordingly. ReplaceTaxonomy(context.Context, *ReplaceTaxonomyRequest) (*Taxonomy, error) // Creates new taxonomies (including their policy tags) in a given project // by importing from inlined or cross-regional sources. diff --git a/datacatalog/apiv1/datacatalogpb/schema.pb.go b/datacatalog/apiv1/datacatalogpb/schema.pb.go index 6362ee967e91..7734ad9adf78 100644 --- a/datacatalog/apiv1/datacatalogpb/schema.pb.go +++ b/datacatalog/apiv1/datacatalogpb/schema.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/datacatalog/v1/schema.proto package datacatalogpb diff --git a/datacatalog/apiv1/datacatalogpb/search.pb.go b/datacatalog/apiv1/datacatalogpb/search.pb.go index 3f532f7d4ea6..484a7552f361 100644 --- a/datacatalog/apiv1/datacatalogpb/search.pb.go +++ b/datacatalog/apiv1/datacatalogpb/search.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/datacatalog/v1/search.proto package datacatalogpb @@ -118,8 +118,8 @@ type SearchCatalogResult struct { // // Examples: // - // - `projects/{PROJECT_ID}/locations/{LOCATION_ID}/entryGroups/{ENTRY_GROUP_ID}/entries/{ENTRY_ID}` - // - `projects/{PROJECT_ID}/tagTemplates/{TAG_TEMPLATE_ID}` + // * `projects/{PROJECT_ID}/locations/{LOCATION_ID}/entryGroups/{ENTRY_GROUP_ID}/entries/{ENTRY_ID}` + // * `projects/{PROJECT_ID}/tagTemplates/{TAG_TEMPLATE_ID}` RelativeResourceName string `protobuf:"bytes,3,opt,name=relative_resource_name,json=relativeResourceName,proto3" json:"relative_resource_name,omitempty"` // The full name of the Google Cloud resource the entry belongs to. // @@ -136,7 +136,6 @@ type SearchCatalogResult struct { // `search_result_type` is `ENTRY`. // // Types that are assignable to System: - // // *SearchCatalogResult_IntegratedSystem // *SearchCatalogResult_UserSpecifiedSystem System isSearchCatalogResult_System `protobuf_oneof:"system"` @@ -146,11 +145,11 @@ type SearchCatalogResult struct { // // * For non-regionalized resources: // - // `{SYSTEM}:{PROJECT}.{PATH_TO_RESOURCE_SEPARATED_WITH_DOTS}` + // `{SYSTEM}:{PROJECT}.{PATH_TO_RESOURCE_SEPARATED_WITH_DOTS}` // // * For regionalized resources: // - // `{SYSTEM}:{PROJECT}.{LOCATION_ID}.{PATH_TO_RESOURCE_SEPARATED_WITH_DOTS}` + // `{SYSTEM}:{PROJECT}.{LOCATION_ID}.{PATH_TO_RESOURCE_SEPARATED_WITH_DOTS}` // // Example for a DPMS table: // diff --git a/datacatalog/apiv1/datacatalogpb/table_spec.pb.go b/datacatalog/apiv1/datacatalogpb/table_spec.pb.go index 229e959d812e..89be17008043 100644 --- a/datacatalog/apiv1/datacatalogpb/table_spec.pb.go +++ b/datacatalog/apiv1/datacatalogpb/table_spec.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/datacatalog/v1/table_spec.proto package datacatalogpb @@ -104,7 +104,6 @@ type BigQueryTableSpec struct { // Output only. // // Types that are assignable to TypeSpec: - // // *BigQueryTableSpec_ViewSpec // *BigQueryTableSpec_TableSpec TypeSpec isBigQueryTableSpec_TypeSpec `protobuf_oneof:"type_spec"` diff --git a/datacatalog/apiv1/datacatalogpb/tags.pb.go b/datacatalog/apiv1/datacatalogpb/tags.pb.go index 76c441abb5ed..a41b231c1e63 100644 --- a/datacatalog/apiv1/datacatalogpb/tags.pb.go +++ b/datacatalog/apiv1/datacatalogpb/tags.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/datacatalog/v1/tags.proto package datacatalogpb @@ -135,7 +135,6 @@ type Tag struct { // These fields cannot be updated after creation. // // Types that are assignable to Scope: - // // *Tag_Column Scope isTag_Scope `protobuf_oneof:"scope"` // Required. Maps the ID of a tag field to its value and additional information @@ -247,7 +246,6 @@ type TagField struct { // Required. The value of this field. // // Types that are assignable to Kind: - // // *TagField_DoubleValue // *TagField_StringValue // *TagField_BoolValue @@ -443,7 +441,7 @@ type TagTemplate struct { // [ListTags][google.cloud.datacatalog.v1.ListTags] API response. // // Additionally, you can search for a public tag by value with a - // simple search query in addition to using a “tag:“ predicate. + // simple search query in addition to using a ``tag:`` predicate. IsPubliclyReadable bool `protobuf:"varint,5,opt,name=is_publicly_readable,json=isPubliclyReadable,proto3" json:"is_publicly_readable,omitempty"` // Required. Map of tag template field IDs to the settings for the field. // This map is an exhaustive list of the allowed fields. The map must contain @@ -452,10 +450,10 @@ type TagTemplate struct { // The keys to this map are tag template field IDs. The IDs have the // following limitations: // - // - Can contain uppercase and lowercase letters, numbers (0-9) and - // underscores (_). - // - Must be at least 1 character and at most 64 characters long. - // - Must start with a letter or underscore. + // * Can contain uppercase and lowercase letters, numbers (0-9) and + // underscores (_). + // * Must be at least 1 character and at most 64 characters long. + // * Must start with a letter or underscore. Fields map[string]*TagTemplateField `protobuf:"bytes,3,rep,name=fields,proto3" json:"fields,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` } @@ -639,7 +637,6 @@ type FieldType struct { // Required. // // Types that are assignable to TypeDecl: - // // *FieldType_PrimitiveType_ // *FieldType_EnumType_ TypeDecl isFieldType_TypeDecl `protobuf_oneof:"type_decl"` diff --git a/datacatalog/apiv1/datacatalogpb/timestamps.pb.go b/datacatalog/apiv1/datacatalogpb/timestamps.pb.go index aeb72f6d487a..c79f235b81ca 100644 --- a/datacatalog/apiv1/datacatalogpb/timestamps.pb.go +++ b/datacatalog/apiv1/datacatalogpb/timestamps.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/datacatalog/v1/timestamps.proto package datacatalogpb diff --git a/datacatalog/apiv1/datacatalogpb/usage.pb.go b/datacatalog/apiv1/datacatalogpb/usage.pb.go index d90128fb8219..11b2fce93c55 100644 --- a/datacatalog/apiv1/datacatalogpb/usage.pb.go +++ b/datacatalog/apiv1/datacatalogpb/usage.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/datacatalog/v1/usage.proto package datacatalogpb diff --git a/datacatalog/apiv1/doc.go b/datacatalog/apiv1/doc.go index e1a2c574f0b5..e49132314810 100644 --- a/datacatalog/apiv1/doc.go +++ b/datacatalog/apiv1/doc.go @@ -87,6 +87,8 @@ package datacatalog // import "cloud.google.com/go/datacatalog/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -175,3 +177,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/datacatalog/apiv1/gapic_metadata.json b/datacatalog/apiv1/gapic_metadata.json index 370bfe259e30..d5a7af1cdf9b 100644 --- a/datacatalog/apiv1/gapic_metadata.json +++ b/datacatalog/apiv1/gapic_metadata.json @@ -171,6 +171,171 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "CreateEntry": { + "methods": [ + "CreateEntry" + ] + }, + "CreateEntryGroup": { + "methods": [ + "CreateEntryGroup" + ] + }, + "CreateTag": { + "methods": [ + "CreateTag" + ] + }, + "CreateTagTemplate": { + "methods": [ + "CreateTagTemplate" + ] + }, + "CreateTagTemplateField": { + "methods": [ + "CreateTagTemplateField" + ] + }, + "DeleteEntry": { + "methods": [ + "DeleteEntry" + ] + }, + "DeleteEntryGroup": { + "methods": [ + "DeleteEntryGroup" + ] + }, + "DeleteTag": { + "methods": [ + "DeleteTag" + ] + }, + "DeleteTagTemplate": { + "methods": [ + "DeleteTagTemplate" + ] + }, + "DeleteTagTemplateField": { + "methods": [ + "DeleteTagTemplateField" + ] + }, + "GetEntry": { + "methods": [ + "GetEntry" + ] + }, + "GetEntryGroup": { + "methods": [ + "GetEntryGroup" + ] + }, + "GetIamPolicy": { + "methods": [ + "GetIamPolicy" + ] + }, + "GetTagTemplate": { + "methods": [ + "GetTagTemplate" + ] + }, + "ListEntries": { + "methods": [ + "ListEntries" + ] + }, + "ListEntryGroups": { + "methods": [ + "ListEntryGroups" + ] + }, + "ListTags": { + "methods": [ + "ListTags" + ] + }, + "LookupEntry": { + "methods": [ + "LookupEntry" + ] + }, + "ModifyEntryContacts": { + "methods": [ + "ModifyEntryContacts" + ] + }, + "ModifyEntryOverview": { + "methods": [ + "ModifyEntryOverview" + ] + }, + "RenameTagTemplateField": { + "methods": [ + "RenameTagTemplateField" + ] + }, + "RenameTagTemplateFieldEnumValue": { + "methods": [ + "RenameTagTemplateFieldEnumValue" + ] + }, + "SearchCatalog": { + "methods": [ + "SearchCatalog" + ] + }, + "SetIamPolicy": { + "methods": [ + "SetIamPolicy" + ] + }, + "StarEntry": { + "methods": [ + "StarEntry" + ] + }, + "TestIamPermissions": { + "methods": [ + "TestIamPermissions" + ] + }, + "UnstarEntry": { + "methods": [ + "UnstarEntry" + ] + }, + "UpdateEntry": { + "methods": [ + "UpdateEntry" + ] + }, + "UpdateEntryGroup": { + "methods": [ + "UpdateEntryGroup" + ] + }, + "UpdateTag": { + "methods": [ + "UpdateTag" + ] + }, + "UpdateTagTemplate": { + "methods": [ + "UpdateTagTemplate" + ] + }, + "UpdateTagTemplateField": { + "methods": [ + "UpdateTagTemplateField" + ] + } + } } } }, @@ -245,6 +410,76 @@ ] } } + }, + "rest": { + "libraryClient": "PolicyTagManagerClient", + "rpcs": { + "CreatePolicyTag": { + "methods": [ + "CreatePolicyTag" + ] + }, + "CreateTaxonomy": { + "methods": [ + "CreateTaxonomy" + ] + }, + "DeletePolicyTag": { + "methods": [ + "DeletePolicyTag" + ] + }, + "DeleteTaxonomy": { + "methods": [ + "DeleteTaxonomy" + ] + }, + "GetIamPolicy": { + "methods": [ + "GetIamPolicy" + ] + }, + "GetPolicyTag": { + "methods": [ + "GetPolicyTag" + ] + }, + "GetTaxonomy": { + "methods": [ + "GetTaxonomy" + ] + }, + "ListPolicyTags": { + "methods": [ + "ListPolicyTags" + ] + }, + "ListTaxonomies": { + "methods": [ + "ListTaxonomies" + ] + }, + "SetIamPolicy": { + "methods": [ + "SetIamPolicy" + ] + }, + "TestIamPermissions": { + "methods": [ + "TestIamPermissions" + ] + }, + "UpdatePolicyTag": { + "methods": [ + "UpdatePolicyTag" + ] + }, + "UpdateTaxonomy": { + "methods": [ + "UpdateTaxonomy" + ] + } + } } } }, @@ -269,6 +504,26 @@ ] } } + }, + "rest": { + "libraryClient": "PolicyTagManagerSerializationClient", + "rpcs": { + "ExportTaxonomies": { + "methods": [ + "ExportTaxonomies" + ] + }, + "ImportTaxonomies": { + "methods": [ + "ImportTaxonomies" + ] + }, + "ReplaceTaxonomy": { + "methods": [ + "ReplaceTaxonomy" + ] + } + } } } } diff --git a/datacatalog/apiv1/policy_tag_manager_client.go b/datacatalog/apiv1/policy_tag_manager_client.go index 9b2b3853ef25..31df08135cf6 100644 --- a/datacatalog/apiv1/policy_tag_manager_client.go +++ b/datacatalog/apiv1/policy_tag_manager_client.go @@ -17,21 +17,27 @@ package datacatalog import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" datacatalogpb "cloud.google.com/go/datacatalog/apiv1/datacatalogpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" iampb "google.golang.org/genproto/googleapis/iam/v1" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -84,6 +90,24 @@ func defaultPolicyTagManagerCallOptions() *PolicyTagManagerCallOptions { } } +func defaultPolicyTagManagerRESTCallOptions() *PolicyTagManagerCallOptions { + return &PolicyTagManagerCallOptions{ + CreateTaxonomy: []gax.CallOption{}, + DeleteTaxonomy: []gax.CallOption{}, + UpdateTaxonomy: []gax.CallOption{}, + ListTaxonomies: []gax.CallOption{}, + GetTaxonomy: []gax.CallOption{}, + CreatePolicyTag: []gax.CallOption{}, + DeletePolicyTag: []gax.CallOption{}, + UpdatePolicyTag: []gax.CallOption{}, + ListPolicyTags: []gax.CallOption{}, + GetPolicyTag: []gax.CallOption{}, + GetIamPolicy: []gax.CallOption{}, + SetIamPolicy: []gax.CallOption{}, + TestIamPermissions: []gax.CallOption{}, + } +} + // internalPolicyTagManagerClient is an interface that defines the methods available from Google Cloud Data Catalog API. type internalPolicyTagManagerClient interface { Close() error @@ -310,6 +334,79 @@ func (c *policyTagManagerGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type policyTagManagerRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing PolicyTagManagerClient + CallOptions **PolicyTagManagerCallOptions +} + +// NewPolicyTagManagerRESTClient creates a new policy tag manager rest client. +// +// Policy Tag Manager API service allows you to manage your policy tags and +// taxonomies. +// +// Policy tags are used to tag BigQuery columns and apply additional access +// control policies. A taxonomy is a hierarchical grouping of policy tags that +// classify data along a common axis. +func NewPolicyTagManagerRESTClient(ctx context.Context, opts ...option.ClientOption) (*PolicyTagManagerClient, error) { + clientOpts := append(defaultPolicyTagManagerRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultPolicyTagManagerRESTCallOptions() + c := &policyTagManagerRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &PolicyTagManagerClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultPolicyTagManagerRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://datacatalog.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://datacatalog.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://datacatalog.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *policyTagManagerRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *policyTagManagerRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *policyTagManagerRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *policyTagManagerGRPCClient) CreateTaxonomy(ctx context.Context, req *datacatalogpb.CreateTaxonomyRequest, opts ...gax.CallOption) (*datacatalogpb.Taxonomy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) @@ -634,6 +731,859 @@ func (c *policyTagManagerGRPCClient) TestIamPermissions(ctx context.Context, req return resp, nil } +// CreateTaxonomy creates a taxonomy in a specified project. +// +// The taxonomy is initially empty, that is, it doesn’t contain policy tags. +func (c *policyTagManagerRESTClient) CreateTaxonomy(ctx context.Context, req *datacatalogpb.CreateTaxonomyRequest, opts ...gax.CallOption) (*datacatalogpb.Taxonomy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetTaxonomy() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/taxonomies", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateTaxonomy[0:len((*c.CallOptions).CreateTaxonomy):len((*c.CallOptions).CreateTaxonomy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &datacatalogpb.Taxonomy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteTaxonomy deletes a taxonomy, including all policy tags in this +// taxonomy, their associated policies, and the policy tags references from +// BigQuery columns. +func (c *policyTagManagerRESTClient) DeleteTaxonomy(ctx context.Context, req *datacatalogpb.DeleteTaxonomyRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// UpdateTaxonomy updates a taxonomy, including its display name, +// description, and activated policy types. +func (c *policyTagManagerRESTClient) UpdateTaxonomy(ctx context.Context, req *datacatalogpb.UpdateTaxonomyRequest, opts ...gax.CallOption) (*datacatalogpb.Taxonomy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetTaxonomy() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetTaxonomy().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "taxonomy.name", url.QueryEscape(req.GetTaxonomy().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateTaxonomy[0:len((*c.CallOptions).UpdateTaxonomy):len((*c.CallOptions).UpdateTaxonomy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &datacatalogpb.Taxonomy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListTaxonomies lists all taxonomies in a project in a particular location that you +// have a permission to view. +func (c *policyTagManagerRESTClient) ListTaxonomies(ctx context.Context, req *datacatalogpb.ListTaxonomiesRequest, opts ...gax.CallOption) *TaxonomyIterator { + it := &TaxonomyIterator{} + req = proto.Clone(req).(*datacatalogpb.ListTaxonomiesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*datacatalogpb.Taxonomy, string, error) { + resp := &datacatalogpb.ListTaxonomiesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/taxonomies", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetTaxonomies(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetTaxonomy gets a taxonomy. +func (c *policyTagManagerRESTClient) GetTaxonomy(ctx context.Context, req *datacatalogpb.GetTaxonomyRequest, opts ...gax.CallOption) (*datacatalogpb.Taxonomy, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetTaxonomy[0:len((*c.CallOptions).GetTaxonomy):len((*c.CallOptions).GetTaxonomy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &datacatalogpb.Taxonomy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreatePolicyTag creates a policy tag in a taxonomy. +func (c *policyTagManagerRESTClient) CreatePolicyTag(ctx context.Context, req *datacatalogpb.CreatePolicyTagRequest, opts ...gax.CallOption) (*datacatalogpb.PolicyTag, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetPolicyTag() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/policyTags", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreatePolicyTag[0:len((*c.CallOptions).CreatePolicyTag):len((*c.CallOptions).CreatePolicyTag)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &datacatalogpb.PolicyTag{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeletePolicyTag deletes a policy tag together with the following: +// +// All of its descendant policy tags, if any +// +// Policies associated with the policy tag and its descendants +// +// References from BigQuery table schema of the policy tag and its +// descendants +func (c *policyTagManagerRESTClient) DeletePolicyTag(ctx context.Context, req *datacatalogpb.DeletePolicyTagRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// UpdatePolicyTag updates a policy tag, including its display +// name, description, and parent policy tag. +func (c *policyTagManagerRESTClient) UpdatePolicyTag(ctx context.Context, req *datacatalogpb.UpdatePolicyTagRequest, opts ...gax.CallOption) (*datacatalogpb.PolicyTag, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetPolicyTag() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetPolicyTag().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "policy_tag.name", url.QueryEscape(req.GetPolicyTag().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdatePolicyTag[0:len((*c.CallOptions).UpdatePolicyTag):len((*c.CallOptions).UpdatePolicyTag)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &datacatalogpb.PolicyTag{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListPolicyTags lists all policy tags in a taxonomy. +func (c *policyTagManagerRESTClient) ListPolicyTags(ctx context.Context, req *datacatalogpb.ListPolicyTagsRequest, opts ...gax.CallOption) *PolicyTagIterator { + it := &PolicyTagIterator{} + req = proto.Clone(req).(*datacatalogpb.ListPolicyTagsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*datacatalogpb.PolicyTag, string, error) { + resp := &datacatalogpb.ListPolicyTagsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/policyTags", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetPolicyTags(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetPolicyTag gets a policy tag. +func (c *policyTagManagerRESTClient) GetPolicyTag(ctx context.Context, req *datacatalogpb.GetPolicyTagRequest, opts ...gax.CallOption) (*datacatalogpb.PolicyTag, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetPolicyTag[0:len((*c.CallOptions).GetPolicyTag):len((*c.CallOptions).GetPolicyTag)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &datacatalogpb.PolicyTag{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetIamPolicy gets the IAM policy for a policy tag or a taxonomy. +func (c *policyTagManagerRESTClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:getIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SetIamPolicy sets the IAM policy for a policy tag or a taxonomy. +func (c *policyTagManagerRESTClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:setIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// TestIamPermissions returns your permissions on a specified policy tag or +// taxonomy. +func (c *policyTagManagerRESTClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:testIamPermissions", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.TestIamPermissionsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + // PolicyTagIterator manages a stream of *datacatalogpb.PolicyTag. type PolicyTagIterator struct { items []*datacatalogpb.PolicyTag diff --git a/datacatalog/apiv1/policy_tag_manager_client_example_test.go b/datacatalog/apiv1/policy_tag_manager_client_example_test.go index 1d6356418c32..c86e13f1daca 100644 --- a/datacatalog/apiv1/policy_tag_manager_client_example_test.go +++ b/datacatalog/apiv1/policy_tag_manager_client_example_test.go @@ -42,6 +42,23 @@ func ExampleNewPolicyTagManagerClient() { _ = c } +func ExampleNewPolicyTagManagerRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := datacatalog.NewPolicyTagManagerRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExamplePolicyTagManagerClient_CreateTaxonomy() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/datacatalog/apiv1/policy_tag_manager_serialization_client.go b/datacatalog/apiv1/policy_tag_manager_serialization_client.go index 5e3e05319574..0637da3dbc0c 100644 --- a/datacatalog/apiv1/policy_tag_manager_serialization_client.go +++ b/datacatalog/apiv1/policy_tag_manager_serialization_client.go @@ -17,19 +17,25 @@ package datacatalog import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" datacatalogpb "cloud.google.com/go/datacatalog/apiv1/datacatalogpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" ) var newPolicyTagManagerSerializationClientHook clientHook @@ -61,6 +67,14 @@ func defaultPolicyTagManagerSerializationCallOptions() *PolicyTagManagerSerializ } } +func defaultPolicyTagManagerSerializationRESTCallOptions() *PolicyTagManagerSerializationCallOptions { + return &PolicyTagManagerSerializationCallOptions{ + ReplaceTaxonomy: []gax.CallOption{}, + ImportTaxonomies: []gax.CallOption{}, + ExportTaxonomies: []gax.CallOption{}, + } +} + // internalPolicyTagManagerSerializationClient is an interface that defines the methods available from Google Cloud Data Catalog API. type internalPolicyTagManagerSerializationClient interface { Close() error @@ -234,6 +248,77 @@ func (c *policyTagManagerSerializationGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type policyTagManagerSerializationRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing PolicyTagManagerSerializationClient + CallOptions **PolicyTagManagerSerializationCallOptions +} + +// NewPolicyTagManagerSerializationRESTClient creates a new policy tag manager serialization rest client. +// +// Policy Tag Manager Serialization API service allows you to manipulate +// your policy tags and taxonomies in a serialized format. +// +// Taxonomy is a hierarchical group of policy tags. +func NewPolicyTagManagerSerializationRESTClient(ctx context.Context, opts ...option.ClientOption) (*PolicyTagManagerSerializationClient, error) { + clientOpts := append(defaultPolicyTagManagerSerializationRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultPolicyTagManagerSerializationRESTCallOptions() + c := &policyTagManagerSerializationRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &PolicyTagManagerSerializationClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultPolicyTagManagerSerializationRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://datacatalog.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://datacatalog.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://datacatalog.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *policyTagManagerSerializationRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *policyTagManagerSerializationRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *policyTagManagerSerializationRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *policyTagManagerSerializationGRPCClient) ReplaceTaxonomy(ctx context.Context, req *datacatalogpb.ReplaceTaxonomyRequest, opts ...gax.CallOption) (*datacatalogpb.Taxonomy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) @@ -299,3 +384,223 @@ func (c *policyTagManagerSerializationGRPCClient) ExportTaxonomies(ctx context.C } return resp, nil } + +// ReplaceTaxonomy replaces (updates) a taxonomy and all its policy tags. +// +// The taxonomy and its entire hierarchy of policy tags must be +// represented literally by SerializedTaxonomy and the nested +// SerializedPolicyTag messages. +// +// This operation automatically does the following: +// +// Deletes the existing policy tags that are missing from the +// SerializedPolicyTag. +// +// Creates policy tags that don’t have resource names. They are considered +// new. +// +// Updates policy tags with valid resources names accordingly. +func (c *policyTagManagerSerializationRESTClient) ReplaceTaxonomy(ctx context.Context, req *datacatalogpb.ReplaceTaxonomyRequest, opts ...gax.CallOption) (*datacatalogpb.Taxonomy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:replace", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).ReplaceTaxonomy[0:len((*c.CallOptions).ReplaceTaxonomy):len((*c.CallOptions).ReplaceTaxonomy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &datacatalogpb.Taxonomy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ImportTaxonomies creates new taxonomies (including their policy tags) in a given project +// by importing from inlined or cross-regional sources. +// +// For a cross-regional source, new taxonomies are created by copying +// from a source in another region. +// +// For an inlined source, taxonomies and policy tags are created in bulk using +// nested protocol buffer structures. +func (c *policyTagManagerSerializationRESTClient) ImportTaxonomies(ctx context.Context, req *datacatalogpb.ImportTaxonomiesRequest, opts ...gax.CallOption) (*datacatalogpb.ImportTaxonomiesResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/taxonomies:import", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).ImportTaxonomies[0:len((*c.CallOptions).ImportTaxonomies):len((*c.CallOptions).ImportTaxonomies)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &datacatalogpb.ImportTaxonomiesResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ExportTaxonomies exports taxonomies in the requested type and returns them, +// including their policy tags. The requested taxonomies must belong to the +// same project. +// +// This method generates SerializedTaxonomy protocol buffers with nested +// policy tags that can be used as input for ImportTaxonomies calls. +func (c *policyTagManagerSerializationRESTClient) ExportTaxonomies(ctx context.Context, req *datacatalogpb.ExportTaxonomiesRequest, opts ...gax.CallOption) (*datacatalogpb.ExportTaxonomiesResponse, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/taxonomies:export", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetSerializedTaxonomies() { + params.Add("serializedTaxonomies", fmt.Sprintf("%v", req.GetSerializedTaxonomies())) + } + if items := req.GetTaxonomies(); len(items) > 0 { + for _, item := range items { + params.Add("taxonomies", fmt.Sprintf("%v", item)) + } + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).ExportTaxonomies[0:len((*c.CallOptions).ExportTaxonomies):len((*c.CallOptions).ExportTaxonomies)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &datacatalogpb.ExportTaxonomiesResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} diff --git a/datacatalog/apiv1/policy_tag_manager_serialization_client_example_test.go b/datacatalog/apiv1/policy_tag_manager_serialization_client_example_test.go index b1f812a02a47..d23b83ec891a 100644 --- a/datacatalog/apiv1/policy_tag_manager_serialization_client_example_test.go +++ b/datacatalog/apiv1/policy_tag_manager_serialization_client_example_test.go @@ -40,6 +40,23 @@ func ExampleNewPolicyTagManagerSerializationClient() { _ = c } +func ExampleNewPolicyTagManagerSerializationRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := datacatalog.NewPolicyTagManagerSerializationRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExamplePolicyTagManagerSerializationClient_ReplaceTaxonomy() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/datacatalog/apiv1beta1/data_catalog_client.go b/datacatalog/apiv1beta1/data_catalog_client.go index 24271a23b911..d32b56ae97a1 100644 --- a/datacatalog/apiv1beta1/data_catalog_client.go +++ b/datacatalog/apiv1beta1/data_catalog_client.go @@ -1561,6 +1561,11 @@ func (c *restClient) SearchCatalog(ctx context.Context, req *datacatalogpb.Searc } baseUrl.Path += fmt.Sprintf("/v1beta1/catalog:search") + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { @@ -1639,6 +1644,7 @@ func (c *restClient) CreateEntryGroup(ctx context.Context, req *datacatalogpb.Cr baseUrl.Path += fmt.Sprintf("/v1beta1/%v/entryGroups", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("entryGroupId", fmt.Sprintf("%v", req.GetEntryGroupId())) baseUrl.RawQuery = params.Encode() @@ -1708,6 +1714,7 @@ func (c *restClient) UpdateEntryGroup(ctx context.Context, req *datacatalogpb.Up baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetEntryGroup().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -1772,6 +1779,7 @@ func (c *restClient) GetEntryGroup(ctx context.Context, req *datacatalogpb.GetEn baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetReadMask() != nil { readMask, err := protojson.Marshal(req.GetReadMask()) if err != nil { @@ -1840,6 +1848,7 @@ func (c *restClient) DeleteEntryGroup(ctx context.Context, req *datacatalogpb.De baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetForce() { params.Add("force", fmt.Sprintf("%v", req.GetForce())) } @@ -1895,6 +1904,7 @@ func (c *restClient) ListEntryGroups(ctx context.Context, req *datacatalogpb.Lis baseUrl.Path += fmt.Sprintf("/v1beta1/%v/entryGroups", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -1984,6 +1994,7 @@ func (c *restClient) CreateEntry(ctx context.Context, req *datacatalogpb.CreateE baseUrl.Path += fmt.Sprintf("/v1beta1/%v/entries", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("entryId", fmt.Sprintf("%v", req.GetEntryId())) baseUrl.RawQuery = params.Encode() @@ -2053,6 +2064,7 @@ func (c *restClient) UpdateEntry(ctx context.Context, req *datacatalogpb.UpdateE baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetEntry().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -2122,6 +2134,11 @@ func (c *restClient) DeleteEntry(ctx context.Context, req *datacatalogpb.DeleteE } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2157,6 +2174,11 @@ func (c *restClient) GetEntry(ctx context.Context, req *datacatalogpb.GetEntryRe } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2213,6 +2235,7 @@ func (c *restClient) LookupEntry(ctx context.Context, req *datacatalogpb.LookupE baseUrl.Path += fmt.Sprintf("/v1beta1/entries:lookup") params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetLinkedResource() != "" { params.Add("linkedResource", fmt.Sprintf("%v", req.GetLinkedResource())) } @@ -2287,6 +2310,7 @@ func (c *restClient) ListEntries(ctx context.Context, req *datacatalogpb.ListEnt baseUrl.Path += fmt.Sprintf("/v1beta1/%v/entries", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -2379,6 +2403,7 @@ func (c *restClient) CreateTagTemplate(ctx context.Context, req *datacatalogpb.C baseUrl.Path += fmt.Sprintf("/v1beta1/%v/tagTemplates", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("tagTemplateId", fmt.Sprintf("%v", req.GetTagTemplateId())) baseUrl.RawQuery = params.Encode() @@ -2436,6 +2461,11 @@ func (c *restClient) GetTagTemplate(ctx context.Context, req *datacatalogpb.GetT } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2503,6 +2533,7 @@ func (c *restClient) UpdateTagTemplate(ctx context.Context, req *datacatalogpb.U baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetTagTemplate().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -2571,6 +2602,7 @@ func (c *restClient) DeleteTagTemplate(ctx context.Context, req *datacatalogpb.D baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("force", fmt.Sprintf("%v", req.GetForce())) baseUrl.RawQuery = params.Encode() @@ -2622,6 +2654,7 @@ func (c *restClient) CreateTagTemplateField(ctx context.Context, req *datacatalo baseUrl.Path += fmt.Sprintf("/v1beta1/%v/fields", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("tagTemplateFieldId", fmt.Sprintf("%v", req.GetTagTemplateFieldId())) baseUrl.RawQuery = params.Encode() @@ -2691,6 +2724,7 @@ func (c *restClient) UpdateTagTemplateField(ctx context.Context, req *datacatalo baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -2764,6 +2798,11 @@ func (c *restClient) RenameTagTemplateField(ctx context.Context, req *datacatalo } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:rename", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2822,6 +2861,7 @@ func (c *restClient) DeleteTagTemplateField(ctx context.Context, req *datacatalo baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("force", fmt.Sprintf("%v", req.GetForce())) baseUrl.RawQuery = params.Encode() @@ -2874,6 +2914,11 @@ func (c *restClient) CreateTag(ctx context.Context, req *datacatalogpb.CreateTag } baseUrl.Path += fmt.Sprintf("/v1beta1/%v/tags", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -2935,6 +2980,7 @@ func (c *restClient) UpdateTag(ctx context.Context, req *datacatalogpb.UpdateTag baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetTag().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -2998,6 +3044,11 @@ func (c *restClient) DeleteTag(ctx context.Context, req *datacatalogpb.DeleteTag } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -3047,6 +3098,7 @@ func (c *restClient) ListTags(ctx context.Context, req *datacatalogpb.ListTagsRe baseUrl.Path += fmt.Sprintf("/v1beta1/%v/tags", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -3145,6 +3197,11 @@ func (c *restClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRe } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:setIamPolicy", req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) @@ -3225,6 +3282,11 @@ func (c *restClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRe } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:getIamPolicy", req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) @@ -3299,6 +3361,11 @@ func (c *restClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamP } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:testIamPermissions", req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) diff --git a/datacatalog/apiv1beta1/datacatalogpb/common.pb.go b/datacatalog/apiv1beta1/datacatalogpb/common.pb.go index 67f7143e67fe..b7fb949d1555 100644 --- a/datacatalog/apiv1beta1/datacatalogpb/common.pb.go +++ b/datacatalog/apiv1beta1/datacatalogpb/common.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/datacatalog/v1beta1/common.proto package datacatalogpb diff --git a/datacatalog/apiv1beta1/datacatalogpb/datacatalog.pb.go b/datacatalog/apiv1beta1/datacatalogpb/datacatalog.pb.go index 1f7bfea887fa..a196b254451b 100644 --- a/datacatalog/apiv1beta1/datacatalogpb/datacatalog.pb.go +++ b/datacatalog/apiv1beta1/datacatalogpb/datacatalog.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/datacatalog/v1beta1/datacatalog.proto package datacatalogpb @@ -148,8 +148,8 @@ type SearchCatalogRequest struct { // Specifies the ordering of results, currently supported case-sensitive // choices are: // - // - `relevance`, only supports descending - // - `last_modified_timestamp [asc|desc]`, defaults to descending if not + // * `relevance`, only supports descending + // * `last_modified_timestamp [asc|desc]`, defaults to descending if not // specified // // If not specified, defaults to `relevance` descending. @@ -757,23 +757,21 @@ type UpdateEntryRequest struct { // // The following fields are modifiable: // * For entries with type `DATA_STREAM`: - // - `schema` - // + // * `schema` // * For entries with type `FILESET` - // - `schema` - // - `display_name` - // - `description` - // - `gcs_fileset_spec` - // - `gcs_fileset_spec.file_patterns` - // + // * `schema` + // * `display_name` + // * `description` + // * `gcs_fileset_spec` + // * `gcs_fileset_spec.file_patterns` // * For entries with `user_specified_type` - // - `schema` - // - `display_name` - // - `description` - // - user_specified_type - // - user_specified_system - // - linked_resource - // - source_system_timestamps + // * `schema` + // * `display_name` + // * `description` + // * user_specified_type + // * user_specified_system + // * linked_resource + // * source_system_timestamps UpdateMask *fieldmaskpb.FieldMask `protobuf:"bytes,2,opt,name=update_mask,json=updateMask,proto3" json:"update_mask,omitempty"` } @@ -938,7 +936,6 @@ type LookupEntryRequest struct { // for a Google Cloud Platform resource. // // Types that are assignable to TargetName: - // // *LookupEntryRequest_LinkedResource // *LookupEntryRequest_SqlResource TargetName isLookupEntryRequest_TargetName `protobuf_oneof:"target_name"` @@ -1009,8 +1006,8 @@ type LookupEntryRequest_LinkedResource struct { // // Examples: // - // - //bigquery.googleapis.com/projects/projectId/datasets/datasetId/tables/tableId - // - //pubsub.googleapis.com/projects/projectId/topics/topicId + // * //bigquery.googleapis.com/projects/projectId/datasets/datasetId/tables/tableId + // * //pubsub.googleapis.com/projects/projectId/topics/topicId LinkedResource string `protobuf:"bytes,1,opt,name=linked_resource,json=linkedResource,proto3,oneof"` } @@ -1019,11 +1016,11 @@ type LookupEntryRequest_SqlResource struct { // // Examples: // - // - `pubsub.project_id.topic_id` - // - “pubsub.project_id.`topic.id.with.dots` “ - // - `bigquery.table.project_id.dataset_id.table_id` - // - `bigquery.dataset.project_id.dataset_id` - // - `datacatalog.entry.project_id.location_id.entry_group_id.entry_id` + // * `pubsub.project_id.topic_id` + // * ``pubsub.project_id.`topic.id.with.dots` `` + // * `bigquery.table.project_id.dataset_id.table_id` + // * `bigquery.dataset.project_id.dataset_id` + // * `datacatalog.entry.project_id.location_id.entry_group_id.entry_id` // // `*_id`s shoud satisfy the standard SQL rules for identifiers. // https://cloud.google.com/bigquery/docs/reference/standard-sql/lexical. @@ -1072,21 +1069,18 @@ type Entry struct { // Required. Entry type. // // Types that are assignable to EntryType: - // // *Entry_Type // *Entry_UserSpecifiedType EntryType isEntry_EntryType `protobuf_oneof:"entry_type"` // The source system of the entry. // // Types that are assignable to System: - // // *Entry_IntegratedSystem // *Entry_UserSpecifiedSystem System isEntry_System `protobuf_oneof:"system"` // Type specification information. // // Types that are assignable to TypeSpec: - // // *Entry_GcsFilesetSpec // *Entry_BigqueryTableSpec // *Entry_BigqueryDateShardedSpec @@ -1555,7 +1549,7 @@ type UpdateTagTemplateRequest struct { // // Allowed fields: // - // - `display_name` + // * `display_name` // // If absent or empty, all of the allowed fields above will be updated. UpdateMask *fieldmaskpb.FieldMask `protobuf:"bytes,2,opt,name=update_mask,json=updateMask,proto3" json:"update_mask,omitempty"` @@ -1940,9 +1934,9 @@ type UpdateTagTemplateFieldRequest struct { // Optional. The field mask specifies the parts of the template to be updated. // Allowed fields: // - // - `display_name` - // - `type.enum_type` - // - `is_required` + // * `display_name` + // * `type.enum_type` + // * `is_required` // // If `update_mask` is not set or empty, all of the allowed fields above will // be updated. @@ -4064,7 +4058,6 @@ type DataCatalogClient interface { // - Tag templates. // - Entries. // - Entry groups. - // // Note, this method cannot be used to manage policies for BigQuery, Pub/Sub // and any external Google Cloud Platform resources synced to Data Catalog. // @@ -4082,7 +4075,6 @@ type DataCatalogClient interface { // - Tag templates. // - Entries. // - Entry groups. - // // Note, this method cannot be used to manage policies for BigQuery, Pub/Sub // and any external Google Cloud Platform resources synced to Data Catalog. // @@ -4100,7 +4092,6 @@ type DataCatalogClient interface { // - Tag templates. // - Entries. // - Entry groups. - // // Note, this method cannot be used to manage policies for BigQuery, Pub/Sub // and any external Google Cloud Platform resources synced to Data Catalog. // @@ -4501,7 +4492,6 @@ type DataCatalogServer interface { // - Tag templates. // - Entries. // - Entry groups. - // // Note, this method cannot be used to manage policies for BigQuery, Pub/Sub // and any external Google Cloud Platform resources synced to Data Catalog. // @@ -4519,7 +4509,6 @@ type DataCatalogServer interface { // - Tag templates. // - Entries. // - Entry groups. - // // Note, this method cannot be used to manage policies for BigQuery, Pub/Sub // and any external Google Cloud Platform resources synced to Data Catalog. // @@ -4537,7 +4526,6 @@ type DataCatalogServer interface { // - Tag templates. // - Entries. // - Entry groups. - // // Note, this method cannot be used to manage policies for BigQuery, Pub/Sub // and any external Google Cloud Platform resources synced to Data Catalog. // diff --git a/datacatalog/apiv1beta1/datacatalogpb/gcs_fileset_spec.pb.go b/datacatalog/apiv1beta1/datacatalogpb/gcs_fileset_spec.pb.go index 186a259c0f9a..89a8c6d096da 100644 --- a/datacatalog/apiv1beta1/datacatalogpb/gcs_fileset_spec.pb.go +++ b/datacatalog/apiv1beta1/datacatalogpb/gcs_fileset_spec.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/datacatalog/v1beta1/gcs_fileset_spec.proto package datacatalogpb @@ -50,26 +50,26 @@ type GcsFilesetSpec struct { // // Examples of valid file_patterns: // - // - `gs://bucket_name/dir/*`: matches all files within `bucket_name/dir` - // directory. - // - `gs://bucket_name/dir/**`: matches all files in `bucket_name/dir` - // spanning all subdirectories. - // - `gs://bucket_name/file*`: matches files prefixed by `file` in - // `bucket_name` - // - `gs://bucket_name/??.txt`: matches files with two characters followed by - // `.txt` in `bucket_name` - // - `gs://bucket_name/[aeiou].txt`: matches files that contain a single - // vowel character followed by `.txt` in - // `bucket_name` - // - `gs://bucket_name/[a-m].txt`: matches files that contain `a`, `b`, ... - // or `m` followed by `.txt` in `bucket_name` - // - `gs://bucket_name/a/*/b`: matches all files in `bucket_name` that match - // `a/*/b` pattern, such as `a/c/b`, `a/d/b` - // - `gs://another_bucket/a.txt`: matches `gs://another_bucket/a.txt` + // * `gs://bucket_name/dir/*`: matches all files within `bucket_name/dir` + // directory. + // * `gs://bucket_name/dir/**`: matches all files in `bucket_name/dir` + // spanning all subdirectories. + // * `gs://bucket_name/file*`: matches files prefixed by `file` in + // `bucket_name` + // * `gs://bucket_name/??.txt`: matches files with two characters followed by + // `.txt` in `bucket_name` + // * `gs://bucket_name/[aeiou].txt`: matches files that contain a single + // vowel character followed by `.txt` in + // `bucket_name` + // * `gs://bucket_name/[a-m].txt`: matches files that contain `a`, `b`, ... + // or `m` followed by `.txt` in `bucket_name` + // * `gs://bucket_name/a/*/b`: matches all files in `bucket_name` that match + // `a/*/b` pattern, such as `a/c/b`, `a/d/b` + // * `gs://another_bucket/a.txt`: matches `gs://another_bucket/a.txt` // // You can combine wildcards to provide more powerful matches, for example: // - // - `gs://bucket_name/[a-m]??.j*g` + // * `gs://bucket_name/[a-m]??.j*g` FilePatterns []string `protobuf:"bytes,1,rep,name=file_patterns,json=filePatterns,proto3" json:"file_patterns,omitempty"` // Output only. Sample files contained in this fileset, not all files contained in this // fileset are represented here. diff --git a/datacatalog/apiv1beta1/datacatalogpb/policytagmanager.pb.go b/datacatalog/apiv1beta1/datacatalogpb/policytagmanager.pb.go index 4fceed002c61..c669fe0c9820 100644 --- a/datacatalog/apiv1beta1/datacatalogpb/policytagmanager.pb.go +++ b/datacatalog/apiv1beta1/datacatalogpb/policytagmanager.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/datacatalog/v1beta1/policytagmanager.proto package datacatalogpb diff --git a/datacatalog/apiv1beta1/datacatalogpb/policytagmanagerserialization.pb.go b/datacatalog/apiv1beta1/datacatalogpb/policytagmanagerserialization.pb.go index 2851d765d697..65fdafa82d58 100644 --- a/datacatalog/apiv1beta1/datacatalogpb/policytagmanagerserialization.pb.go +++ b/datacatalog/apiv1beta1/datacatalogpb/policytagmanagerserialization.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/datacatalog/v1beta1/policytagmanagerserialization.proto package datacatalogpb @@ -193,7 +193,6 @@ type ImportTaxonomiesRequest struct { // Required. Source taxonomies to be imported in a tree structure. // // Types that are assignable to Source: - // // *ImportTaxonomiesRequest_InlineSource Source isImportTaxonomiesRequest_Source `protobuf_oneof:"source"` } @@ -376,7 +375,6 @@ type ExportTaxonomiesRequest struct { // Required. Taxonomies export destination. // // Types that are assignable to Destination: - // // *ExportTaxonomiesRequest_SerializedTaxonomies Destination isExportTaxonomiesRequest_Destination `protobuf_oneof:"destination"` } diff --git a/datacatalog/apiv1beta1/datacatalogpb/schema.pb.go b/datacatalog/apiv1beta1/datacatalogpb/schema.pb.go index b7f2fface401..768136276cac 100644 --- a/datacatalog/apiv1beta1/datacatalogpb/schema.pb.go +++ b/datacatalog/apiv1beta1/datacatalogpb/schema.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/datacatalog/v1beta1/schema.proto package datacatalogpb diff --git a/datacatalog/apiv1beta1/datacatalogpb/search.pb.go b/datacatalog/apiv1beta1/datacatalogpb/search.pb.go index 9b4bee670c87..063216580fb4 100644 --- a/datacatalog/apiv1beta1/datacatalogpb/search.pb.go +++ b/datacatalog/apiv1beta1/datacatalogpb/search.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/datacatalog/v1beta1/search.proto package datacatalogpb @@ -110,14 +110,14 @@ type SearchCatalogResult struct { // The relative resource name of the resource in URL format. // Examples: // - // - `projects/{project_id}/locations/{location_id}/entryGroups/{entry_group_id}/entries/{entry_id}` - // - `projects/{project_id}/tagTemplates/{tag_template_id}` + // * `projects/{project_id}/locations/{location_id}/entryGroups/{entry_group_id}/entries/{entry_id}` + // * `projects/{project_id}/tagTemplates/{tag_template_id}` RelativeResourceName string `protobuf:"bytes,3,opt,name=relative_resource_name,json=relativeResourceName,proto3" json:"relative_resource_name,omitempty"` // The full name of the cloud resource the entry belongs to. See: // https://cloud.google.com/apis/design/resource_names#full_resource_name. // Example: // - // - `//bigquery.googleapis.com/projects/projectId/datasets/datasetId/tables/tableId` + // * `//bigquery.googleapis.com/projects/projectId/datasets/datasetId/tables/tableId` LinkedResource string `protobuf:"bytes,4,opt,name=linked_resource,json=linkedResource,proto3" json:"linked_resource,omitempty"` } diff --git a/datacatalog/apiv1beta1/datacatalogpb/table_spec.pb.go b/datacatalog/apiv1beta1/datacatalogpb/table_spec.pb.go index 3ba291fdbb82..71e72a9df060 100644 --- a/datacatalog/apiv1beta1/datacatalogpb/table_spec.pb.go +++ b/datacatalog/apiv1beta1/datacatalogpb/table_spec.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/datacatalog/v1beta1/table_spec.proto package datacatalogpb @@ -100,7 +100,6 @@ type BigQueryTableSpec struct { // Output only. // // Types that are assignable to TypeSpec: - // // *BigQueryTableSpec_ViewSpec // *BigQueryTableSpec_TableSpec TypeSpec isBigQueryTableSpec_TypeSpec `protobuf_oneof:"type_spec"` diff --git a/datacatalog/apiv1beta1/datacatalogpb/tags.pb.go b/datacatalog/apiv1beta1/datacatalogpb/tags.pb.go index 38f61d7f75b5..6a501e5fbe4b 100644 --- a/datacatalog/apiv1beta1/datacatalogpb/tags.pb.go +++ b/datacatalog/apiv1beta1/datacatalogpb/tags.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/datacatalog/v1beta1/tags.proto package datacatalogpb @@ -129,7 +129,6 @@ type Tag struct { // to that scope. These fields cannot be updated after creation. // // Types that are assignable to Scope: - // // *Tag_Column Scope isTag_Scope `protobuf_oneof:"scope"` // Required. This maps the ID of a tag field to the value of and additional information @@ -241,7 +240,6 @@ type TagField struct { // Required. The value of this field. // // Types that are assignable to Kind: - // // *TagField_DoubleValue // *TagField_StringValue // *TagField_BoolValue @@ -571,7 +569,6 @@ type FieldType struct { // Required. // // Types that are assignable to TypeDecl: - // // *FieldType_PrimitiveType_ // *FieldType_EnumType_ TypeDecl isFieldType_TypeDecl `protobuf_oneof:"type_decl"` diff --git a/datacatalog/apiv1beta1/datacatalogpb/timestamps.pb.go b/datacatalog/apiv1beta1/datacatalogpb/timestamps.pb.go index 19d593b61837..00546894bba1 100644 --- a/datacatalog/apiv1beta1/datacatalogpb/timestamps.pb.go +++ b/datacatalog/apiv1beta1/datacatalogpb/timestamps.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/datacatalog/v1beta1/timestamps.proto package datacatalogpb diff --git a/datacatalog/apiv1beta1/policy_tag_manager_client.go b/datacatalog/apiv1beta1/policy_tag_manager_client.go index 669d8ced78f4..4fb8c3f64545 100644 --- a/datacatalog/apiv1beta1/policy_tag_manager_client.go +++ b/datacatalog/apiv1beta1/policy_tag_manager_client.go @@ -666,6 +666,11 @@ func (c *policyTagManagerRESTClient) CreateTaxonomy(ctx context.Context, req *da } baseUrl.Path += fmt.Sprintf("/v1beta1/%v/taxonomies", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -720,6 +725,11 @@ func (c *policyTagManagerRESTClient) DeleteTaxonomy(ctx context.Context, req *da } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -763,6 +773,7 @@ func (c *policyTagManagerRESTClient) UpdateTaxonomy(ctx context.Context, req *da baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetTaxonomy().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -841,6 +852,7 @@ func (c *policyTagManagerRESTClient) ListTaxonomies(ctx context.Context, req *da baseUrl.Path += fmt.Sprintf("/v1beta1/%v/taxonomies", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -914,6 +926,11 @@ func (c *policyTagManagerRESTClient) GetTaxonomy(ctx context.Context, req *datac } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -974,6 +991,11 @@ func (c *policyTagManagerRESTClient) CreatePolicyTag(ctx context.Context, req *d } baseUrl.Path += fmt.Sprintf("/v1beta1/%v/policyTags", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1027,6 +1049,11 @@ func (c *policyTagManagerRESTClient) DeletePolicyTag(ctx context.Context, req *d } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1070,6 +1097,7 @@ func (c *policyTagManagerRESTClient) UpdatePolicyTag(ctx context.Context, req *d baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetPolicyTag().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -1147,6 +1175,7 @@ func (c *policyTagManagerRESTClient) ListPolicyTags(ctx context.Context, req *da baseUrl.Path += fmt.Sprintf("/v1beta1/%v/policyTags", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -1220,6 +1249,11 @@ func (c *policyTagManagerRESTClient) GetPolicyTag(ctx context.Context, req *data } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1279,6 +1313,11 @@ func (c *policyTagManagerRESTClient) GetIamPolicy(ctx context.Context, req *iamp } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:getIamPolicy", req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) @@ -1338,6 +1377,11 @@ func (c *policyTagManagerRESTClient) SetIamPolicy(ctx context.Context, req *iamp } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:setIamPolicy", req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) @@ -1398,6 +1442,11 @@ func (c *policyTagManagerRESTClient) TestIamPermissions(ctx context.Context, req } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:testIamPermissions", req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) diff --git a/datacatalog/apiv1beta1/policy_tag_manager_serialization_client.go b/datacatalog/apiv1beta1/policy_tag_manager_serialization_client.go index 5cbe72a16d83..1a28512a1bde 100644 --- a/datacatalog/apiv1beta1/policy_tag_manager_serialization_client.go +++ b/datacatalog/apiv1beta1/policy_tag_manager_serialization_client.go @@ -336,6 +336,11 @@ func (c *policyTagManagerSerializationRESTClient) ImportTaxonomies(ctx context.C } baseUrl.Path += fmt.Sprintf("/v1beta1/%v/taxonomies:import", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -393,11 +398,14 @@ func (c *policyTagManagerSerializationRESTClient) ExportTaxonomies(ctx context.C baseUrl.Path += fmt.Sprintf("/v1beta1/%v/taxonomies:export", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetSerializedTaxonomies() { params.Add("serializedTaxonomies", fmt.Sprintf("%v", req.GetSerializedTaxonomies())) } - if req.GetTaxonomies() != nil { - params.Add("taxonomies", fmt.Sprintf("%v", req.GetTaxonomies())) + if items := req.GetTaxonomies(); len(items) > 0 { + for _, item := range items { + params.Add("taxonomies", fmt.Sprintf("%v", item)) + } } baseUrl.RawQuery = params.Encode() diff --git a/dataflow/apiv1beta3/dataflowpb/environment.pb.go b/dataflow/apiv1beta3/dataflowpb/environment.pb.go index d25eebfec731..5d5c8d43e353 100644 --- a/dataflow/apiv1beta3/dataflowpb/environment.pb.go +++ b/dataflow/apiv1beta3/dataflowpb/environment.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/dataflow/v1beta3/environment.proto package dataflowpb @@ -449,8 +449,8 @@ type Environment struct { // // Google Cloud Storage: // - // storage.googleapis.com/{bucket}/{object} - // bucket.storage.googleapis.com/{object} + // storage.googleapis.com/{bucket}/{object} + // bucket.storage.googleapis.com/{object} TempStoragePrefix string `protobuf:"bytes,1,opt,name=temp_storage_prefix,json=tempStoragePrefix,proto3" json:"temp_storage_prefix,omitempty"` // The type of cluster manager API to use. If unknown or // unspecified, the service will attempt to choose a reasonable @@ -469,8 +469,7 @@ type Environment struct { // at rest, AKA a Customer Managed Encryption Key (CMEK). // // Format: - // - // projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys/KEY + // projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys/KEY ServiceKmsKeyName string `protobuf:"bytes,12,opt,name=service_kms_key_name,json=serviceKmsKeyName,proto3" json:"service_kms_key_name,omitempty"` // The worker pools. At least one "harness" worker pool must be // specified in order for the job to have workers. @@ -486,8 +485,7 @@ type Environment struct { // The supported resource type is: // // Google BigQuery: - // - // bigquery.googleapis.com/{dataset} + // bigquery.googleapis.com/{dataset} Dataset string `protobuf:"bytes,7,opt,name=dataset,proto3" json:"dataset,omitempty"` // The Cloud Dataflow SDK pipeline options specified by the user. These // options are passed through the service and are used to recreate the @@ -689,8 +687,8 @@ type Package struct { // // Google Cloud Storage: // - // storage.googleapis.com/{bucket} - // bucket.storage.googleapis.com/ + // storage.googleapis.com/{bucket} + // bucket.storage.googleapis.com/ Location string `protobuf:"bytes,2,opt,name=location,proto3" json:"location,omitempty"` } @@ -858,8 +856,8 @@ type WorkerSettings struct { // // Google Cloud Storage: // - // storage.googleapis.com/{bucket}/{object} - // bucket.storage.googleapis.com/{object} + // storage.googleapis.com/{bucket}/{object} + // bucket.storage.googleapis.com/{object} TempStoragePrefix string `protobuf:"bytes,6,opt,name=temp_storage_prefix,json=tempStoragePrefix,proto3" json:"temp_storage_prefix,omitempty"` } @@ -981,9 +979,8 @@ type TaskRunnerSettings struct { // The supported resource type is: // // Google Cloud Storage: - // - // storage.googleapis.com/{bucket}/{object} - // bucket.storage.googleapis.com/{object} + // storage.googleapis.com/{bucket}/{object} + // bucket.storage.googleapis.com/{object} LogUploadLocation string `protobuf:"bytes,11,opt,name=log_upload_location,json=logUploadLocation,proto3" json:"log_upload_location,omitempty"` // The directory on the VM to store logs. LogDir string `protobuf:"bytes,12,opt,name=log_dir,json=logDir,proto3" json:"log_dir,omitempty"` @@ -993,9 +990,8 @@ type TaskRunnerSettings struct { // The supported resource type is: // // Google Cloud Storage: - // - // storage.googleapis.com/{bucket}/{object} - // bucket.storage.googleapis.com/{object} + // storage.googleapis.com/{bucket}/{object} + // bucket.storage.googleapis.com/{object} TempStoragePrefix string `protobuf:"bytes,13,opt,name=temp_storage_prefix,json=tempStoragePrefix,proto3" json:"temp_storage_prefix,omitempty"` // The command to launch the worker harness. HarnessCommand string `protobuf:"bytes,14,opt,name=harness_command,json=harnessCommand,proto3" json:"harness_command,omitempty"` diff --git a/dataflow/apiv1beta3/dataflowpb/jobs.pb.go b/dataflow/apiv1beta3/dataflowpb/jobs.pb.go index 7bffedab1cbb..a12f7a952d22 100644 --- a/dataflow/apiv1beta3/dataflowpb/jobs.pb.go +++ b/dataflow/apiv1beta3/dataflowpb/jobs.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/dataflow/v1beta3/jobs.proto package dataflowpb @@ -524,8 +524,8 @@ type Job struct { // // Google Cloud Storage: // - // storage.googleapis.com/{bucket}/{object} - // bucket.storage.googleapis.com/{object} + // storage.googleapis.com/{bucket}/{object} + // bucket.storage.googleapis.com/{object} TempFiles []string `protobuf:"bytes,16,rep,name=temp_files,json=tempFiles,proto3" json:"temp_files,omitempty"` // User-defined labels for this job. // @@ -1684,7 +1684,6 @@ type DisplayData struct { // set. // // Types that are assignable to Value: - // // *DisplayData_StrValue // *DisplayData_Int64Value // *DisplayData_FloatValue diff --git a/dataflow/apiv1beta3/dataflowpb/messages.pb.go b/dataflow/apiv1beta3/dataflowpb/messages.pb.go index b2a876431da5..c755eabdbf21 100644 --- a/dataflow/apiv1beta3/dataflowpb/messages.pb.go +++ b/dataflow/apiv1beta3/dataflowpb/messages.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/dataflow/v1beta3/messages.proto package dataflowpb diff --git a/dataflow/apiv1beta3/dataflowpb/metrics.pb.go b/dataflow/apiv1beta3/dataflowpb/metrics.pb.go index 59aa395c2cba..2632b8723e55 100644 --- a/dataflow/apiv1beta3/dataflowpb/metrics.pb.go +++ b/dataflow/apiv1beta3/dataflowpb/metrics.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/dataflow/v1beta3/metrics.proto package dataflowpb diff --git a/dataflow/apiv1beta3/dataflowpb/snapshots.pb.go b/dataflow/apiv1beta3/dataflowpb/snapshots.pb.go index 5e4ddc9dbd6c..85454682bace 100644 --- a/dataflow/apiv1beta3/dataflowpb/snapshots.pb.go +++ b/dataflow/apiv1beta3/dataflowpb/snapshots.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/dataflow/v1beta3/snapshots.proto package dataflowpb diff --git a/dataflow/apiv1beta3/dataflowpb/streaming.pb.go b/dataflow/apiv1beta3/dataflowpb/streaming.pb.go index 5c145a5cd6e3..138fe6e16e26 100644 --- a/dataflow/apiv1beta3/dataflowpb/streaming.pb.go +++ b/dataflow/apiv1beta3/dataflowpb/streaming.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/dataflow/v1beta3/streaming.proto package dataflowpb @@ -398,7 +398,6 @@ type StreamLocation struct { // A specification of a stream's location. // // Types that are assignable to Location: - // // *StreamLocation_StreamingStageLocation // *StreamLocation_PubsubLocation // *StreamLocation_SideInputLocation diff --git a/dataflow/apiv1beta3/dataflowpb/templates.pb.go b/dataflow/apiv1beta3/dataflowpb/templates.pb.go index 87c59370ef66..4c353d73d726 100644 --- a/dataflow/apiv1beta3/dataflowpb/templates.pb.go +++ b/dataflow/apiv1beta3/dataflowpb/templates.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/dataflow/v1beta3/templates.proto package dataflowpb @@ -412,7 +412,6 @@ type LaunchFlexTemplateParameter struct { // Launch Mechanism. // // Types that are assignable to Template: - // // *LaunchFlexTemplateParameter_ContainerSpec // *LaunchFlexTemplateParameter_ContainerSpecGcsPath Template isLaunchFlexTemplateParameter_Template `protobuf_oneof:"template"` @@ -1426,7 +1425,6 @@ type CreateJobFromTemplateRequest struct { // The template from which to create the job. // // Types that are assignable to Template: - // // *CreateJobFromTemplateRequest_GcsPath Template isCreateJobFromTemplateRequest_Template `protobuf_oneof:"template"` // The runtime parameters to pass to the job. @@ -1544,7 +1542,6 @@ type GetTemplateRequest struct { // The template from which to create the job. // // Types that are assignable to Template: - // // *GetTemplateRequest_GcsPath Template isGetTemplateRequest_Template `protobuf_oneof:"template"` // The view to retrieve. Defaults to METADATA_ONLY. @@ -1814,7 +1811,6 @@ type LaunchTemplateRequest struct { // The template from which to create the job. // // Types that are assignable to Template: - // // *LaunchTemplateRequest_GcsPath // *LaunchTemplateRequest_DynamicTemplate Template isLaunchTemplateRequest_Template `protobuf_oneof:"template"` diff --git a/dataflow/apiv1beta3/flex_templates_client.go b/dataflow/apiv1beta3/flex_templates_client.go index 1aa2e5355707..752a814d5bc7 100644 --- a/dataflow/apiv1beta3/flex_templates_client.go +++ b/dataflow/apiv1beta3/flex_templates_client.go @@ -296,6 +296,11 @@ func (c *flexTemplatesRESTClient) LaunchFlexTemplate(ctx context.Context, req *d } baseUrl.Path += fmt.Sprintf("/v1b3/projects/%v/locations/%v/flexTemplates:launch", req.GetProjectId(), req.GetLocation()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "location", url.QueryEscape(req.GetLocation()))) diff --git a/dataflow/apiv1beta3/jobs_v1_beta3_client.go b/dataflow/apiv1beta3/jobs_v1_beta3_client.go index 49aade2aac1e..dbd740bb5b58 100644 --- a/dataflow/apiv1beta3/jobs_v1_beta3_client.go +++ b/dataflow/apiv1beta3/jobs_v1_beta3_client.go @@ -570,6 +570,7 @@ func (c *jobsV1Beta3RESTClient) CreateJob(ctx context.Context, req *dataflowpb.C baseUrl.Path += fmt.Sprintf("/v1b3/projects/%v/locations/%v/jobs", req.GetProjectId(), req.GetLocation()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetReplaceJobId() != "" { params.Add("replaceJobId", fmt.Sprintf("%v", req.GetReplaceJobId())) } @@ -639,6 +640,7 @@ func (c *jobsV1Beta3RESTClient) GetJob(ctx context.Context, req *dataflowpb.GetJ baseUrl.Path += fmt.Sprintf("/v1b3/projects/%v/locations/%v/jobs/%v", req.GetProjectId(), req.GetLocation(), req.GetJobId()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetView() != 0 { params.Add("view", fmt.Sprintf("%v", req.GetView())) } @@ -711,6 +713,11 @@ func (c *jobsV1Beta3RESTClient) UpdateJob(ctx context.Context, req *dataflowpb.U } baseUrl.Path += fmt.Sprintf("/v1b3/projects/%v/locations/%v/jobs/%v", req.GetProjectId(), req.GetLocation(), req.GetJobId()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "location", url.QueryEscape(req.GetLocation()), "job_id", url.QueryEscape(req.GetJobId()))) @@ -785,6 +792,7 @@ func (c *jobsV1Beta3RESTClient) ListJobs(ctx context.Context, req *dataflowpb.Li baseUrl.Path += fmt.Sprintf("/v1b3/projects/%v/locations/%v/jobs", req.GetProjectId(), req.GetLocation()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != 0 { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -878,6 +886,7 @@ func (c *jobsV1Beta3RESTClient) AggregatedListJobs(ctx context.Context, req *dat baseUrl.Path += fmt.Sprintf("/v1b3/projects/%v/jobs:aggregated", req.GetProjectId()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != 0 { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -961,6 +970,7 @@ func (c *jobsV1Beta3RESTClient) CheckActiveJobs(ctx context.Context, req *datafl baseUrl.Path += fmt.Sprintf("") params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetProjectId() != "" { params.Add("projectId", fmt.Sprintf("%v", req.GetProjectId())) } @@ -1024,6 +1034,11 @@ func (c *jobsV1Beta3RESTClient) SnapshotJob(ctx context.Context, req *dataflowpb } baseUrl.Path += fmt.Sprintf("/v1b3/projects/%v/locations/%v/jobs/%v:snapshot", req.GetProjectId(), req.GetLocation(), req.GetJobId()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "location", url.QueryEscape(req.GetLocation()), "job_id", url.QueryEscape(req.GetJobId()))) diff --git a/dataflow/apiv1beta3/messages_v1_beta3_client.go b/dataflow/apiv1beta3/messages_v1_beta3_client.go index 0fa34311f643..c7b16403c59e 100644 --- a/dataflow/apiv1beta3/messages_v1_beta3_client.go +++ b/dataflow/apiv1beta3/messages_v1_beta3_client.go @@ -348,6 +348,7 @@ func (c *messagesV1Beta3RESTClient) ListJobMessages(ctx context.Context, req *da baseUrl.Path += fmt.Sprintf("/v1b3/projects/%v/locations/%v/jobs/%v/messages", req.GetProjectId(), req.GetLocation(), req.GetJobId()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetEndTime() != nil { endTime, err := protojson.Marshal(req.GetEndTime()) if err != nil { diff --git a/dataflow/apiv1beta3/metrics_v1_beta3_client.go b/dataflow/apiv1beta3/metrics_v1_beta3_client.go index 51f28ba72b7c..c0b031a640ff 100644 --- a/dataflow/apiv1beta3/metrics_v1_beta3_client.go +++ b/dataflow/apiv1beta3/metrics_v1_beta3_client.go @@ -426,6 +426,7 @@ func (c *metricsV1Beta3RESTClient) GetJobMetrics(ctx context.Context, req *dataf baseUrl.Path += fmt.Sprintf("/v1b3/projects/%v/locations/%v/jobs/%v/metrics", req.GetProjectId(), req.GetLocation(), req.GetJobId()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetStartTime() != nil { startTime, err := protojson.Marshal(req.GetStartTime()) if err != nil { @@ -505,6 +506,7 @@ func (c *metricsV1Beta3RESTClient) GetJobExecutionDetails(ctx context.Context, r baseUrl.Path += fmt.Sprintf("/v1b3/projects/%v/locations/%v/jobs/%v/executionDetails", req.GetProjectId(), req.GetLocation(), req.GetJobId()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -595,6 +597,7 @@ func (c *metricsV1Beta3RESTClient) GetStageExecutionDetails(ctx context.Context, baseUrl.Path += fmt.Sprintf("/v1b3/projects/%v/locations/%v/jobs/%v/stages/%v/executionDetails", req.GetProjectId(), req.GetLocation(), req.GetJobId(), req.GetStageId()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetEndTime() != nil { endTime, err := protojson.Marshal(req.GetEndTime()) if err != nil { diff --git a/dataflow/apiv1beta3/snapshots_v1_beta3_client.go b/dataflow/apiv1beta3/snapshots_v1_beta3_client.go index 2cef5c01635a..af326e7fe715 100644 --- a/dataflow/apiv1beta3/snapshots_v1_beta3_client.go +++ b/dataflow/apiv1beta3/snapshots_v1_beta3_client.go @@ -357,6 +357,11 @@ func (c *snapshotsV1Beta3RESTClient) GetSnapshot(ctx context.Context, req *dataf } baseUrl.Path += fmt.Sprintf("/v1b3/projects/%v/locations/%v/snapshots/%v", req.GetProjectId(), req.GetLocation(), req.GetSnapshotId()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "location", url.QueryEscape(req.GetLocation()), "snapshot_id", url.QueryEscape(req.GetSnapshotId()))) @@ -410,6 +415,11 @@ func (c *snapshotsV1Beta3RESTClient) DeleteSnapshot(ctx context.Context, req *da } baseUrl.Path += fmt.Sprintf("/v1b3/projects/%v/locations/%v/snapshots/%v", req.GetProjectId(), req.GetLocation(), req.GetSnapshotId()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "location", url.QueryEscape(req.GetLocation()), "snapshot_id", url.QueryEscape(req.GetSnapshotId()))) @@ -463,6 +473,11 @@ func (c *snapshotsV1Beta3RESTClient) ListSnapshots(ctx context.Context, req *dat } baseUrl.Path += fmt.Sprintf("/v1b3/projects/%v/locations/%v/jobs/%v/snapshots", req.GetProjectId(), req.GetLocation(), req.GetJobId()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "location", url.QueryEscape(req.GetLocation()), "job_id", url.QueryEscape(req.GetJobId()))) diff --git a/dataflow/apiv1beta3/templates_client.go b/dataflow/apiv1beta3/templates_client.go index e67feaf6f253..2037adcb4c2a 100644 --- a/dataflow/apiv1beta3/templates_client.go +++ b/dataflow/apiv1beta3/templates_client.go @@ -364,6 +364,11 @@ func (c *templatesRESTClient) CreateJobFromTemplate(ctx context.Context, req *da } baseUrl.Path += fmt.Sprintf("/v1b3/projects/%v/locations/%v/templates", req.GetProjectId(), req.GetLocation()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "location", url.QueryEscape(req.GetLocation()))) @@ -425,6 +430,7 @@ func (c *templatesRESTClient) LaunchTemplate(ctx context.Context, req *dataflowp baseUrl.Path += fmt.Sprintf("/v1b3/projects/%v/locations/%v/templates:launch", req.GetProjectId(), req.GetLocation()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetDynamicTemplate().GetGcsPath() != "" { params.Add("dynamicTemplate.gcsPath", fmt.Sprintf("%v", req.GetDynamicTemplate().GetGcsPath())) } @@ -494,6 +500,7 @@ func (c *templatesRESTClient) GetTemplate(ctx context.Context, req *dataflowpb.G baseUrl.Path += fmt.Sprintf("/v1b3/projects/%v/locations/%v/templates:get", req.GetProjectId(), req.GetLocation()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetGcsPath() != "" { params.Add("gcsPath", fmt.Sprintf("%v", req.GetGcsPath())) } diff --git a/dataform/apiv1alpha2/dataform_client.go b/dataform/apiv1alpha2/dataform_client.go index af29fb0dfe5b..7bfb418ab1a4 100644 --- a/dataform/apiv1alpha2/dataform_client.go +++ b/dataform/apiv1alpha2/dataform_client.go @@ -1553,6 +1553,7 @@ func (c *restClient) ListRepositories(ctx context.Context, req *dataformpb.ListR baseUrl.Path += fmt.Sprintf("/v1alpha2/%v/repositories", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1632,6 +1633,11 @@ func (c *restClient) GetRepository(ctx context.Context, req *dataformpb.GetRepos } baseUrl.Path += fmt.Sprintf("/v1alpha2/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1693,6 +1699,7 @@ func (c *restClient) CreateRepository(ctx context.Context, req *dataformpb.Creat baseUrl.Path += fmt.Sprintf("/v1alpha2/%v/repositories", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("repositoryId", fmt.Sprintf("%v", req.GetRepositoryId())) baseUrl.RawQuery = params.Encode() @@ -1758,6 +1765,7 @@ func (c *restClient) UpdateRepository(ctx context.Context, req *dataformpb.Updat baseUrl.Path += fmt.Sprintf("/v1alpha2/%v", req.GetRepository().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -1822,6 +1830,7 @@ func (c *restClient) DeleteRepository(ctx context.Context, req *dataformpb.Delet baseUrl.Path += fmt.Sprintf("/v1alpha2/%v", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetForce() { params.Add("force", fmt.Sprintf("%v", req.GetForce())) } @@ -1863,6 +1872,11 @@ func (c *restClient) FetchRemoteBranches(ctx context.Context, req *dataformpb.Fe } baseUrl.Path += fmt.Sprintf("/v1alpha2/%v:fetchRemoteBranches", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1930,6 +1944,7 @@ func (c *restClient) ListWorkspaces(ctx context.Context, req *dataformpb.ListWor baseUrl.Path += fmt.Sprintf("/v1alpha2/%v/workspaces", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -2009,6 +2024,11 @@ func (c *restClient) GetWorkspace(ctx context.Context, req *dataformpb.GetWorksp } baseUrl.Path += fmt.Sprintf("/v1alpha2/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2070,6 +2090,7 @@ func (c *restClient) CreateWorkspace(ctx context.Context, req *dataformpb.Create baseUrl.Path += fmt.Sprintf("/v1alpha2/%v/workspaces", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("workspaceId", fmt.Sprintf("%v", req.GetWorkspaceId())) baseUrl.RawQuery = params.Encode() @@ -2127,6 +2148,11 @@ func (c *restClient) DeleteWorkspace(ctx context.Context, req *dataformpb.Delete } baseUrl.Path += fmt.Sprintf("/v1alpha2/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2168,6 +2194,11 @@ func (c *restClient) InstallNpmPackages(ctx context.Context, req *dataformpb.Ins } baseUrl.Path += fmt.Sprintf("/v1alpha2/%v:installNpmPackages", req.GetWorkspace()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "workspace", url.QueryEscape(req.GetWorkspace()))) @@ -2227,6 +2258,11 @@ func (c *restClient) PullGitCommits(ctx context.Context, req *dataformpb.PullGit } baseUrl.Path += fmt.Sprintf("/v1alpha2/%v:pull", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2268,6 +2304,11 @@ func (c *restClient) PushGitCommits(ctx context.Context, req *dataformpb.PushGit } baseUrl.Path += fmt.Sprintf("/v1alpha2/%v:push", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2303,6 +2344,11 @@ func (c *restClient) FetchFileGitStatuses(ctx context.Context, req *dataformpb.F } baseUrl.Path += fmt.Sprintf("/v1alpha2/%v:fetchFileGitStatuses", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2357,6 +2403,7 @@ func (c *restClient) FetchGitAheadBehind(ctx context.Context, req *dataformpb.Fe baseUrl.Path += fmt.Sprintf("/v1alpha2/%v:fetchGitAheadBehind", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetRemoteBranch() != "" { params.Add("remoteBranch", fmt.Sprintf("%v", req.GetRemoteBranch())) } @@ -2422,6 +2469,11 @@ func (c *restClient) CommitWorkspaceChanges(ctx context.Context, req *dataformpb } baseUrl.Path += fmt.Sprintf("/v1alpha2/%v:commit", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2463,6 +2515,11 @@ func (c *restClient) ResetWorkspaceChanges(ctx context.Context, req *dataformpb. } baseUrl.Path += fmt.Sprintf("/v1alpha2/%v:reset", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2499,6 +2556,7 @@ func (c *restClient) FetchFileDiff(ctx context.Context, req *dataformpb.FetchFil baseUrl.Path += fmt.Sprintf("/v1alpha2/%v:fetchFileDiff", req.GetWorkspace()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("path", fmt.Sprintf("%v", req.GetPath())) baseUrl.RawQuery = params.Encode() @@ -2570,6 +2628,7 @@ func (c *restClient) QueryDirectoryContents(ctx context.Context, req *dataformpb baseUrl.Path += fmt.Sprintf("/v1alpha2/%v:queryDirectoryContents", req.GetWorkspace()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -2652,6 +2711,11 @@ func (c *restClient) MakeDirectory(ctx context.Context, req *dataformpb.MakeDire } baseUrl.Path += fmt.Sprintf("/v1alpha2/%v:makeDirectory", req.GetWorkspace()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "workspace", url.QueryEscape(req.GetWorkspace()))) @@ -2711,6 +2775,11 @@ func (c *restClient) RemoveDirectory(ctx context.Context, req *dataformpb.Remove } baseUrl.Path += fmt.Sprintf("/v1alpha2/%v:removeDirectory", req.GetWorkspace()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "workspace", url.QueryEscape(req.GetWorkspace()))) @@ -2753,6 +2822,11 @@ func (c *restClient) MoveDirectory(ctx context.Context, req *dataformpb.MoveDire } baseUrl.Path += fmt.Sprintf("/v1alpha2/%v:moveDirectory", req.GetWorkspace()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "workspace", url.QueryEscape(req.GetWorkspace()))) @@ -2807,6 +2881,7 @@ func (c *restClient) ReadFile(ctx context.Context, req *dataformpb.ReadFileReque baseUrl.Path += fmt.Sprintf("/v1alpha2/%v:readFile", req.GetWorkspace()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("path", fmt.Sprintf("%v", req.GetPath())) baseUrl.RawQuery = params.Encode() @@ -2870,6 +2945,11 @@ func (c *restClient) RemoveFile(ctx context.Context, req *dataformpb.RemoveFileR } baseUrl.Path += fmt.Sprintf("/v1alpha2/%v:removeFile", req.GetWorkspace()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "workspace", url.QueryEscape(req.GetWorkspace()))) @@ -2911,6 +2991,11 @@ func (c *restClient) MoveFile(ctx context.Context, req *dataformpb.MoveFileReque } baseUrl.Path += fmt.Sprintf("/v1alpha2/%v:moveFile", req.GetWorkspace()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "workspace", url.QueryEscape(req.GetWorkspace()))) @@ -2970,6 +3055,11 @@ func (c *restClient) WriteFile(ctx context.Context, req *dataformpb.WriteFileReq } baseUrl.Path += fmt.Sprintf("/v1alpha2/%v:writeFile", req.GetWorkspace()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "workspace", url.QueryEscape(req.GetWorkspace()))) @@ -3037,6 +3127,7 @@ func (c *restClient) ListCompilationResults(ctx context.Context, req *dataformpb baseUrl.Path += fmt.Sprintf("/v1alpha2/%v/compilationResults", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -3110,6 +3201,11 @@ func (c *restClient) GetCompilationResult(ctx context.Context, req *dataformpb.G } baseUrl.Path += fmt.Sprintf("/v1alpha2/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -3170,6 +3266,11 @@ func (c *restClient) CreateCompilationResult(ctx context.Context, req *dataformp } baseUrl.Path += fmt.Sprintf("/v1alpha2/%v/compilationResults", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -3237,6 +3338,7 @@ func (c *restClient) QueryCompilationResultActions(ctx context.Context, req *dat baseUrl.Path += fmt.Sprintf("/v1alpha2/%v:query", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -3327,6 +3429,7 @@ func (c *restClient) ListWorkflowInvocations(ctx context.Context, req *dataformp baseUrl.Path += fmt.Sprintf("/v1alpha2/%v/workflowInvocations", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -3400,6 +3503,11 @@ func (c *restClient) GetWorkflowInvocation(ctx context.Context, req *dataformpb. } baseUrl.Path += fmt.Sprintf("/v1alpha2/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -3460,6 +3568,11 @@ func (c *restClient) CreateWorkflowInvocation(ctx context.Context, req *dataform } baseUrl.Path += fmt.Sprintf("/v1alpha2/%v/workflowInvocations", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -3513,6 +3626,11 @@ func (c *restClient) DeleteWorkflowInvocation(ctx context.Context, req *dataform } baseUrl.Path += fmt.Sprintf("/v1alpha2/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -3554,6 +3672,11 @@ func (c *restClient) CancelWorkflowInvocation(ctx context.Context, req *dataform } baseUrl.Path += fmt.Sprintf("/v1alpha2/%v:cancel", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -3603,6 +3726,7 @@ func (c *restClient) QueryWorkflowInvocationActions(ctx context.Context, req *da baseUrl.Path += fmt.Sprintf("/v1alpha2/%v:query", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -3676,6 +3800,11 @@ func (c *restClient) GetLocation(ctx context.Context, req *locationpb.GetLocatio } baseUrl.Path += fmt.Sprintf("/v1alpha2/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -3743,6 +3872,7 @@ func (c *restClient) ListLocations(ctx context.Context, req *locationpb.ListLoca baseUrl.Path += fmt.Sprintf("/v1alpha2/%v/locations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -3821,6 +3951,7 @@ func (c *restClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRe baseUrl.Path += fmt.Sprintf("/v1alpha2/%v:getIamPolicy", req.GetResource()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetOptions().GetRequestedPolicyVersion() != 0 { params.Add("options.requestedPolicyVersion", fmt.Sprintf("%v", req.GetOptions().GetRequestedPolicyVersion())) } @@ -3890,6 +4021,11 @@ func (c *restClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRe } baseUrl.Path += fmt.Sprintf("/v1alpha2/%v:setIamPolicy", req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) @@ -3955,6 +4091,11 @@ func (c *restClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamP } baseUrl.Path += fmt.Sprintf("/v1alpha2/%v:testIamPermissions", req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) diff --git a/dataform/apiv1alpha2/dataformpb/dataform.pb.go b/dataform/apiv1alpha2/dataformpb/dataform.pb.go index 08cec84b4366..99c25f70ad65 100644 --- a/dataform/apiv1alpha2/dataformpb/dataform.pb.go +++ b/dataform/apiv1alpha2/dataformpb/dataform.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dataform/v1alpha2/dataform.proto package dataformpb @@ -2830,7 +2830,6 @@ type CompilationResult struct { // Output only. The compilation result's name. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Types that are assignable to Source: - // // *CompilationResult_GitCommitish // *CompilationResult_Workspace Source isCompilationResult_Source `protobuf_oneof:"source"` @@ -3348,7 +3347,6 @@ type CompilationResultAction struct { // to the workspace root. FilePath string `protobuf:"bytes,3,opt,name=file_path,json=filePath,proto3" json:"file_path,omitempty"` // Types that are assignable to CompiledObject: - // // *CompilationResultAction_Relation_ // *CompilationResultAction_Operations_ // *CompilationResultAction_Assertion_ @@ -4427,7 +4425,6 @@ type QueryDirectoryContentsResponse_DirectoryEntry struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Entry: - // // *QueryDirectoryContentsResponse_DirectoryEntry_File // *QueryDirectoryContentsResponse_DirectoryEntry_Directory Entry isQueryDirectoryContentsResponse_DirectoryEntry_Entry `protobuf_oneof:"entry"` diff --git a/dataform/apiv1beta1/dataform_client.go b/dataform/apiv1beta1/dataform_client.go index 1cecfb6123fb..301a790c3215 100644 --- a/dataform/apiv1beta1/dataform_client.go +++ b/dataform/apiv1beta1/dataform_client.go @@ -1460,6 +1460,7 @@ func (c *restClient) ListRepositories(ctx context.Context, req *dataformpb.ListR baseUrl.Path += fmt.Sprintf("/v1beta1/%v/repositories", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1539,6 +1540,11 @@ func (c *restClient) GetRepository(ctx context.Context, req *dataformpb.GetRepos } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1600,6 +1606,7 @@ func (c *restClient) CreateRepository(ctx context.Context, req *dataformpb.Creat baseUrl.Path += fmt.Sprintf("/v1beta1/%v/repositories", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("repositoryId", fmt.Sprintf("%v", req.GetRepositoryId())) baseUrl.RawQuery = params.Encode() @@ -1665,6 +1672,7 @@ func (c *restClient) UpdateRepository(ctx context.Context, req *dataformpb.Updat baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetRepository().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -1729,6 +1737,7 @@ func (c *restClient) DeleteRepository(ctx context.Context, req *dataformpb.Delet baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetForce() { params.Add("force", fmt.Sprintf("%v", req.GetForce())) } @@ -1770,6 +1779,11 @@ func (c *restClient) FetchRemoteBranches(ctx context.Context, req *dataformpb.Fe } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:fetchRemoteBranches", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1837,6 +1851,7 @@ func (c *restClient) ListWorkspaces(ctx context.Context, req *dataformpb.ListWor baseUrl.Path += fmt.Sprintf("/v1beta1/%v/workspaces", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1916,6 +1931,11 @@ func (c *restClient) GetWorkspace(ctx context.Context, req *dataformpb.GetWorksp } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1977,6 +1997,7 @@ func (c *restClient) CreateWorkspace(ctx context.Context, req *dataformpb.Create baseUrl.Path += fmt.Sprintf("/v1beta1/%v/workspaces", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("workspaceId", fmt.Sprintf("%v", req.GetWorkspaceId())) baseUrl.RawQuery = params.Encode() @@ -2034,6 +2055,11 @@ func (c *restClient) DeleteWorkspace(ctx context.Context, req *dataformpb.Delete } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2075,6 +2101,11 @@ func (c *restClient) InstallNpmPackages(ctx context.Context, req *dataformpb.Ins } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:installNpmPackages", req.GetWorkspace()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "workspace", url.QueryEscape(req.GetWorkspace()))) @@ -2134,6 +2165,11 @@ func (c *restClient) PullGitCommits(ctx context.Context, req *dataformpb.PullGit } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:pull", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2175,6 +2211,11 @@ func (c *restClient) PushGitCommits(ctx context.Context, req *dataformpb.PushGit } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:push", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2210,6 +2251,11 @@ func (c *restClient) FetchFileGitStatuses(ctx context.Context, req *dataformpb.F } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:fetchFileGitStatuses", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2264,6 +2310,7 @@ func (c *restClient) FetchGitAheadBehind(ctx context.Context, req *dataformpb.Fe baseUrl.Path += fmt.Sprintf("/v1beta1/%v:fetchGitAheadBehind", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetRemoteBranch() != "" { params.Add("remoteBranch", fmt.Sprintf("%v", req.GetRemoteBranch())) } @@ -2329,6 +2376,11 @@ func (c *restClient) CommitWorkspaceChanges(ctx context.Context, req *dataformpb } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:commit", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2370,6 +2422,11 @@ func (c *restClient) ResetWorkspaceChanges(ctx context.Context, req *dataformpb. } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:reset", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2406,6 +2463,7 @@ func (c *restClient) FetchFileDiff(ctx context.Context, req *dataformpb.FetchFil baseUrl.Path += fmt.Sprintf("/v1beta1/%v:fetchFileDiff", req.GetWorkspace()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("path", fmt.Sprintf("%v", req.GetPath())) baseUrl.RawQuery = params.Encode() @@ -2477,6 +2535,7 @@ func (c *restClient) QueryDirectoryContents(ctx context.Context, req *dataformpb baseUrl.Path += fmt.Sprintf("/v1beta1/%v:queryDirectoryContents", req.GetWorkspace()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -2559,6 +2618,11 @@ func (c *restClient) MakeDirectory(ctx context.Context, req *dataformpb.MakeDire } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:makeDirectory", req.GetWorkspace()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "workspace", url.QueryEscape(req.GetWorkspace()))) @@ -2618,6 +2682,11 @@ func (c *restClient) RemoveDirectory(ctx context.Context, req *dataformpb.Remove } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:removeDirectory", req.GetWorkspace()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "workspace", url.QueryEscape(req.GetWorkspace()))) @@ -2660,6 +2729,11 @@ func (c *restClient) MoveDirectory(ctx context.Context, req *dataformpb.MoveDire } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:moveDirectory", req.GetWorkspace()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "workspace", url.QueryEscape(req.GetWorkspace()))) @@ -2714,6 +2788,7 @@ func (c *restClient) ReadFile(ctx context.Context, req *dataformpb.ReadFileReque baseUrl.Path += fmt.Sprintf("/v1beta1/%v:readFile", req.GetWorkspace()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("path", fmt.Sprintf("%v", req.GetPath())) baseUrl.RawQuery = params.Encode() @@ -2777,6 +2852,11 @@ func (c *restClient) RemoveFile(ctx context.Context, req *dataformpb.RemoveFileR } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:removeFile", req.GetWorkspace()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "workspace", url.QueryEscape(req.GetWorkspace()))) @@ -2818,6 +2898,11 @@ func (c *restClient) MoveFile(ctx context.Context, req *dataformpb.MoveFileReque } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:moveFile", req.GetWorkspace()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "workspace", url.QueryEscape(req.GetWorkspace()))) @@ -2877,6 +2962,11 @@ func (c *restClient) WriteFile(ctx context.Context, req *dataformpb.WriteFileReq } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:writeFile", req.GetWorkspace()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "workspace", url.QueryEscape(req.GetWorkspace()))) @@ -2944,6 +3034,7 @@ func (c *restClient) ListCompilationResults(ctx context.Context, req *dataformpb baseUrl.Path += fmt.Sprintf("/v1beta1/%v/compilationResults", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -3017,6 +3108,11 @@ func (c *restClient) GetCompilationResult(ctx context.Context, req *dataformpb.G } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -3077,6 +3173,11 @@ func (c *restClient) CreateCompilationResult(ctx context.Context, req *dataformp } baseUrl.Path += fmt.Sprintf("/v1beta1/%v/compilationResults", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -3144,6 +3245,7 @@ func (c *restClient) QueryCompilationResultActions(ctx context.Context, req *dat baseUrl.Path += fmt.Sprintf("/v1beta1/%v:query", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -3234,6 +3336,7 @@ func (c *restClient) ListWorkflowInvocations(ctx context.Context, req *dataformp baseUrl.Path += fmt.Sprintf("/v1beta1/%v/workflowInvocations", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -3307,6 +3410,11 @@ func (c *restClient) GetWorkflowInvocation(ctx context.Context, req *dataformpb. } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -3367,6 +3475,11 @@ func (c *restClient) CreateWorkflowInvocation(ctx context.Context, req *dataform } baseUrl.Path += fmt.Sprintf("/v1beta1/%v/workflowInvocations", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -3420,6 +3533,11 @@ func (c *restClient) DeleteWorkflowInvocation(ctx context.Context, req *dataform } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -3461,6 +3579,11 @@ func (c *restClient) CancelWorkflowInvocation(ctx context.Context, req *dataform } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:cancel", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -3510,6 +3633,7 @@ func (c *restClient) QueryWorkflowInvocationActions(ctx context.Context, req *da baseUrl.Path += fmt.Sprintf("/v1beta1/%v:query", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -3583,6 +3707,11 @@ func (c *restClient) GetLocation(ctx context.Context, req *locationpb.GetLocatio } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -3650,6 +3779,7 @@ func (c *restClient) ListLocations(ctx context.Context, req *locationpb.ListLoca baseUrl.Path += fmt.Sprintf("/v1beta1/%v/locations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/dataform/apiv1beta1/dataformpb/dataform.pb.go b/dataform/apiv1beta1/dataformpb/dataform.pb.go index 4923e6d6c2eb..0fe154451a0b 100644 --- a/dataform/apiv1beta1/dataformpb/dataform.pb.go +++ b/dataform/apiv1beta1/dataformpb/dataform.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dataform/v1beta1/dataform.proto package dataformpb @@ -2830,7 +2830,6 @@ type CompilationResult struct { // Output only. The compilation result's name. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Types that are assignable to Source: - // // *CompilationResult_GitCommitish // *CompilationResult_Workspace Source isCompilationResult_Source `protobuf_oneof:"source"` @@ -3348,7 +3347,6 @@ type CompilationResultAction struct { // to the workspace root. FilePath string `protobuf:"bytes,3,opt,name=file_path,json=filePath,proto3" json:"file_path,omitempty"` // Types that are assignable to CompiledObject: - // // *CompilationResultAction_Relation_ // *CompilationResultAction_Operations_ // *CompilationResultAction_Assertion_ @@ -4428,7 +4426,6 @@ type QueryDirectoryContentsResponse_DirectoryEntry struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Entry: - // // *QueryDirectoryContentsResponse_DirectoryEntry_File // *QueryDirectoryContentsResponse_DirectoryEntry_Directory Entry isQueryDirectoryContentsResponse_DirectoryEntry_Entry `protobuf_oneof:"entry"` diff --git a/datafusion/apiv1/data_fusion_client.go b/datafusion/apiv1/data_fusion_client.go index 745e05c69f17..225d5a486705 100644 --- a/datafusion/apiv1/data_fusion_client.go +++ b/datafusion/apiv1/data_fusion_client.go @@ -17,9 +17,12 @@ package datafusion import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,13 +30,16 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -74,6 +80,18 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + ListAvailableVersions: []gax.CallOption{}, + ListInstances: []gax.CallOption{}, + GetInstance: []gax.CallOption{}, + CreateInstance: []gax.CallOption{}, + DeleteInstance: []gax.CallOption{}, + UpdateInstance: []gax.CallOption{}, + RestartInstance: []gax.CallOption{}, + } +} + // internalClient is an interface that defines the methods available from Cloud Data Fusion API. type internalClient interface { Close() error @@ -294,6 +312,91 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new data fusion rest client. +// +// Service for creating and managing Data Fusion instances. +// Data Fusion enables ETL developers to build code-free, data integration +// pipelines via a point-and-click UI. +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://datafusion.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://datafusion.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://datafusion.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) ListAvailableVersions(ctx context.Context, req *datafusionpb.ListAvailableVersionsRequest, opts ...gax.CallOption) *VersionIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -502,9 +605,531 @@ func (c *gRPCClient) RestartInstance(ctx context.Context, req *datafusionpb.Rest }, nil } +// ListAvailableVersions lists possible versions for Data Fusion instances in the specified project +// and location. +func (c *restClient) ListAvailableVersions(ctx context.Context, req *datafusionpb.ListAvailableVersionsRequest, opts ...gax.CallOption) *VersionIterator { + it := &VersionIterator{} + req = proto.Clone(req).(*datafusionpb.ListAvailableVersionsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*datafusionpb.Version, string, error) { + resp := &datafusionpb.ListAvailableVersionsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/versions", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetLatestPatchOnly() { + params.Add("latestPatchOnly", fmt.Sprintf("%v", req.GetLatestPatchOnly())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetAvailableVersions(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// ListInstances lists Data Fusion instances in the specified project and location. +func (c *restClient) ListInstances(ctx context.Context, req *datafusionpb.ListInstancesRequest, opts ...gax.CallOption) *InstanceIterator { + it := &InstanceIterator{} + req = proto.Clone(req).(*datafusionpb.ListInstancesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*datafusionpb.Instance, string, error) { + resp := &datafusionpb.ListInstancesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/instances", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetInstances(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetInstance gets details of a single Data Fusion instance. +func (c *restClient) GetInstance(ctx context.Context, req *datafusionpb.GetInstanceRequest, opts ...gax.CallOption) (*datafusionpb.Instance, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetInstance[0:len((*c.CallOptions).GetInstance):len((*c.CallOptions).GetInstance)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &datafusionpb.Instance{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateInstance creates a new Data Fusion instance in the specified project and location. +func (c *restClient) CreateInstance(ctx context.Context, req *datafusionpb.CreateInstanceRequest, opts ...gax.CallOption) (*CreateInstanceOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetInstance() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/instances", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("instanceId", fmt.Sprintf("%v", req.GetInstanceId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteInstance deletes a single Date Fusion instance. +func (c *restClient) DeleteInstance(ctx context.Context, req *datafusionpb.DeleteInstanceRequest, opts ...gax.CallOption) (*DeleteInstanceOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateInstance updates a single Data Fusion instance. +func (c *restClient) UpdateInstance(ctx context.Context, req *datafusionpb.UpdateInstanceRequest, opts ...gax.CallOption) (*UpdateInstanceOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetInstance() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetInstance().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "instance.name", url.QueryEscape(req.GetInstance().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// RestartInstance restart a single Data Fusion instance. +// At the end of an operation instance is fully restarted. +func (c *restClient) RestartInstance(ctx context.Context, req *datafusionpb.RestartInstanceRequest, opts ...gax.CallOption) (*RestartInstanceOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:restart", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &RestartInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + // CreateInstanceOperation manages a long-running operation from CreateInstance. type CreateInstanceOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateInstanceOperation returns a new CreateInstanceOperation from a given name. @@ -515,10 +1140,21 @@ func (c *gRPCClient) CreateInstanceOperation(name string) *CreateInstanceOperati } } +// CreateInstanceOperation returns a new CreateInstanceOperation from a given name. +// The name must be that of a previously created CreateInstanceOperation, possibly from a different process. +func (c *restClient) CreateInstanceOperation(name string) *CreateInstanceOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*datafusionpb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp datafusionpb.Instance if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -536,6 +1172,7 @@ func (op *CreateInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOpt // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateInstanceOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*datafusionpb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp datafusionpb.Instance if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -573,7 +1210,8 @@ func (op *CreateInstanceOperation) Name() string { // DeleteInstanceOperation manages a long-running operation from DeleteInstance. type DeleteInstanceOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteInstanceOperation returns a new DeleteInstanceOperation from a given name. @@ -584,10 +1222,21 @@ func (c *gRPCClient) DeleteInstanceOperation(name string) *DeleteInstanceOperati } } +// DeleteInstanceOperation returns a new DeleteInstanceOperation from a given name. +// The name must be that of a previously created DeleteInstanceOperation, possibly from a different process. +func (c *restClient) DeleteInstanceOperation(name string) *DeleteInstanceOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -601,6 +1250,7 @@ func (op *DeleteInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOpt // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteInstanceOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -631,7 +1281,8 @@ func (op *DeleteInstanceOperation) Name() string { // RestartInstanceOperation manages a long-running operation from RestartInstance. type RestartInstanceOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // RestartInstanceOperation returns a new RestartInstanceOperation from a given name. @@ -642,10 +1293,21 @@ func (c *gRPCClient) RestartInstanceOperation(name string) *RestartInstanceOpera } } +// RestartInstanceOperation returns a new RestartInstanceOperation from a given name. +// The name must be that of a previously created RestartInstanceOperation, possibly from a different process. +func (c *restClient) RestartInstanceOperation(name string) *RestartInstanceOperation { + override := fmt.Sprintf("/v1/%s", name) + return &RestartInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *RestartInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*datafusionpb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp datafusionpb.Instance if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -663,6 +1325,7 @@ func (op *RestartInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOp // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *RestartInstanceOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*datafusionpb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp datafusionpb.Instance if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -700,7 +1363,8 @@ func (op *RestartInstanceOperation) Name() string { // UpdateInstanceOperation manages a long-running operation from UpdateInstance. type UpdateInstanceOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateInstanceOperation returns a new UpdateInstanceOperation from a given name. @@ -711,10 +1375,21 @@ func (c *gRPCClient) UpdateInstanceOperation(name string) *UpdateInstanceOperati } } +// UpdateInstanceOperation returns a new UpdateInstanceOperation from a given name. +// The name must be that of a previously created UpdateInstanceOperation, possibly from a different process. +func (c *restClient) UpdateInstanceOperation(name string) *UpdateInstanceOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*datafusionpb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp datafusionpb.Instance if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -732,6 +1407,7 @@ func (op *UpdateInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOpt // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateInstanceOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*datafusionpb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp datafusionpb.Instance if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/datafusion/apiv1/data_fusion_client_example_test.go b/datafusion/apiv1/data_fusion_client_example_test.go index 18a7fb607067..d98442bd9175 100644 --- a/datafusion/apiv1/data_fusion_client_example_test.go +++ b/datafusion/apiv1/data_fusion_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := datafusion.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_ListAvailableVersions() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/datafusion/apiv1/datafusionpb/datafusion.pb.go b/datafusion/apiv1/datafusionpb/datafusion.pb.go index 49879b5262bd..9b14d0b7fcb6 100644 --- a/datafusion/apiv1/datafusionpb/datafusion.pb.go +++ b/datafusion/apiv1/datafusionpb/datafusion.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/datafusion/v1/datafusion.proto package datafusionpb diff --git a/datafusion/apiv1/doc.go b/datafusion/apiv1/doc.go index acf398ffd061..4550aab86c6d 100644 --- a/datafusion/apiv1/doc.go +++ b/datafusion/apiv1/doc.go @@ -92,6 +92,8 @@ package datafusion // import "cloud.google.com/go/datafusion/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -180,3 +182,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/datafusion/apiv1/gapic_metadata.json b/datafusion/apiv1/gapic_metadata.json index ab1e6146719c..94112c3e61ae 100644 --- a/datafusion/apiv1/gapic_metadata.json +++ b/datafusion/apiv1/gapic_metadata.json @@ -46,6 +46,46 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "CreateInstance": { + "methods": [ + "CreateInstance" + ] + }, + "DeleteInstance": { + "methods": [ + "DeleteInstance" + ] + }, + "GetInstance": { + "methods": [ + "GetInstance" + ] + }, + "ListAvailableVersions": { + "methods": [ + "ListAvailableVersions" + ] + }, + "ListInstances": { + "methods": [ + "ListInstances" + ] + }, + "RestartInstance": { + "methods": [ + "RestartInstance" + ] + }, + "UpdateInstance": { + "methods": [ + "UpdateInstance" + ] + } + } } } } diff --git a/datalabeling/apiv1beta1/data_labeling_client.go b/datalabeling/apiv1beta1/data_labeling_client.go index ec12710d0318..e83058c9180a 100644 --- a/datalabeling/apiv1beta1/data_labeling_client.go +++ b/datalabeling/apiv1beta1/data_labeling_client.go @@ -2056,6 +2056,11 @@ func (c *restClient) CreateDataset(ctx context.Context, req *datalabelingpb.Crea } baseUrl.Path += fmt.Sprintf("/v1beta1/%v/datasets", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -2109,6 +2114,11 @@ func (c *restClient) GetDataset(ctx context.Context, req *datalabelingpb.GetData } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2176,6 +2186,7 @@ func (c *restClient) ListDatasets(ctx context.Context, req *datalabelingpb.ListD baseUrl.Path += fmt.Sprintf("/v1beta1/%v/datasets", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -2252,6 +2263,11 @@ func (c *restClient) DeleteDataset(ctx context.Context, req *datalabelingpb.Dele } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2297,6 +2313,11 @@ func (c *restClient) ImportData(ctx context.Context, req *datalabelingpb.ImportD } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:importData", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2360,6 +2381,11 @@ func (c *restClient) ExportData(ctx context.Context, req *datalabelingpb.ExportD } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:exportData", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2418,6 +2444,11 @@ func (c *restClient) GetDataItem(ctx context.Context, req *datalabelingpb.GetDat } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2486,6 +2517,7 @@ func (c *restClient) ListDataItems(ctx context.Context, req *datalabelingpb.List baseUrl.Path += fmt.Sprintf("/v1beta1/%v/dataItems", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -2562,6 +2594,11 @@ func (c *restClient) GetAnnotatedDataset(ctx context.Context, req *datalabelingp } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2629,6 +2666,7 @@ func (c *restClient) ListAnnotatedDatasets(ctx context.Context, req *datalabelin baseUrl.Path += fmt.Sprintf("/v1beta1/%v/annotatedDatasets", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -2705,6 +2743,11 @@ func (c *restClient) DeleteAnnotatedDataset(ctx context.Context, req *datalabeli } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2747,6 +2790,11 @@ func (c *restClient) LabelImage(ctx context.Context, req *datalabelingpb.LabelIm } baseUrl.Path += fmt.Sprintf("/v1beta1/%v/image:label", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -2811,6 +2859,11 @@ func (c *restClient) LabelVideo(ctx context.Context, req *datalabelingpb.LabelVi } baseUrl.Path += fmt.Sprintf("/v1beta1/%v/video:label", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -2875,6 +2928,11 @@ func (c *restClient) LabelText(ctx context.Context, req *datalabelingpb.LabelTex } baseUrl.Path += fmt.Sprintf("/v1beta1/%v/text:label", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -2933,6 +2991,7 @@ func (c *restClient) GetExample(ctx context.Context, req *datalabelingpb.GetExam baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -3006,6 +3065,7 @@ func (c *restClient) ListExamples(ctx context.Context, req *datalabelingpb.ListE baseUrl.Path += fmt.Sprintf("/v1beta1/%v/examples", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -3088,6 +3148,11 @@ func (c *restClient) CreateAnnotationSpecSet(ctx context.Context, req *datalabel } baseUrl.Path += fmt.Sprintf("/v1beta1/%v/annotationSpecSets", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -3141,6 +3206,11 @@ func (c *restClient) GetAnnotationSpecSet(ctx context.Context, req *datalabeling } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -3208,6 +3278,7 @@ func (c *restClient) ListAnnotationSpecSets(ctx context.Context, req *datalabeli baseUrl.Path += fmt.Sprintf("/v1beta1/%v/annotationSpecSets", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -3284,6 +3355,11 @@ func (c *restClient) DeleteAnnotationSpecSet(ctx context.Context, req *datalabel } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -3325,6 +3401,11 @@ func (c *restClient) CreateInstruction(ctx context.Context, req *datalabelingpb. } baseUrl.Path += fmt.Sprintf("/v1beta1/%v/instructions", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -3382,6 +3463,11 @@ func (c *restClient) GetInstruction(ctx context.Context, req *datalabelingpb.Get } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -3449,6 +3535,7 @@ func (c *restClient) ListInstructions(ctx context.Context, req *datalabelingpb.L baseUrl.Path += fmt.Sprintf("/v1beta1/%v/instructions", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -3525,6 +3612,11 @@ func (c *restClient) DeleteInstruction(ctx context.Context, req *datalabelingpb. } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -3561,6 +3653,11 @@ func (c *restClient) GetEvaluation(ctx context.Context, req *datalabelingpb.GetE } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -3628,6 +3725,7 @@ func (c *restClient) SearchEvaluations(ctx context.Context, req *datalabelingpb. baseUrl.Path += fmt.Sprintf("/v1beta1/%v/evaluations:search", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -3725,6 +3823,11 @@ func (c *restClient) SearchExampleComparisons(ctx context.Context, req *datalabe } baseUrl.Path += fmt.Sprintf("/v1beta1/%v/exampleComparisons:search", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { @@ -3795,6 +3898,11 @@ func (c *restClient) CreateEvaluationJob(ctx context.Context, req *datalabelingp } baseUrl.Path += fmt.Sprintf("/v1beta1/%v/evaluationJobs", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -3861,6 +3969,7 @@ func (c *restClient) UpdateEvaluationJob(ctx context.Context, req *datalabelingp baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetEvaluationJob().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -3924,6 +4033,11 @@ func (c *restClient) GetEvaluationJob(ctx context.Context, req *datalabelingpb.G } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -3984,6 +4098,11 @@ func (c *restClient) PauseEvaluationJob(ctx context.Context, req *datalabelingpb } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:pause", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -4026,6 +4145,11 @@ func (c *restClient) ResumeEvaluationJob(ctx context.Context, req *datalabelingp } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:resume", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -4061,6 +4185,11 @@ func (c *restClient) DeleteEvaluationJob(ctx context.Context, req *datalabelingp } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -4111,6 +4240,7 @@ func (c *restClient) ListEvaluationJobs(ctx context.Context, req *datalabelingpb baseUrl.Path += fmt.Sprintf("/v1beta1/%v/evaluationJobs", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/datalabeling/apiv1beta1/datalabelingpb/annotation.pb.go b/datalabeling/apiv1beta1/datalabelingpb/annotation.pb.go index 45c7884b93f5..44dd5d1c77b3 100644 --- a/datalabeling/apiv1beta1/datalabelingpb/annotation.pb.go +++ b/datalabeling/apiv1beta1/datalabelingpb/annotation.pb.go @@ -15,8 +15,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/datalabeling/v1beta1/annotation.proto package datalabelingpb @@ -332,7 +332,6 @@ type AnnotationValue struct { unknownFields protoimpl.UnknownFields // Types that are assignable to ValueType: - // // *AnnotationValue_ImageClassificationAnnotation // *AnnotationValue_ImageBoundingPolyAnnotation // *AnnotationValue_ImagePolylineAnnotation @@ -795,7 +794,6 @@ type ImageBoundingPolyAnnotation struct { // four points. // // Types that are assignable to BoundedArea: - // // *ImageBoundingPolyAnnotation_BoundingPoly // *ImageBoundingPolyAnnotation_NormalizedBoundingPoly BoundedArea isImageBoundingPolyAnnotation_BoundedArea `protobuf_oneof:"bounded_area"` @@ -985,7 +983,6 @@ type ImagePolylineAnnotation struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Poly: - // // *ImagePolylineAnnotation_Polyline // *ImagePolylineAnnotation_NormalizedPolyline Poly isImagePolylineAnnotation_Poly `protobuf_oneof:"poly"` @@ -1430,7 +1427,6 @@ type ObjectTrackingFrame struct { // The bounding box location of this object track for the frame. // // Types that are assignable to BoundedArea: - // // *ObjectTrackingFrame_BoundingPoly // *ObjectTrackingFrame_NormalizedBoundingPoly BoundedArea isObjectTrackingFrame_BoundedArea `protobuf_oneof:"bounded_area"` diff --git a/datalabeling/apiv1beta1/datalabelingpb/annotation_spec_set.pb.go b/datalabeling/apiv1beta1/datalabelingpb/annotation_spec_set.pb.go index 77edd29958a3..f813232db2ba 100644 --- a/datalabeling/apiv1beta1/datalabelingpb/annotation_spec_set.pb.go +++ b/datalabeling/apiv1beta1/datalabelingpb/annotation_spec_set.pb.go @@ -15,8 +15,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/datalabeling/v1beta1/annotation_spec_set.proto package datalabelingpb diff --git a/datalabeling/apiv1beta1/datalabelingpb/data_labeling_service.pb.go b/datalabeling/apiv1beta1/datalabelingpb/data_labeling_service.pb.go index d854ae34266b..02fb2e381d1b 100644 --- a/datalabeling/apiv1beta1/datalabelingpb/data_labeling_service.pb.go +++ b/datalabeling/apiv1beta1/datalabelingpb/data_labeling_service.pb.go @@ -15,8 +15,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/datalabeling/v1beta1/data_labeling_service.proto package datalabelingpb @@ -1129,7 +1129,6 @@ type LabelImageRequest struct { // match the selected feature. // // Types that are assignable to RequestConfig: - // // *LabelImageRequest_ImageClassificationConfig // *LabelImageRequest_BoundingPolyConfig // *LabelImageRequest_PolylineConfig @@ -1282,7 +1281,6 @@ type LabelVideoRequest struct { // match the selected feature. // // Types that are assignable to RequestConfig: - // // *LabelVideoRequest_VideoClassificationConfig // *LabelVideoRequest_ObjectDetectionConfig // *LabelVideoRequest_ObjectTrackingConfig @@ -1435,7 +1433,6 @@ type LabelTextRequest struct { // match the selected feature. // // Types that are assignable to RequestConfig: - // // *LabelTextRequest_TextClassificationConfig // *LabelTextRequest_TextEntityExtractionConfig RequestConfig isLabelTextRequest_RequestConfig `protobuf_oneof:"request_config"` @@ -2410,22 +2407,22 @@ type SearchEvaluationsRequest struct { Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // Optional. To search evaluations, you can filter by the following: // - // - evaluation_job.evaluation_job_id (the last part of - // [EvaluationJob.name][google.cloud.datalabeling.v1beta1.EvaluationJob.name]) - // - evaluation_job.model_id (the {model_name} portion - // of [EvaluationJob.modelVersion][google.cloud.datalabeling.v1beta1.EvaluationJob.model_version]) - // - evaluation_job.evaluation_job_run_time_start (Minimum - // threshold for the - // [evaluationJobRunTime][google.cloud.datalabeling.v1beta1.Evaluation.evaluation_job_run_time] that created - // the evaluation) - // - evaluation_job.evaluation_job_run_time_end (Maximum - // threshold for the - // [evaluationJobRunTime][google.cloud.datalabeling.v1beta1.Evaluation.evaluation_job_run_time] that created - // the evaluation) - // - evaluation_job.job_state ([EvaluationJob.state][google.cloud.datalabeling.v1beta1.EvaluationJob.state]) - // - annotation_spec.display_name (the Evaluation contains a - // metric for the annotation spec with this - // [displayName][google.cloud.datalabeling.v1beta1.AnnotationSpec.display_name]) + // * evaluation_job.evaluation_job_id (the last part of + // [EvaluationJob.name][google.cloud.datalabeling.v1beta1.EvaluationJob.name]) + // * evaluation_job.model_id (the {model_name} portion + // of [EvaluationJob.modelVersion][google.cloud.datalabeling.v1beta1.EvaluationJob.model_version]) + // * evaluation_job.evaluation_job_run_time_start (Minimum + // threshold for the + // [evaluationJobRunTime][google.cloud.datalabeling.v1beta1.Evaluation.evaluation_job_run_time] that created + // the evaluation) + // * evaluation_job.evaluation_job_run_time_end (Maximum + // threshold for the + // [evaluationJobRunTime][google.cloud.datalabeling.v1beta1.Evaluation.evaluation_job_run_time] that created + // the evaluation) + // * evaluation_job.job_state ([EvaluationJob.state][google.cloud.datalabeling.v1beta1.EvaluationJob.state]) + // * annotation_spec.display_name (the Evaluation contains a + // metric for the annotation spec with this + // [displayName][google.cloud.datalabeling.v1beta1.AnnotationSpec.display_name]) // // To filter by multiple critiera, use the `AND` operator or the `OR` // operator. The following examples shows a string that filters by several diff --git a/datalabeling/apiv1beta1/datalabelingpb/data_payloads.pb.go b/datalabeling/apiv1beta1/datalabelingpb/data_payloads.pb.go index 93055ed3eb48..b2c7d75e62b6 100644 --- a/datalabeling/apiv1beta1/datalabelingpb/data_payloads.pb.go +++ b/datalabeling/apiv1beta1/datalabelingpb/data_payloads.pb.go @@ -15,8 +15,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/datalabeling/v1beta1/data_payloads.proto package datalabelingpb diff --git a/datalabeling/apiv1beta1/datalabelingpb/dataset.pb.go b/datalabeling/apiv1beta1/datalabelingpb/dataset.pb.go index f747dd8db8fc..0b02faa52035 100644 --- a/datalabeling/apiv1beta1/datalabelingpb/dataset.pb.go +++ b/datalabeling/apiv1beta1/datalabelingpb/dataset.pb.go @@ -15,8 +15,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/datalabeling/v1beta1/dataset.proto package datalabelingpb @@ -214,13 +214,11 @@ type InputConfig struct { // Optional. The metadata associated with each data type. // // Types that are assignable to DataTypeMetadata: - // // *InputConfig_TextMetadata DataTypeMetadata isInputConfig_DataTypeMetadata `protobuf_oneof:"data_type_metadata"` // Required. Where the data is from. // // Types that are assignable to Source: - // // *InputConfig_GcsSource // *InputConfig_BigquerySource Source isInputConfig_Source `protobuf_oneof:"source"` @@ -586,7 +584,6 @@ type OutputConfig struct { // Required. Location to output data to. // // Types that are assignable to Destination: - // // *OutputConfig_GcsDestination // *OutputConfig_GcsFolderDestination Destination isOutputConfig_Destination `protobuf_oneof:"destination"` @@ -784,7 +781,6 @@ type DataItem struct { // Output only. // // Types that are assignable to Payload: - // // *DataItem_ImagePayload // *DataItem_TextPayload // *DataItem_VideoPayload @@ -1098,7 +1094,6 @@ type AnnotatedDatasetMetadata struct { // Specific request configuration used when requesting the labeling task. // // Types that are assignable to AnnotationRequestConfig: - // // *AnnotatedDatasetMetadata_ImageClassificationConfig // *AnnotatedDatasetMetadata_BoundingPolyConfig // *AnnotatedDatasetMetadata_PolylineConfig @@ -1324,7 +1319,6 @@ type Example struct { // Output only. The data part of Example. // // Types that are assignable to Payload: - // // *Example_ImagePayload // *Example_TextPayload // *Example_VideoPayload diff --git a/datalabeling/apiv1beta1/datalabelingpb/evaluation.pb.go b/datalabeling/apiv1beta1/datalabelingpb/evaluation.pb.go index 323d7f1471e1..be2591655869 100644 --- a/datalabeling/apiv1beta1/datalabelingpb/evaluation.pb.go +++ b/datalabeling/apiv1beta1/datalabelingpb/evaluation.pb.go @@ -15,8 +15,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/datalabeling/v1beta1/evaluation.proto package datalabelingpb @@ -163,7 +163,6 @@ type EvaluationConfig struct { // Vertical specific options for general metrics. // // Types that are assignable to VerticalOption: - // // *EvaluationConfig_BoundingBoxEvaluationOptions VerticalOption isEvaluationConfig_VerticalOption `protobuf_oneof:"vertical_option"` } @@ -289,7 +288,6 @@ type EvaluationMetrics struct { // Common metrics covering most general cases. // // Types that are assignable to Metrics: - // // *EvaluationMetrics_ClassificationMetrics // *EvaluationMetrics_ObjectDetectionMetrics Metrics isEvaluationMetrics_Metrics `protobuf_oneof:"metrics"` diff --git a/datalabeling/apiv1beta1/datalabelingpb/evaluation_job.pb.go b/datalabeling/apiv1beta1/datalabelingpb/evaluation_job.pb.go index e917080cce3d..51c1ea1490e2 100644 --- a/datalabeling/apiv1beta1/datalabelingpb/evaluation_job.pb.go +++ b/datalabeling/apiv1beta1/datalabelingpb/evaluation_job.pb.go @@ -15,8 +15,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/datalabeling/v1beta1/evaluation_job.proto package datalabelingpb @@ -54,25 +54,25 @@ const ( // The job is currently running. When the job runs, Data Labeling Service // does several things: // - // 1. If you have configured your job to use Data Labeling Service for - // ground truth labeling, the service creates a - // [Dataset][google.cloud.datalabeling.v1beta1.Dataset] and a labeling task for all data sampled - // since the last time the job ran. Human labelers provide ground truth - // labels for your data. Human labeling may take hours, or even days, - // depending on how much data has been sampled. The job remains in the - // `RUNNING` state during this time, and it can even be running multiple - // times in parallel if it gets triggered again (for example 24 hours - // later) before the earlier run has completed. When human labelers have - // finished labeling the data, the next step occurs. - //

- // If you have configured your job to provide your own ground truth - // labels, Data Labeling Service still creates a [Dataset][google.cloud.datalabeling.v1beta1.Dataset] for newly - // sampled data, but it expects that you have already added ground truth - // labels to the BigQuery table by this time. The next step occurs - // immediately. + // 1. If you have configured your job to use Data Labeling Service for + // ground truth labeling, the service creates a + // [Dataset][google.cloud.datalabeling.v1beta1.Dataset] and a labeling task for all data sampled + // since the last time the job ran. Human labelers provide ground truth + // labels for your data. Human labeling may take hours, or even days, + // depending on how much data has been sampled. The job remains in the + // `RUNNING` state during this time, and it can even be running multiple + // times in parallel if it gets triggered again (for example 24 hours + // later) before the earlier run has completed. When human labelers have + // finished labeling the data, the next step occurs. + //

+ // If you have configured your job to provide your own ground truth + // labels, Data Labeling Service still creates a [Dataset][google.cloud.datalabeling.v1beta1.Dataset] for newly + // sampled data, but it expects that you have already added ground truth + // labels to the BigQuery table by this time. The next step occurs + // immediately. // - // 2. Data Labeling Service creates an [Evaluation][google.cloud.datalabeling.v1beta1.Evaluation] by comparing your - // model version's predictions with the ground truth labels. + // 2. Data Labeling Service creates an [Evaluation][google.cloud.datalabeling.v1beta1.Evaluation] by comparing your + // model version's predictions with the ground truth labels. // // If the job remains in this state for a long time, it continues to sample // prediction data into your BigQuery table and will run again at the next @@ -306,7 +306,6 @@ type EvaluationJobConfig struct { // labels. // // Types that are assignable to HumanAnnotationRequestConfig: - // // *EvaluationJobConfig_ImageClassificationConfig // *EvaluationJobConfig_BoundingPolyConfig // *EvaluationJobConfig_TextClassificationConfig @@ -314,13 +313,13 @@ type EvaluationJobConfig struct { // Rquired. Details for the sampled prediction input. Within this // configuration, there are requirements for several fields: // - // - `dataType` must be one of `IMAGE`, `TEXT`, or `GENERAL_DATA`. - // - `annotationType` must be one of `IMAGE_CLASSIFICATION_ANNOTATION`, - // `TEXT_CLASSIFICATION_ANNOTATION`, `GENERAL_CLASSIFICATION_ANNOTATION`, - // or `IMAGE_BOUNDING_BOX_ANNOTATION` (image object detection). - // - If your machine learning model performs classification, you must specify - // `classificationMetadata.isMultiLabel`. - // - You must specify `bigquerySource` (not `gcsSource`). + // * `dataType` must be one of `IMAGE`, `TEXT`, or `GENERAL_DATA`. + // * `annotationType` must be one of `IMAGE_CLASSIFICATION_ANNOTATION`, + // `TEXT_CLASSIFICATION_ANNOTATION`, `GENERAL_CLASSIFICATION_ANNOTATION`, + // or `IMAGE_BOUNDING_BOX_ANNOTATION` (image object detection). + // * If your machine learning model performs classification, you must specify + // `classificationMetadata.isMultiLabel`. + // * You must specify `bigquerySource` (not `gcsSource`). InputConfig *InputConfig `protobuf:"bytes,1,opt,name=input_config,json=inputConfig,proto3" json:"input_config,omitempty"` // Required. Details for calculating evaluation metrics and creating // [Evaulations][google.cloud.datalabeling.v1beta1.Evaluation]. If your model version performs image object @@ -345,14 +344,14 @@ type EvaluationJobConfig struct { // // You can provide the following entries in this field: // - // - `data_json_key`: the data key for prediction input. You must provide - // either this key or `reference_json_key`. - // - `reference_json_key`: the data reference key for prediction input. You - // must provide either this key or `data_json_key`. - // - `label_json_key`: the label key for prediction output. Required. - // - `label_score_json_key`: the score key for prediction output. Required. - // - `bounding_box_json_key`: the bounding box key for prediction output. - // Required if your model version perform image object detection. + // * `data_json_key`: the data key for prediction input. You must provide + // either this key or `reference_json_key`. + // * `reference_json_key`: the data reference key for prediction input. You + // must provide either this key or `data_json_key`. + // * `label_json_key`: the label key for prediction output. Required. + // * `label_score_json_key`: the score key for prediction output. Required. + // * `bounding_box_json_key`: the bounding box key for prediction output. + // Required if your model version perform image object detection. // // Learn [how to configure prediction // keys](/ml-engine/docs/continuous-evaluation/create-job#prediction-keys). diff --git a/datalabeling/apiv1beta1/datalabelingpb/human_annotation_config.pb.go b/datalabeling/apiv1beta1/datalabelingpb/human_annotation_config.pb.go index 3812d9a51408..7624e95feec3 100644 --- a/datalabeling/apiv1beta1/datalabelingpb/human_annotation_config.pb.go +++ b/datalabeling/apiv1beta1/datalabelingpb/human_annotation_config.pb.go @@ -15,8 +15,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/datalabeling/v1beta1/human_annotation_config.proto package datalabelingpb diff --git a/datalabeling/apiv1beta1/datalabelingpb/instruction.pb.go b/datalabeling/apiv1beta1/datalabelingpb/instruction.pb.go index 23b3c77d84f5..136229707a2b 100644 --- a/datalabeling/apiv1beta1/datalabelingpb/instruction.pb.go +++ b/datalabeling/apiv1beta1/datalabelingpb/instruction.pb.go @@ -15,8 +15,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/datalabeling/v1beta1/instruction.proto package datalabelingpb diff --git a/datalabeling/apiv1beta1/datalabelingpb/operations.pb.go b/datalabeling/apiv1beta1/datalabelingpb/operations.pb.go index 3c5230ec9795..46c47a5a8526 100644 --- a/datalabeling/apiv1beta1/datalabelingpb/operations.pb.go +++ b/datalabeling/apiv1beta1/datalabelingpb/operations.pb.go @@ -15,8 +15,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/datalabeling/v1beta1/operations.proto package datalabelingpb @@ -341,7 +341,6 @@ type LabelOperationMetadata struct { // Ouptut only. Details of specific label operation. // // Types that are assignable to Details: - // // *LabelOperationMetadata_ImageClassificationDetails // *LabelOperationMetadata_ImageBoundingBoxDetails // *LabelOperationMetadata_ImageBoundingPolyDetails diff --git a/dataplex/apiv1/content_client.go b/dataplex/apiv1/content_client.go index 63233f940cf6..0b0d0b86397b 100644 --- a/dataplex/apiv1/content_client.go +++ b/dataplex/apiv1/content_client.go @@ -17,24 +17,30 @@ package dataplex import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" dataplexpb "cloud.google.com/go/dataplex/apiv1/dataplexpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" iampb "google.golang.org/genproto/googleapis/iam/v1" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -129,6 +135,61 @@ func defaultContentCallOptions() *ContentCallOptions { } } +func defaultContentRESTCallOptions() *ContentCallOptions { + return &ContentCallOptions{ + CreateContent: []gax.CallOption{}, + UpdateContent: []gax.CallOption{}, + DeleteContent: []gax.CallOption{}, + GetContent: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetIamPolicy: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + SetIamPolicy: []gax.CallOption{}, + TestIamPermissions: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListContent: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + CancelOperation: []gax.CallOption{}, + DeleteOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalContentClient is an interface that defines the methods available from Cloud Dataplex API. type internalContentClient interface { Close() error @@ -360,6 +421,74 @@ func (c *contentGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type contentRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing ContentClient + CallOptions **ContentCallOptions +} + +// NewContentRESTClient creates a new content service rest client. +// +// ContentService manages Notebook and SQL Scripts for Dataplex. +func NewContentRESTClient(ctx context.Context, opts ...option.ClientOption) (*ContentClient, error) { + clientOpts := append(defaultContentRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultContentRESTCallOptions() + c := &contentRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &ContentClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultContentRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://dataplex.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://dataplex.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://dataplex.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *contentRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *contentRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *contentRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *contentGRPCClient) CreateContent(ctx context.Context, req *dataplexpb.CreateContentRequest, opts ...gax.CallOption) (*dataplexpb.Content, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) @@ -705,6 +834,932 @@ func (c *contentGRPCClient) ListOperations(ctx context.Context, req *longrunning return it } +// CreateContent create a content. +func (c *contentRESTClient) CreateContent(ctx context.Context, req *dataplexpb.CreateContentRequest, opts ...gax.CallOption) (*dataplexpb.Content, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetContent() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/contentitems", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateContent[0:len((*c.CallOptions).CreateContent):len((*c.CallOptions).CreateContent)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dataplexpb.Content{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateContent update a content. Only supports full resource update. +func (c *contentRESTClient) UpdateContent(ctx context.Context, req *dataplexpb.UpdateContentRequest, opts ...gax.CallOption) (*dataplexpb.Content, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetContent() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetContent().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "content.name", url.QueryEscape(req.GetContent().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateContent[0:len((*c.CallOptions).UpdateContent):len((*c.CallOptions).UpdateContent)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dataplexpb.Content{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteContent delete a content. +func (c *contentRESTClient) DeleteContent(ctx context.Context, req *dataplexpb.DeleteContentRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetContent get a content resource. +func (c *contentRESTClient) GetContent(ctx context.Context, req *dataplexpb.GetContentRequest, opts ...gax.CallOption) (*dataplexpb.Content, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetView() != 0 { + params.Add("view", fmt.Sprintf("%v", req.GetView())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetContent[0:len((*c.CallOptions).GetContent):len((*c.CallOptions).GetContent)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dataplexpb.Content{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetIamPolicy gets the access control policy for a contentitem resource. A NOT_FOUND +// error is returned if the resource does not exist. An empty policy is +// returned if the resource exists but does not have a policy set on it. +// +// Caller must have Google IAM dataplex.content.getIamPolicy permission +// on the resource. +func (c *contentRESTClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:getIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetOptions().GetRequestedPolicyVersion() != 0 { + params.Add("options.requestedPolicyVersion", fmt.Sprintf("%v", req.GetOptions().GetRequestedPolicyVersion())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SetIamPolicy sets the access control policy on the specified contentitem resource. +// Replaces any existing policy. +// +// Caller must have Google IAM dataplex.content.setIamPolicy permission +// on the resource. +func (c *contentRESTClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:setIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// TestIamPermissions returns the caller’s permissions on a resource. +// If the resource does not exist, an empty set of +// permissions is returned (a NOT_FOUND error is not returned). +// +// A caller is not required to have Google IAM permission to make this +// request. +// +// Note: This operation is designed to be used for building permission-aware +// UIs and command-line tools, not for authorization checking. This operation +// may “fail open” without warning. +func (c *contentRESTClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:testIamPermissions", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.TestIamPermissionsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListContent list content. +func (c *contentRESTClient) ListContent(ctx context.Context, req *dataplexpb.ListContentRequest, opts ...gax.CallOption) *ContentIterator { + it := &ContentIterator{} + req = proto.Clone(req).(*dataplexpb.ListContentRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*dataplexpb.Content, string, error) { + resp := &dataplexpb.ListContentResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/contentitems", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetContent(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetLocation gets information about a location. +func (c *contentRESTClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *contentRESTClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *contentRESTClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// DeleteOperation is a utility method from google.longrunning.Operations. +func (c *contentRESTClient) DeleteOperation(ctx context.Context, req *longrunningpb.DeleteOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *contentRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *contentRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + // ContentIterator manages a stream of *dataplexpb.Content. type ContentIterator struct { items []*dataplexpb.Content diff --git a/dataplex/apiv1/content_client_example_test.go b/dataplex/apiv1/content_client_example_test.go index 2da1f129e727..d87dbc39c392 100644 --- a/dataplex/apiv1/content_client_example_test.go +++ b/dataplex/apiv1/content_client_example_test.go @@ -44,6 +44,23 @@ func ExampleNewContentClient() { _ = c } +func ExampleNewContentRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := dataplex.NewContentRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleContentClient_CreateContent() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/dataplex/apiv1/dataplex_client.go b/dataplex/apiv1/dataplex_client.go index ee5d58bd08cc..05906f5541cf 100644 --- a/dataplex/apiv1/dataplex_client.go +++ b/dataplex/apiv1/dataplex_client.go @@ -17,9 +17,12 @@ package dataplex import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,15 +30,18 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -288,6 +294,184 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + CreateLake: []gax.CallOption{}, + UpdateLake: []gax.CallOption{}, + DeleteLake: []gax.CallOption{}, + ListLakes: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetLake: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListLakeActions: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateZone: []gax.CallOption{}, + UpdateZone: []gax.CallOption{}, + DeleteZone: []gax.CallOption{}, + ListZones: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetZone: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListZoneActions: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateAsset: []gax.CallOption{}, + UpdateAsset: []gax.CallOption{}, + DeleteAsset: []gax.CallOption{}, + ListAssets: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetAsset: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListAssetActions: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateTask: []gax.CallOption{}, + UpdateTask: []gax.CallOption{}, + DeleteTask: []gax.CallOption{}, + ListTasks: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetTask: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListJobs: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetJob: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CancelJob: []gax.CallOption{}, + CreateEnvironment: []gax.CallOption{}, + UpdateEnvironment: []gax.CallOption{}, + DeleteEnvironment: []gax.CallOption{}, + ListEnvironments: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetEnvironment: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListSessions: []gax.CallOption{}, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + CancelOperation: []gax.CallOption{}, + DeleteOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalClient is an interface that defines the methods available from Cloud Dataplex API. type internalClient interface { Close() error @@ -783,6 +967,93 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new dataplex service rest client. +// +// Dataplex service provides data lakes as a service. The primary resources +// offered by this service are Lakes, Zones and Assets which collectively allow +// a data administrator to organize, manage, secure and catalog data across +// their organization located across cloud projects in a variety of storage +// systems including Cloud Storage and BigQuery. +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://dataplex.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://dataplex.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://dataplex.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) CreateLake(ctx context.Context, req *dataplexpb.CreateLakeRequest, opts ...gax.CallOption) (*CreateLakeOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) @@ -1893,79 +2164,2858 @@ func (c *gRPCClient) ListOperations(ctx context.Context, req *longrunningpb.List return it } -// CreateAssetOperation manages a long-running operation from CreateAsset. -type CreateAssetOperation struct { - lro *longrunning.Operation -} - -// CreateAssetOperation returns a new CreateAssetOperation from a given name. -// The name must be that of a previously created CreateAssetOperation, possibly from a different process. -func (c *gRPCClient) CreateAssetOperation(name string) *CreateAssetOperation { - return &CreateAssetOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} - -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *CreateAssetOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*dataplexpb.Asset, error) { - var resp dataplexpb.Asset - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { +// CreateLake creates a lake resource. +func (c *restClient) CreateLake(ctx context.Context, req *dataplexpb.CreateLakeRequest, opts ...gax.CallOption) (*CreateLakeOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetLake() + jsonReq, err := m.Marshal(body) + if err != nil { return nil, err } - return &resp, nil -} -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *CreateAssetOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*dataplexpb.Asset, error) { - var resp dataplexpb.Asset - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - if !op.Done() { - return nil, nil - } - return &resp, nil -} + baseUrl.Path += fmt.Sprintf("/v1/%v/lakes", req.GetParent()) -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *CreateAssetOperation) Metadata() (*dataplexpb.OperationMetadata, error) { - var meta dataplexpb.OperationMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { - return nil, err + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("lakeId", fmt.Sprintf("%v", req.GetLakeId())) + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) } - return &meta, nil -} -// Done reports whether the long-running operation has completed. -func (op *CreateAssetOperation) Done() bool { - return op.lro.Done() -} + baseUrl.RawQuery = params.Encode() -// 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 *CreateAssetOperation) Name() string { - return op.lro.Name() -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) -// CreateEnvironmentOperation manages a long-running operation from CreateEnvironment. -type CreateEnvironmentOperation struct { - lro *longrunning.Operation -} + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateLakeOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateLake updates a lake resource. +func (c *restClient) UpdateLake(ctx context.Context, req *dataplexpb.UpdateLakeRequest, opts ...gax.CallOption) (*UpdateLakeOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetLake() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetLake().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "lake.name", url.QueryEscape(req.GetLake().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateLakeOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteLake deletes a lake resource. All zones within the lake must be deleted before +// the lake can be deleted. +func (c *restClient) DeleteLake(ctx context.Context, req *dataplexpb.DeleteLakeRequest, opts ...gax.CallOption) (*DeleteLakeOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteLakeOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListLakes lists lake resources in a project and location. +func (c *restClient) ListLakes(ctx context.Context, req *dataplexpb.ListLakesRequest, opts ...gax.CallOption) *LakeIterator { + it := &LakeIterator{} + req = proto.Clone(req).(*dataplexpb.ListLakesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*dataplexpb.Lake, string, error) { + resp := &dataplexpb.ListLakesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/lakes", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLakes(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetLake retrieves a lake resource. +func (c *restClient) GetLake(ctx context.Context, req *dataplexpb.GetLakeRequest, opts ...gax.CallOption) (*dataplexpb.Lake, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLake[0:len((*c.CallOptions).GetLake):len((*c.CallOptions).GetLake)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dataplexpb.Lake{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLakeActions lists action resources in a lake. +func (c *restClient) ListLakeActions(ctx context.Context, req *dataplexpb.ListLakeActionsRequest, opts ...gax.CallOption) *ActionIterator { + it := &ActionIterator{} + req = proto.Clone(req).(*dataplexpb.ListLakeActionsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*dataplexpb.Action, string, error) { + resp := &dataplexpb.ListActionsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/actions", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetActions(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CreateZone creates a zone resource within a lake. +func (c *restClient) CreateZone(ctx context.Context, req *dataplexpb.CreateZoneRequest, opts ...gax.CallOption) (*CreateZoneOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetZone() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/zones", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + params.Add("zoneId", fmt.Sprintf("%v", req.GetZoneId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateZoneOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateZone updates a zone resource. +func (c *restClient) UpdateZone(ctx context.Context, req *dataplexpb.UpdateZoneRequest, opts ...gax.CallOption) (*UpdateZoneOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetZone() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetZone().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "zone.name", url.QueryEscape(req.GetZone().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateZoneOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteZone deletes a zone resource. All assets within a zone must be deleted before +// the zone can be deleted. +func (c *restClient) DeleteZone(ctx context.Context, req *dataplexpb.DeleteZoneRequest, opts ...gax.CallOption) (*DeleteZoneOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteZoneOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListZones lists zone resources in a lake. +func (c *restClient) ListZones(ctx context.Context, req *dataplexpb.ListZonesRequest, opts ...gax.CallOption) *ZoneIterator { + it := &ZoneIterator{} + req = proto.Clone(req).(*dataplexpb.ListZonesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*dataplexpb.Zone, string, error) { + resp := &dataplexpb.ListZonesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/zones", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetZones(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetZone retrieves a zone resource. +func (c *restClient) GetZone(ctx context.Context, req *dataplexpb.GetZoneRequest, opts ...gax.CallOption) (*dataplexpb.Zone, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetZone[0:len((*c.CallOptions).GetZone):len((*c.CallOptions).GetZone)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dataplexpb.Zone{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListZoneActions lists action resources in a zone. +func (c *restClient) ListZoneActions(ctx context.Context, req *dataplexpb.ListZoneActionsRequest, opts ...gax.CallOption) *ActionIterator { + it := &ActionIterator{} + req = proto.Clone(req).(*dataplexpb.ListZoneActionsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*dataplexpb.Action, string, error) { + resp := &dataplexpb.ListActionsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/actions", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetActions(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CreateAsset creates an asset resource. +func (c *restClient) CreateAsset(ctx context.Context, req *dataplexpb.CreateAssetRequest, opts ...gax.CallOption) (*CreateAssetOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetAsset() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/assets", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("assetId", fmt.Sprintf("%v", req.GetAssetId())) + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateAssetOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateAsset updates an asset resource. +func (c *restClient) UpdateAsset(ctx context.Context, req *dataplexpb.UpdateAssetRequest, opts ...gax.CallOption) (*UpdateAssetOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetAsset() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetAsset().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "asset.name", url.QueryEscape(req.GetAsset().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateAssetOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteAsset deletes an asset resource. The referenced storage resource is detached +// (default) or deleted based on the associated Lifecycle policy. +func (c *restClient) DeleteAsset(ctx context.Context, req *dataplexpb.DeleteAssetRequest, opts ...gax.CallOption) (*DeleteAssetOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteAssetOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListAssets lists asset resources in a zone. +func (c *restClient) ListAssets(ctx context.Context, req *dataplexpb.ListAssetsRequest, opts ...gax.CallOption) *AssetIterator { + it := &AssetIterator{} + req = proto.Clone(req).(*dataplexpb.ListAssetsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*dataplexpb.Asset, string, error) { + resp := &dataplexpb.ListAssetsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/assets", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetAssets(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetAsset retrieves an asset resource. +func (c *restClient) GetAsset(ctx context.Context, req *dataplexpb.GetAssetRequest, opts ...gax.CallOption) (*dataplexpb.Asset, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetAsset[0:len((*c.CallOptions).GetAsset):len((*c.CallOptions).GetAsset)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dataplexpb.Asset{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListAssetActions lists action resources in an asset. +func (c *restClient) ListAssetActions(ctx context.Context, req *dataplexpb.ListAssetActionsRequest, opts ...gax.CallOption) *ActionIterator { + it := &ActionIterator{} + req = proto.Clone(req).(*dataplexpb.ListAssetActionsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*dataplexpb.Action, string, error) { + resp := &dataplexpb.ListActionsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/actions", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetActions(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CreateTask creates a task resource within a lake. +func (c *restClient) CreateTask(ctx context.Context, req *dataplexpb.CreateTaskRequest, opts ...gax.CallOption) (*CreateTaskOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetTask() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/tasks", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("taskId", fmt.Sprintf("%v", req.GetTaskId())) + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateTaskOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateTask update the task resource. +func (c *restClient) UpdateTask(ctx context.Context, req *dataplexpb.UpdateTaskRequest, opts ...gax.CallOption) (*UpdateTaskOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetTask() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetTask().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "task.name", url.QueryEscape(req.GetTask().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateTaskOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteTask delete the task resource. +func (c *restClient) DeleteTask(ctx context.Context, req *dataplexpb.DeleteTaskRequest, opts ...gax.CallOption) (*DeleteTaskOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteTaskOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListTasks lists tasks under the given lake. +func (c *restClient) ListTasks(ctx context.Context, req *dataplexpb.ListTasksRequest, opts ...gax.CallOption) *TaskIterator { + it := &TaskIterator{} + req = proto.Clone(req).(*dataplexpb.ListTasksRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*dataplexpb.Task, string, error) { + resp := &dataplexpb.ListTasksResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/tasks", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetTasks(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetTask get task resource. +func (c *restClient) GetTask(ctx context.Context, req *dataplexpb.GetTaskRequest, opts ...gax.CallOption) (*dataplexpb.Task, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetTask[0:len((*c.CallOptions).GetTask):len((*c.CallOptions).GetTask)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dataplexpb.Task{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListJobs lists Jobs under the given task. +func (c *restClient) ListJobs(ctx context.Context, req *dataplexpb.ListJobsRequest, opts ...gax.CallOption) *JobIterator { + it := &JobIterator{} + req = proto.Clone(req).(*dataplexpb.ListJobsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*dataplexpb.Job, string, error) { + resp := &dataplexpb.ListJobsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/jobs", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetJobs(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetJob get job resource. +func (c *restClient) GetJob(ctx context.Context, req *dataplexpb.GetJobRequest, opts ...gax.CallOption) (*dataplexpb.Job, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetJob[0:len((*c.CallOptions).GetJob):len((*c.CallOptions).GetJob)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dataplexpb.Job{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CancelJob cancel jobs running for the task resource. +func (c *restClient) CancelJob(ctx context.Context, req *dataplexpb.CancelJobRequest, opts ...gax.CallOption) error { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// CreateEnvironment create an environment resource. +func (c *restClient) CreateEnvironment(ctx context.Context, req *dataplexpb.CreateEnvironmentRequest, opts ...gax.CallOption) (*CreateEnvironmentOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetEnvironment() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/environments", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("environmentId", fmt.Sprintf("%v", req.GetEnvironmentId())) + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateEnvironmentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateEnvironment update the environment resource. +func (c *restClient) UpdateEnvironment(ctx context.Context, req *dataplexpb.UpdateEnvironmentRequest, opts ...gax.CallOption) (*UpdateEnvironmentOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetEnvironment() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetEnvironment().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "environment.name", url.QueryEscape(req.GetEnvironment().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateEnvironmentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteEnvironment delete the environment resource. All the child resources must have been +// deleted before environment deletion can be initiated. +func (c *restClient) DeleteEnvironment(ctx context.Context, req *dataplexpb.DeleteEnvironmentRequest, opts ...gax.CallOption) (*DeleteEnvironmentOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteEnvironmentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListEnvironments lists environments under the given lake. +func (c *restClient) ListEnvironments(ctx context.Context, req *dataplexpb.ListEnvironmentsRequest, opts ...gax.CallOption) *EnvironmentIterator { + it := &EnvironmentIterator{} + req = proto.Clone(req).(*dataplexpb.ListEnvironmentsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*dataplexpb.Environment, string, error) { + resp := &dataplexpb.ListEnvironmentsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/environments", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetEnvironments(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetEnvironment get environment resource. +func (c *restClient) GetEnvironment(ctx context.Context, req *dataplexpb.GetEnvironmentRequest, opts ...gax.CallOption) (*dataplexpb.Environment, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetEnvironment[0:len((*c.CallOptions).GetEnvironment):len((*c.CallOptions).GetEnvironment)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dataplexpb.Environment{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListSessions lists session resources in an environment. +func (c *restClient) ListSessions(ctx context.Context, req *dataplexpb.ListSessionsRequest, opts ...gax.CallOption) *SessionIterator { + it := &SessionIterator{} + req = proto.Clone(req).(*dataplexpb.ListSessionsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*dataplexpb.Session, string, error) { + resp := &dataplexpb.ListSessionsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/sessions", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetSessions(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetLocation gets information about a location. +func (c *restClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *restClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *restClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// DeleteOperation is a utility method from google.longrunning.Operations. +func (c *restClient) DeleteOperation(ctx context.Context, req *longrunningpb.DeleteOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *restClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *restClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CreateAssetOperation manages a long-running operation from CreateAsset. +type CreateAssetOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateAssetOperation returns a new CreateAssetOperation from a given name. +// The name must be that of a previously created CreateAssetOperation, possibly from a different process. +func (c *gRPCClient) CreateAssetOperation(name string) *CreateAssetOperation { + return &CreateAssetOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateAssetOperation returns a new CreateAssetOperation from a given name. +// The name must be that of a previously created CreateAssetOperation, possibly from a different process. +func (c *restClient) CreateAssetOperation(name string) *CreateAssetOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateAssetOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CreateAssetOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*dataplexpb.Asset, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp dataplexpb.Asset + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *CreateAssetOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*dataplexpb.Asset, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp dataplexpb.Asset + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *CreateAssetOperation) Metadata() (*dataplexpb.OperationMetadata, error) { + var meta dataplexpb.OperationMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *CreateAssetOperation) Done() bool { + return op.lro.Done() +} + +// 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 *CreateAssetOperation) Name() string { + return op.lro.Name() +} + +// CreateEnvironmentOperation manages a long-running operation from CreateEnvironment. +type CreateEnvironmentOperation struct { + lro *longrunning.Operation + pollPath string +} // CreateEnvironmentOperation returns a new CreateEnvironmentOperation from a given name. // The name must be that of a previously created CreateEnvironmentOperation, possibly from a different process. @@ -1975,10 +5025,21 @@ func (c *gRPCClient) CreateEnvironmentOperation(name string) *CreateEnvironmentO } } +// CreateEnvironmentOperation returns a new CreateEnvironmentOperation from a given name. +// The name must be that of a previously created CreateEnvironmentOperation, possibly from a different process. +func (c *restClient) CreateEnvironmentOperation(name string) *CreateEnvironmentOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateEnvironmentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateEnvironmentOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*dataplexpb.Environment, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp dataplexpb.Environment if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1996,6 +5057,7 @@ func (op *CreateEnvironmentOperation) Wait(ctx context.Context, opts ...gax.Call // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateEnvironmentOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*dataplexpb.Environment, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp dataplexpb.Environment if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2033,7 +5095,8 @@ func (op *CreateEnvironmentOperation) Name() string { // CreateLakeOperation manages a long-running operation from CreateLake. type CreateLakeOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateLakeOperation returns a new CreateLakeOperation from a given name. @@ -2044,10 +5107,21 @@ func (c *gRPCClient) CreateLakeOperation(name string) *CreateLakeOperation { } } +// CreateLakeOperation returns a new CreateLakeOperation from a given name. +// The name must be that of a previously created CreateLakeOperation, possibly from a different process. +func (c *restClient) CreateLakeOperation(name string) *CreateLakeOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateLakeOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateLakeOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*dataplexpb.Lake, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp dataplexpb.Lake if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2065,6 +5139,7 @@ func (op *CreateLakeOperation) Wait(ctx context.Context, opts ...gax.CallOption) // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateLakeOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*dataplexpb.Lake, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp dataplexpb.Lake if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2102,7 +5177,8 @@ func (op *CreateLakeOperation) Name() string { // CreateTaskOperation manages a long-running operation from CreateTask. type CreateTaskOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateTaskOperation returns a new CreateTaskOperation from a given name. @@ -2113,10 +5189,21 @@ func (c *gRPCClient) CreateTaskOperation(name string) *CreateTaskOperation { } } +// CreateTaskOperation returns a new CreateTaskOperation from a given name. +// The name must be that of a previously created CreateTaskOperation, possibly from a different process. +func (c *restClient) CreateTaskOperation(name string) *CreateTaskOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateTaskOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateTaskOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*dataplexpb.Task, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp dataplexpb.Task if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2134,6 +5221,7 @@ func (op *CreateTaskOperation) Wait(ctx context.Context, opts ...gax.CallOption) // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateTaskOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*dataplexpb.Task, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp dataplexpb.Task if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2171,7 +5259,8 @@ func (op *CreateTaskOperation) Name() string { // CreateZoneOperation manages a long-running operation from CreateZone. type CreateZoneOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateZoneOperation returns a new CreateZoneOperation from a given name. @@ -2182,10 +5271,21 @@ func (c *gRPCClient) CreateZoneOperation(name string) *CreateZoneOperation { } } +// CreateZoneOperation returns a new CreateZoneOperation from a given name. +// The name must be that of a previously created CreateZoneOperation, possibly from a different process. +func (c *restClient) CreateZoneOperation(name string) *CreateZoneOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateZoneOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateZoneOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*dataplexpb.Zone, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp dataplexpb.Zone if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2203,6 +5303,7 @@ func (op *CreateZoneOperation) Wait(ctx context.Context, opts ...gax.CallOption) // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateZoneOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*dataplexpb.Zone, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp dataplexpb.Zone if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2240,7 +5341,8 @@ func (op *CreateZoneOperation) Name() string { // DeleteAssetOperation manages a long-running operation from DeleteAsset. type DeleteAssetOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteAssetOperation returns a new DeleteAssetOperation from a given name. @@ -2251,10 +5353,21 @@ func (c *gRPCClient) DeleteAssetOperation(name string) *DeleteAssetOperation { } } +// DeleteAssetOperation returns a new DeleteAssetOperation from a given name. +// The name must be that of a previously created DeleteAssetOperation, possibly from a different process. +func (c *restClient) DeleteAssetOperation(name string) *DeleteAssetOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteAssetOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteAssetOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -2268,6 +5381,7 @@ func (op *DeleteAssetOperation) Wait(ctx context.Context, opts ...gax.CallOption // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteAssetOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -2298,7 +5412,8 @@ func (op *DeleteAssetOperation) Name() string { // DeleteEnvironmentOperation manages a long-running operation from DeleteEnvironment. type DeleteEnvironmentOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteEnvironmentOperation returns a new DeleteEnvironmentOperation from a given name. @@ -2309,10 +5424,21 @@ func (c *gRPCClient) DeleteEnvironmentOperation(name string) *DeleteEnvironmentO } } +// DeleteEnvironmentOperation returns a new DeleteEnvironmentOperation from a given name. +// The name must be that of a previously created DeleteEnvironmentOperation, possibly from a different process. +func (c *restClient) DeleteEnvironmentOperation(name string) *DeleteEnvironmentOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteEnvironmentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteEnvironmentOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -2326,6 +5452,7 @@ func (op *DeleteEnvironmentOperation) Wait(ctx context.Context, opts ...gax.Call // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteEnvironmentOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -2356,7 +5483,8 @@ func (op *DeleteEnvironmentOperation) Name() string { // DeleteLakeOperation manages a long-running operation from DeleteLake. type DeleteLakeOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteLakeOperation returns a new DeleteLakeOperation from a given name. @@ -2367,10 +5495,21 @@ func (c *gRPCClient) DeleteLakeOperation(name string) *DeleteLakeOperation { } } +// DeleteLakeOperation returns a new DeleteLakeOperation from a given name. +// The name must be that of a previously created DeleteLakeOperation, possibly from a different process. +func (c *restClient) DeleteLakeOperation(name string) *DeleteLakeOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteLakeOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteLakeOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -2384,6 +5523,7 @@ func (op *DeleteLakeOperation) Wait(ctx context.Context, opts ...gax.CallOption) // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteLakeOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -2414,7 +5554,8 @@ func (op *DeleteLakeOperation) Name() string { // DeleteTaskOperation manages a long-running operation from DeleteTask. type DeleteTaskOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteTaskOperation returns a new DeleteTaskOperation from a given name. @@ -2425,10 +5566,21 @@ func (c *gRPCClient) DeleteTaskOperation(name string) *DeleteTaskOperation { } } +// DeleteTaskOperation returns a new DeleteTaskOperation from a given name. +// The name must be that of a previously created DeleteTaskOperation, possibly from a different process. +func (c *restClient) DeleteTaskOperation(name string) *DeleteTaskOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteTaskOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteTaskOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -2442,6 +5594,7 @@ func (op *DeleteTaskOperation) Wait(ctx context.Context, opts ...gax.CallOption) // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteTaskOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -2472,7 +5625,8 @@ func (op *DeleteTaskOperation) Name() string { // DeleteZoneOperation manages a long-running operation from DeleteZone. type DeleteZoneOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteZoneOperation returns a new DeleteZoneOperation from a given name. @@ -2483,10 +5637,21 @@ func (c *gRPCClient) DeleteZoneOperation(name string) *DeleteZoneOperation { } } +// DeleteZoneOperation returns a new DeleteZoneOperation from a given name. +// The name must be that of a previously created DeleteZoneOperation, possibly from a different process. +func (c *restClient) DeleteZoneOperation(name string) *DeleteZoneOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteZoneOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteZoneOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -2500,6 +5665,7 @@ func (op *DeleteZoneOperation) Wait(ctx context.Context, opts ...gax.CallOption) // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteZoneOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -2530,7 +5696,8 @@ func (op *DeleteZoneOperation) Name() string { // UpdateAssetOperation manages a long-running operation from UpdateAsset. type UpdateAssetOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateAssetOperation returns a new UpdateAssetOperation from a given name. @@ -2541,10 +5708,21 @@ func (c *gRPCClient) UpdateAssetOperation(name string) *UpdateAssetOperation { } } +// UpdateAssetOperation returns a new UpdateAssetOperation from a given name. +// The name must be that of a previously created UpdateAssetOperation, possibly from a different process. +func (c *restClient) UpdateAssetOperation(name string) *UpdateAssetOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateAssetOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateAssetOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*dataplexpb.Asset, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp dataplexpb.Asset if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2562,6 +5740,7 @@ func (op *UpdateAssetOperation) Wait(ctx context.Context, opts ...gax.CallOption // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateAssetOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*dataplexpb.Asset, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp dataplexpb.Asset if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2599,7 +5778,8 @@ func (op *UpdateAssetOperation) Name() string { // UpdateEnvironmentOperation manages a long-running operation from UpdateEnvironment. type UpdateEnvironmentOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateEnvironmentOperation returns a new UpdateEnvironmentOperation from a given name. @@ -2610,10 +5790,21 @@ func (c *gRPCClient) UpdateEnvironmentOperation(name string) *UpdateEnvironmentO } } +// UpdateEnvironmentOperation returns a new UpdateEnvironmentOperation from a given name. +// The name must be that of a previously created UpdateEnvironmentOperation, possibly from a different process. +func (c *restClient) UpdateEnvironmentOperation(name string) *UpdateEnvironmentOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateEnvironmentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateEnvironmentOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*dataplexpb.Environment, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp dataplexpb.Environment if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2631,6 +5822,7 @@ func (op *UpdateEnvironmentOperation) Wait(ctx context.Context, opts ...gax.Call // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateEnvironmentOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*dataplexpb.Environment, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp dataplexpb.Environment if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2668,7 +5860,8 @@ func (op *UpdateEnvironmentOperation) Name() string { // UpdateLakeOperation manages a long-running operation from UpdateLake. type UpdateLakeOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateLakeOperation returns a new UpdateLakeOperation from a given name. @@ -2679,10 +5872,21 @@ func (c *gRPCClient) UpdateLakeOperation(name string) *UpdateLakeOperation { } } +// UpdateLakeOperation returns a new UpdateLakeOperation from a given name. +// The name must be that of a previously created UpdateLakeOperation, possibly from a different process. +func (c *restClient) UpdateLakeOperation(name string) *UpdateLakeOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateLakeOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateLakeOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*dataplexpb.Lake, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp dataplexpb.Lake if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2700,6 +5904,7 @@ func (op *UpdateLakeOperation) Wait(ctx context.Context, opts ...gax.CallOption) // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateLakeOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*dataplexpb.Lake, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp dataplexpb.Lake if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2737,7 +5942,8 @@ func (op *UpdateLakeOperation) Name() string { // UpdateTaskOperation manages a long-running operation from UpdateTask. type UpdateTaskOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateTaskOperation returns a new UpdateTaskOperation from a given name. @@ -2748,10 +5954,21 @@ func (c *gRPCClient) UpdateTaskOperation(name string) *UpdateTaskOperation { } } +// UpdateTaskOperation returns a new UpdateTaskOperation from a given name. +// The name must be that of a previously created UpdateTaskOperation, possibly from a different process. +func (c *restClient) UpdateTaskOperation(name string) *UpdateTaskOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateTaskOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateTaskOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*dataplexpb.Task, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp dataplexpb.Task if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2769,6 +5986,7 @@ func (op *UpdateTaskOperation) Wait(ctx context.Context, opts ...gax.CallOption) // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateTaskOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*dataplexpb.Task, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp dataplexpb.Task if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2806,7 +6024,8 @@ func (op *UpdateTaskOperation) Name() string { // UpdateZoneOperation manages a long-running operation from UpdateZone. type UpdateZoneOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateZoneOperation returns a new UpdateZoneOperation from a given name. @@ -2817,10 +6036,21 @@ func (c *gRPCClient) UpdateZoneOperation(name string) *UpdateZoneOperation { } } +// UpdateZoneOperation returns a new UpdateZoneOperation from a given name. +// The name must be that of a previously created UpdateZoneOperation, possibly from a different process. +func (c *restClient) UpdateZoneOperation(name string) *UpdateZoneOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateZoneOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateZoneOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*dataplexpb.Zone, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp dataplexpb.Zone if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2838,6 +6068,7 @@ func (op *UpdateZoneOperation) Wait(ctx context.Context, opts ...gax.CallOption) // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateZoneOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*dataplexpb.Zone, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp dataplexpb.Zone if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/dataplex/apiv1/dataplex_client_example_test.go b/dataplex/apiv1/dataplex_client_example_test.go index 54cb7d3ede21..d4af201e8fe9 100644 --- a/dataplex/apiv1/dataplex_client_example_test.go +++ b/dataplex/apiv1/dataplex_client_example_test.go @@ -43,6 +43,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := dataplex.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_CreateLake() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/dataplex/apiv1/dataplexpb/analyze.pb.go b/dataplex/apiv1/dataplexpb/analyze.pb.go index 437424afad30..aba035511b85 100644 --- a/dataplex/apiv1/dataplexpb/analyze.pb.go +++ b/dataplex/apiv1/dataplexpb/analyze.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dataplex/v1/analyze.proto package dataplexpb @@ -314,11 +314,9 @@ type Content struct { // Only returned in `GetContent` requests and not in `ListContent` request. // // Types that are assignable to Data: - // // *Content_DataText Data isContent_Data `protobuf_oneof:"data"` // Types that are assignable to Content: - // // *Content_SqlScript_ // *Content_Notebook_ Content isContent_Content `protobuf_oneof:"content"` @@ -554,13 +552,11 @@ type Environment_InfrastructureSpec struct { // Hardware config // // Types that are assignable to Resources: - // // *Environment_InfrastructureSpec_Compute Resources isEnvironment_InfrastructureSpec_Resources `protobuf_oneof:"resources"` // Software config // // Types that are assignable to Runtime: - // // *Environment_InfrastructureSpec_OsImage Runtime isEnvironment_InfrastructureSpec_Runtime `protobuf_oneof:"runtime"` } diff --git a/dataplex/apiv1/dataplexpb/content.pb.go b/dataplex/apiv1/dataplexpb/content.pb.go index 4799f7bfc01b..52357411ed45 100644 --- a/dataplex/apiv1/dataplexpb/content.pb.go +++ b/dataplex/apiv1/dataplexpb/content.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dataplex/v1/content.proto package dataplexpb diff --git a/dataplex/apiv1/dataplexpb/logs.pb.go b/dataplex/apiv1/dataplexpb/logs.pb.go index 81ffb51e03c3..1fc150b8f475 100644 --- a/dataplex/apiv1/dataplexpb/logs.pb.go +++ b/dataplex/apiv1/dataplexpb/logs.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dataplex/v1/logs.proto package dataplexpb @@ -463,7 +463,6 @@ type DiscoveryEvent struct { // Additional details about the event. // // Types that are assignable to Details: - // // *DiscoveryEvent_Config // *DiscoveryEvent_Entity // *DiscoveryEvent_Partition @@ -753,7 +752,6 @@ type SessionEvent struct { // Additional information about the Query metadata. // // Types that are assignable to Detail: - // // *SessionEvent_Query Detail isSessionEvent_Detail `protobuf_oneof:"detail"` // The status of the event. diff --git a/dataplex/apiv1/dataplexpb/metadata.pb.go b/dataplex/apiv1/dataplexpb/metadata.pb.go index 3155e2bc8051..f08c0b4ec181 100644 --- a/dataplex/apiv1/dataplexpb/metadata.pb.go +++ b/dataplex/apiv1/dataplexpb/metadata.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dataplex/v1/metadata.proto package dataplexpb @@ -1053,18 +1053,17 @@ type ListPartitionsRequest struct { // - LIKE operators: // - The right hand of a LIKE operator supports "." and // "*" for wildcard searches, for example "value1 LIKE ".*oo.*" - // // - parenthetical grouping: ( ) // // Sample filter expression: `?filter="key1 < value1 OR key2 > value2" // // **Notes:** // - // - Keys to the left of operators are case insensitive. - // - Partition results are sorted first by creation time, then by - // lexicographic order. - // - Up to 20 key value filter pairs are allowed, but due to performance - // considerations, only the first 10 will be used as a filter. + // - Keys to the left of operators are case insensitive. + // - Partition results are sorted first by creation time, then by + // lexicographic order. + // - Up to 20 key value filter pairs are allowed, but due to performance + // considerations, only the first 10 will be used as a filter. Filter string `protobuf:"bytes,4,opt,name=filter,proto3" json:"filter,omitempty"` } @@ -1670,16 +1669,16 @@ type Schema struct { // Required. Set to `true` if user-managed or `false` if managed by Dataplex. The // default is `false` (managed by Dataplex). // - // - Set to `false`to enable Dataplex discovery to update the schema. - // including new data discovery, schema inference, and schema evolution. - // Users retain the ability to input and edit the schema. Dataplex - // treats schema input by the user as though produced - // by a previous Dataplex discovery operation, and it will - // evolve the schema and take action based on that treatment. + // - Set to `false`to enable Dataplex discovery to update the schema. + // including new data discovery, schema inference, and schema evolution. + // Users retain the ability to input and edit the schema. Dataplex + // treats schema input by the user as though produced + // by a previous Dataplex discovery operation, and it will + // evolve the schema and take action based on that treatment. // - // - Set to `true` to fully manage the entity - // schema. This setting guarantees that Dataplex will not - // change schema fields. + // - Set to `true` to fully manage the entity + // schema. This setting guarantees that Dataplex will not + // change schema fields. UserManaged bool `protobuf:"varint,1,opt,name=user_managed,json=userManaged,proto3" json:"user_managed,omitempty"` // Optional. The sequence of fields describing data in table entities. // **Note:** BigQuery SchemaFields are immutable. @@ -1781,7 +1780,6 @@ type StorageFormat struct { // Additional format-specific options. // // Types that are assignable to Options: - // // *StorageFormat_Csv // *StorageFormat_Json Options isStorageFormat_Options `protobuf_oneof:"options"` @@ -2163,7 +2161,7 @@ type StorageFormat_CsvOptions struct { // Optional. The delimiter used to separate values. Defaults to ','. Delimiter string `protobuf:"bytes,3,opt,name=delimiter,proto3" json:"delimiter,omitempty"` // Optional. The character used to quote column values. Accepts '"' - // (double quotation mark) or ”' (single quotation mark). Defaults to + // (double quotation mark) or ''' (single quotation mark). Defaults to // '"' (double quotation mark) if unspecified. Quote string `protobuf:"bytes,4,opt,name=quote,proto3" json:"quote,omitempty"` } diff --git a/dataplex/apiv1/dataplexpb/resources.pb.go b/dataplex/apiv1/dataplexpb/resources.pb.go index afbc17ae60e8..a8e2f58adf27 100644 --- a/dataplex/apiv1/dataplexpb/resources.pb.go +++ b/dataplex/apiv1/dataplexpb/resources.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dataplex/v1/resources.proto package dataplexpb @@ -1077,7 +1077,6 @@ type Action struct { // Additional details about the action based on the action category. // // Types that are assignable to Details: - // // *Action_InvalidDataFormat_ // *Action_IncompatibleDataSchema_ // *Action_InvalidDataPartition_ @@ -1669,7 +1668,6 @@ type Zone_DiscoverySpec struct { // Determines when discovery is triggered. // // Types that are assignable to Trigger: - // // *Zone_DiscoverySpec_Schedule Trigger isZone_DiscoverySpec_Trigger `protobuf_oneof:"trigger"` } @@ -2423,7 +2421,6 @@ type Asset_DiscoverySpec struct { // Determines when discovery is triggered. // // Types that are assignable to Trigger: - // // *Asset_DiscoverySpec_Schedule Trigger isAsset_DiscoverySpec_Trigger `protobuf_oneof:"trigger"` } @@ -2536,9 +2533,8 @@ type Asset_ResourceSpec struct { // Immutable. Relative name of the cloud resource that contains the data that is // being managed within a lake. For example: - // - // `projects/{project_number}/buckets/{bucket_id}` - // `projects/{project_number}/datasets/{dataset_id}` + // `projects/{project_number}/buckets/{bucket_id}` + // `projects/{project_number}/datasets/{dataset_id}` Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Required. Immutable. Type of resource. Type Asset_ResourceSpec_Type `protobuf:"varint,2,opt,name=type,proto3,enum=google.cloud.dataplex.v1.Asset_ResourceSpec_Type" json:"type,omitempty"` diff --git a/dataplex/apiv1/dataplexpb/service.pb.go b/dataplex/apiv1/dataplexpb/service.pb.go index a0651829be8b..c5a295581e1d 100644 --- a/dataplex/apiv1/dataplexpb/service.pb.go +++ b/dataplex/apiv1/dataplexpb/service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dataplex/v1/service.proto package dataplexpb diff --git a/dataplex/apiv1/dataplexpb/tasks.pb.go b/dataplex/apiv1/dataplexpb/tasks.pb.go index 3d8db8e71c05..809175eec7a8 100644 --- a/dataplex/apiv1/dataplexpb/tasks.pb.go +++ b/dataplex/apiv1/dataplexpb/tasks.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dataplex/v1/tasks.proto package dataplexpb @@ -241,7 +241,6 @@ type Task struct { // Task template specific user-specified config. // // Types that are assignable to Config: - // // *Task_Spark // *Task_Notebook Config isTask_Config `protobuf_oneof:"config"` @@ -527,19 +526,16 @@ type Task_InfrastructureSpec struct { // Hardware config. // // Types that are assignable to Resources: - // // *Task_InfrastructureSpec_Batch Resources isTask_InfrastructureSpec_Resources `protobuf_oneof:"resources"` // Software config. // // Types that are assignable to Runtime: - // // *Task_InfrastructureSpec_ContainerImage Runtime isTask_InfrastructureSpec_Runtime `protobuf_oneof:"runtime"` // Networking config. // // Types that are assignable to Network: - // // *Task_InfrastructureSpec_VpcNetwork_ Network isTask_InfrastructureSpec_Network `protobuf_oneof:"network"` } @@ -673,7 +669,6 @@ type Task_TriggerSpec struct { // Trigger only applies for RECURRING tasks. // // Types that are assignable to Trigger: - // // *Task_TriggerSpec_Schedule Trigger isTask_TriggerSpec_Trigger `protobuf_oneof:"trigger"` } @@ -882,7 +877,6 @@ type Task_SparkTaskConfig struct { // main class name. // // Types that are assignable to Driver: - // // *Task_SparkTaskConfig_MainJarFileUri // *Task_SparkTaskConfig_MainClass // *Task_SparkTaskConfig_PythonScriptFile @@ -1343,7 +1337,6 @@ type Task_InfrastructureSpec_VpcNetwork struct { // The Cloud VPC network identifier. // // Types that are assignable to NetworkName: - // // *Task_InfrastructureSpec_VpcNetwork_Network // *Task_InfrastructureSpec_VpcNetwork_SubNetwork NetworkName isTask_InfrastructureSpec_VpcNetwork_NetworkName `protobuf_oneof:"network_name"` diff --git a/dataplex/apiv1/doc.go b/dataplex/apiv1/doc.go index c91bf3692e02..c9f160ce8390 100644 --- a/dataplex/apiv1/doc.go +++ b/dataplex/apiv1/doc.go @@ -80,6 +80,8 @@ package dataplex // import "cloud.google.com/go/dataplex/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -168,3 +170,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/dataplex/apiv1/gapic_metadata.json b/dataplex/apiv1/gapic_metadata.json index e1c77a798360..47a87a901d76 100644 --- a/dataplex/apiv1/gapic_metadata.json +++ b/dataplex/apiv1/gapic_metadata.json @@ -81,6 +81,81 @@ ] } } + }, + "rest": { + "libraryClient": "ContentClient", + "rpcs": { + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "CreateContent": { + "methods": [ + "CreateContent" + ] + }, + "DeleteContent": { + "methods": [ + "DeleteContent" + ] + }, + "DeleteOperation": { + "methods": [ + "DeleteOperation" + ] + }, + "GetContent": { + "methods": [ + "GetContent" + ] + }, + "GetIamPolicy": { + "methods": [ + "GetIamPolicy" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ListContent": { + "methods": [ + "ListContent" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "SetIamPolicy": { + "methods": [ + "SetIamPolicy" + ] + }, + "TestIamPermissions": { + "methods": [ + "TestIamPermissions" + ] + }, + "UpdateContent": { + "methods": [ + "UpdateContent" + ] + } + } } } }, @@ -280,6 +355,201 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "CancelJob": { + "methods": [ + "CancelJob" + ] + }, + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "CreateAsset": { + "methods": [ + "CreateAsset" + ] + }, + "CreateEnvironment": { + "methods": [ + "CreateEnvironment" + ] + }, + "CreateLake": { + "methods": [ + "CreateLake" + ] + }, + "CreateTask": { + "methods": [ + "CreateTask" + ] + }, + "CreateZone": { + "methods": [ + "CreateZone" + ] + }, + "DeleteAsset": { + "methods": [ + "DeleteAsset" + ] + }, + "DeleteEnvironment": { + "methods": [ + "DeleteEnvironment" + ] + }, + "DeleteLake": { + "methods": [ + "DeleteLake" + ] + }, + "DeleteOperation": { + "methods": [ + "DeleteOperation" + ] + }, + "DeleteTask": { + "methods": [ + "DeleteTask" + ] + }, + "DeleteZone": { + "methods": [ + "DeleteZone" + ] + }, + "GetAsset": { + "methods": [ + "GetAsset" + ] + }, + "GetEnvironment": { + "methods": [ + "GetEnvironment" + ] + }, + "GetJob": { + "methods": [ + "GetJob" + ] + }, + "GetLake": { + "methods": [ + "GetLake" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "GetTask": { + "methods": [ + "GetTask" + ] + }, + "GetZone": { + "methods": [ + "GetZone" + ] + }, + "ListAssetActions": { + "methods": [ + "ListAssetActions" + ] + }, + "ListAssets": { + "methods": [ + "ListAssets" + ] + }, + "ListEnvironments": { + "methods": [ + "ListEnvironments" + ] + }, + "ListJobs": { + "methods": [ + "ListJobs" + ] + }, + "ListLakeActions": { + "methods": [ + "ListLakeActions" + ] + }, + "ListLakes": { + "methods": [ + "ListLakes" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "ListSessions": { + "methods": [ + "ListSessions" + ] + }, + "ListTasks": { + "methods": [ + "ListTasks" + ] + }, + "ListZoneActions": { + "methods": [ + "ListZoneActions" + ] + }, + "ListZones": { + "methods": [ + "ListZones" + ] + }, + "UpdateAsset": { + "methods": [ + "UpdateAsset" + ] + }, + "UpdateEnvironment": { + "methods": [ + "UpdateEnvironment" + ] + }, + "UpdateLake": { + "methods": [ + "UpdateLake" + ] + }, + "UpdateTask": { + "methods": [ + "UpdateTask" + ] + }, + "UpdateZone": { + "methods": [ + "UpdateZone" + ] + } + } } } }, @@ -364,6 +634,86 @@ ] } } + }, + "rest": { + "libraryClient": "MetadataClient", + "rpcs": { + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "CreateEntity": { + "methods": [ + "CreateEntity" + ] + }, + "CreatePartition": { + "methods": [ + "CreatePartition" + ] + }, + "DeleteEntity": { + "methods": [ + "DeleteEntity" + ] + }, + "DeleteOperation": { + "methods": [ + "DeleteOperation" + ] + }, + "DeletePartition": { + "methods": [ + "DeletePartition" + ] + }, + "GetEntity": { + "methods": [ + "GetEntity" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "GetPartition": { + "methods": [ + "GetPartition" + ] + }, + "ListEntities": { + "methods": [ + "ListEntities" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "ListPartitions": { + "methods": [ + "ListPartitions" + ] + }, + "UpdateEntity": { + "methods": [ + "UpdateEntity" + ] + } + } } } } diff --git a/dataplex/apiv1/metadata_client.go b/dataplex/apiv1/metadata_client.go index bdf2e31ed7ea..7215c786d79d 100644 --- a/dataplex/apiv1/metadata_client.go +++ b/dataplex/apiv1/metadata_client.go @@ -17,23 +17,29 @@ package dataplex import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" dataplexpb "cloud.google.com/go/dataplex/apiv1/dataplexpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -130,6 +136,62 @@ func defaultMetadataCallOptions() *MetadataCallOptions { } } +func defaultMetadataRESTCallOptions() *MetadataCallOptions { + return &MetadataCallOptions{ + CreateEntity: []gax.CallOption{}, + UpdateEntity: []gax.CallOption{}, + DeleteEntity: []gax.CallOption{}, + GetEntity: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListEntities: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreatePartition: []gax.CallOption{}, + DeletePartition: []gax.CallOption{}, + GetPartition: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListPartitions: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + CancelOperation: []gax.CallOption{}, + DeleteOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalMetadataClient is an interface that defines the methods available from Cloud Dataplex API. type internalMetadataClient interface { Close() error @@ -351,6 +413,75 @@ func (c *metadataGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type metadataRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing MetadataClient + CallOptions **MetadataCallOptions +} + +// NewMetadataRESTClient creates a new metadata service rest client. +// +// Metadata service manages metadata resources such as tables, filesets and +// partitions. +func NewMetadataRESTClient(ctx context.Context, opts ...option.ClientOption) (*MetadataClient, error) { + clientOpts := append(defaultMetadataRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultMetadataRESTCallOptions() + c := &metadataRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &MetadataClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultMetadataRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://dataplex.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://dataplex.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://dataplex.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *metadataRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *metadataRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *metadataRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *metadataGRPCClient) CreateEntity(ctx context.Context, req *dataplexpb.CreateEntityRequest, opts ...gax.CallOption) (*dataplexpb.Entity, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) @@ -737,6 +868,980 @@ func (c *metadataGRPCClient) ListOperations(ctx context.Context, req *longrunnin return it } +// CreateEntity create a metadata entity. +func (c *metadataRESTClient) CreateEntity(ctx context.Context, req *dataplexpb.CreateEntityRequest, opts ...gax.CallOption) (*dataplexpb.Entity, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetEntity() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/entities", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateEntity[0:len((*c.CallOptions).CreateEntity):len((*c.CallOptions).CreateEntity)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dataplexpb.Entity{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateEntity update a metadata entity. Only supports full resource update. +func (c *metadataRESTClient) UpdateEntity(ctx context.Context, req *dataplexpb.UpdateEntityRequest, opts ...gax.CallOption) (*dataplexpb.Entity, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetEntity() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetEntity().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "entity.name", url.QueryEscape(req.GetEntity().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateEntity[0:len((*c.CallOptions).UpdateEntity):len((*c.CallOptions).UpdateEntity)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dataplexpb.Entity{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PUT", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteEntity delete a metadata entity. +func (c *metadataRESTClient) DeleteEntity(ctx context.Context, req *dataplexpb.DeleteEntityRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("etag", fmt.Sprintf("%v", req.GetEtag())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetEntity get a metadata entity. +func (c *metadataRESTClient) GetEntity(ctx context.Context, req *dataplexpb.GetEntityRequest, opts ...gax.CallOption) (*dataplexpb.Entity, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetView() != 0 { + params.Add("view", fmt.Sprintf("%v", req.GetView())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetEntity[0:len((*c.CallOptions).GetEntity):len((*c.CallOptions).GetEntity)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dataplexpb.Entity{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListEntities list metadata entities in a zone. +func (c *metadataRESTClient) ListEntities(ctx context.Context, req *dataplexpb.ListEntitiesRequest, opts ...gax.CallOption) *EntityIterator { + it := &EntityIterator{} + req = proto.Clone(req).(*dataplexpb.ListEntitiesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*dataplexpb.Entity, string, error) { + resp := &dataplexpb.ListEntitiesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/entities", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + params.Add("view", fmt.Sprintf("%v", req.GetView())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetEntities(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CreatePartition create a metadata partition. +func (c *metadataRESTClient) CreatePartition(ctx context.Context, req *dataplexpb.CreatePartitionRequest, opts ...gax.CallOption) (*dataplexpb.Partition, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetPartition() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/partitions", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreatePartition[0:len((*c.CallOptions).CreatePartition):len((*c.CallOptions).CreatePartition)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dataplexpb.Partition{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeletePartition delete a metadata partition. +func (c *metadataRESTClient) DeletePartition(ctx context.Context, req *dataplexpb.DeletePartitionRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetEtag() != "" { + params.Add("etag", fmt.Sprintf("%v", req.GetEtag())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetPartition get a metadata partition of an entity. +func (c *metadataRESTClient) GetPartition(ctx context.Context, req *dataplexpb.GetPartitionRequest, opts ...gax.CallOption) (*dataplexpb.Partition, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetPartition[0:len((*c.CallOptions).GetPartition):len((*c.CallOptions).GetPartition)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dataplexpb.Partition{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListPartitions list metadata partitions of an entity. +func (c *metadataRESTClient) ListPartitions(ctx context.Context, req *dataplexpb.ListPartitionsRequest, opts ...gax.CallOption) *PartitionIterator { + it := &PartitionIterator{} + req = proto.Clone(req).(*dataplexpb.ListPartitionsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*dataplexpb.Partition, string, error) { + resp := &dataplexpb.ListPartitionsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/partitions", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetPartitions(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetLocation gets information about a location. +func (c *metadataRESTClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *metadataRESTClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *metadataRESTClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// DeleteOperation is a utility method from google.longrunning.Operations. +func (c *metadataRESTClient) DeleteOperation(ctx context.Context, req *longrunningpb.DeleteOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *metadataRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *metadataRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + // EntityIterator manages a stream of *dataplexpb.Entity. type EntityIterator struct { items []*dataplexpb.Entity diff --git a/dataplex/apiv1/metadata_client_example_test.go b/dataplex/apiv1/metadata_client_example_test.go index 7f4ae0d8c2b0..d0f893b42311 100644 --- a/dataplex/apiv1/metadata_client_example_test.go +++ b/dataplex/apiv1/metadata_client_example_test.go @@ -43,6 +43,23 @@ func ExampleNewMetadataClient() { _ = c } +func ExampleNewMetadataRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := dataplex.NewMetadataRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleMetadataClient_CreateEntity() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/dataproc/apiv1/autoscaling_policy_client.go b/dataproc/apiv1/autoscaling_policy_client.go index e5f1eba680dd..f6b2aee67ebe 100644 --- a/dataproc/apiv1/autoscaling_policy_client.go +++ b/dataproc/apiv1/autoscaling_policy_client.go @@ -17,21 +17,27 @@ package dataproc import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" dataprocpb "cloud.google.com/go/dataproc/apiv1/dataprocpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -101,6 +107,46 @@ func defaultAutoscalingPolicyCallOptions() *AutoscalingPolicyCallOptions { } } +func defaultAutoscalingPolicyRESTCallOptions() *AutoscalingPolicyCallOptions { + return &AutoscalingPolicyCallOptions{ + CreateAutoscalingPolicy: []gax.CallOption{}, + UpdateAutoscalingPolicy: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + GetAutoscalingPolicy: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + ListAutoscalingPolicies: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + DeleteAutoscalingPolicy: []gax.CallOption{}, + } +} + // internalAutoscalingPolicyClient is an interface that defines the methods available from Cloud Dataproc API. type internalAutoscalingPolicyClient interface { Close() error @@ -260,6 +306,75 @@ func (c *autoscalingPolicyGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type autoscalingPolicyRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing AutoscalingPolicyClient + CallOptions **AutoscalingPolicyCallOptions +} + +// NewAutoscalingPolicyRESTClient creates a new autoscaling policy service rest client. +// +// The API interface for managing autoscaling policies in the +// Dataproc API. +func NewAutoscalingPolicyRESTClient(ctx context.Context, opts ...option.ClientOption) (*AutoscalingPolicyClient, error) { + clientOpts := append(defaultAutoscalingPolicyRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultAutoscalingPolicyRESTCallOptions() + c := &autoscalingPolicyRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &AutoscalingPolicyClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultAutoscalingPolicyRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://dataproc.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://dataproc.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://dataproc.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *autoscalingPolicyRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *autoscalingPolicyRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *autoscalingPolicyRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *autoscalingPolicyGRPCClient) CreateAutoscalingPolicy(ctx context.Context, req *dataprocpb.CreateAutoscalingPolicyRequest, opts ...gax.CallOption) (*dataprocpb.AutoscalingPolicy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) @@ -389,6 +504,326 @@ func (c *autoscalingPolicyGRPCClient) DeleteAutoscalingPolicy(ctx context.Contex return err } +// CreateAutoscalingPolicy creates new autoscaling policy. +func (c *autoscalingPolicyRESTClient) CreateAutoscalingPolicy(ctx context.Context, req *dataprocpb.CreateAutoscalingPolicyRequest, opts ...gax.CallOption) (*dataprocpb.AutoscalingPolicy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetPolicy() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/autoscalingPolicies", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateAutoscalingPolicy[0:len((*c.CallOptions).CreateAutoscalingPolicy):len((*c.CallOptions).CreateAutoscalingPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dataprocpb.AutoscalingPolicy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateAutoscalingPolicy updates (replaces) autoscaling policy. +// +// Disabled check for update_mask, because all updates will be full +// replacements. +func (c *autoscalingPolicyRESTClient) UpdateAutoscalingPolicy(ctx context.Context, req *dataprocpb.UpdateAutoscalingPolicyRequest, opts ...gax.CallOption) (*dataprocpb.AutoscalingPolicy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetPolicy() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetPolicy().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "policy.name", url.QueryEscape(req.GetPolicy().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateAutoscalingPolicy[0:len((*c.CallOptions).UpdateAutoscalingPolicy):len((*c.CallOptions).UpdateAutoscalingPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dataprocpb.AutoscalingPolicy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PUT", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetAutoscalingPolicy retrieves autoscaling policy. +func (c *autoscalingPolicyRESTClient) GetAutoscalingPolicy(ctx context.Context, req *dataprocpb.GetAutoscalingPolicyRequest, opts ...gax.CallOption) (*dataprocpb.AutoscalingPolicy, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetAutoscalingPolicy[0:len((*c.CallOptions).GetAutoscalingPolicy):len((*c.CallOptions).GetAutoscalingPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dataprocpb.AutoscalingPolicy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListAutoscalingPolicies lists autoscaling policies in the project. +func (c *autoscalingPolicyRESTClient) ListAutoscalingPolicies(ctx context.Context, req *dataprocpb.ListAutoscalingPoliciesRequest, opts ...gax.CallOption) *AutoscalingPolicyIterator { + it := &AutoscalingPolicyIterator{} + req = proto.Clone(req).(*dataprocpb.ListAutoscalingPoliciesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*dataprocpb.AutoscalingPolicy, string, error) { + resp := &dataprocpb.ListAutoscalingPoliciesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/autoscalingPolicies", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetPolicies(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// DeleteAutoscalingPolicy deletes an autoscaling policy. It is an error to delete an autoscaling +// policy that is in use by one or more clusters. +func (c *autoscalingPolicyRESTClient) DeleteAutoscalingPolicy(ctx context.Context, req *dataprocpb.DeleteAutoscalingPolicyRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + // AutoscalingPolicyIterator manages a stream of *dataprocpb.AutoscalingPolicy. type AutoscalingPolicyIterator struct { items []*dataprocpb.AutoscalingPolicy diff --git a/dataproc/apiv1/autoscaling_policy_client_example_test.go b/dataproc/apiv1/autoscaling_policy_client_example_test.go index f8b36408ccbe..256ed9850fee 100644 --- a/dataproc/apiv1/autoscaling_policy_client_example_test.go +++ b/dataproc/apiv1/autoscaling_policy_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewAutoscalingPolicyClient() { _ = c } +func ExampleNewAutoscalingPolicyRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := dataproc.NewAutoscalingPolicyRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleAutoscalingPolicyClient_CreateAutoscalingPolicy() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/dataproc/apiv1/batch_controller_client.go b/dataproc/apiv1/batch_controller_client.go index 152890103a19..d2037289ee6e 100644 --- a/dataproc/apiv1/batch_controller_client.go +++ b/dataproc/apiv1/batch_controller_client.go @@ -17,9 +17,12 @@ package dataproc import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,13 +30,16 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -68,6 +74,15 @@ func defaultBatchControllerCallOptions() *BatchControllerCallOptions { } } +func defaultBatchControllerRESTCallOptions() *BatchControllerCallOptions { + return &BatchControllerCallOptions{ + CreateBatch: []gax.CallOption{}, + GetBatch: []gax.CallOption{}, + ListBatches: []gax.CallOption{}, + DeleteBatch: []gax.CallOption{}, + } +} + // internalBatchControllerClient is an interface that defines the methods available from Cloud Dataproc API. type internalBatchControllerClient interface { Close() error @@ -244,6 +259,89 @@ func (c *batchControllerGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type batchControllerRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing BatchControllerClient + CallOptions **BatchControllerCallOptions +} + +// NewBatchControllerRESTClient creates a new batch controller rest client. +// +// The BatchController provides methods to manage batch workloads. +func NewBatchControllerRESTClient(ctx context.Context, opts ...option.ClientOption) (*BatchControllerClient, error) { + clientOpts := append(defaultBatchControllerRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultBatchControllerRESTCallOptions() + c := &batchControllerRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &BatchControllerClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultBatchControllerRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://dataproc.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://dataproc.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://dataproc.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *batchControllerRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *batchControllerRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *batchControllerRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *batchControllerGRPCClient) CreateBatch(ctx context.Context, req *dataprocpb.CreateBatchRequest, opts ...gax.CallOption) (*CreateBatchOperation, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -338,9 +436,272 @@ func (c *batchControllerGRPCClient) DeleteBatch(ctx context.Context, req *datapr return err } +// CreateBatch creates a batch workload that executes asynchronously. +func (c *batchControllerRESTClient) CreateBatch(ctx context.Context, req *dataprocpb.CreateBatchRequest, opts ...gax.CallOption) (*CreateBatchOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetBatch() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/batches", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetBatchId() != "" { + params.Add("batchId", fmt.Sprintf("%v", req.GetBatchId())) + } + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateBatchOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetBatch gets the batch workload resource representation. +func (c *batchControllerRESTClient) GetBatch(ctx context.Context, req *dataprocpb.GetBatchRequest, opts ...gax.CallOption) (*dataprocpb.Batch, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetBatch[0:len((*c.CallOptions).GetBatch):len((*c.CallOptions).GetBatch)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dataprocpb.Batch{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListBatches lists batch workloads. +func (c *batchControllerRESTClient) ListBatches(ctx context.Context, req *dataprocpb.ListBatchesRequest, opts ...gax.CallOption) *BatchIterator { + it := &BatchIterator{} + req = proto.Clone(req).(*dataprocpb.ListBatchesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*dataprocpb.Batch, string, error) { + resp := &dataprocpb.ListBatchesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/batches", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetBatches(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// DeleteBatch deletes the batch workload resource. If the batch is not in terminal state, +// the delete fails and the response returns FAILED_PRECONDITION. +func (c *batchControllerRESTClient) DeleteBatch(ctx context.Context, req *dataprocpb.DeleteBatchRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + // CreateBatchOperation manages a long-running operation from CreateBatch. type CreateBatchOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateBatchOperation returns a new CreateBatchOperation from a given name. @@ -351,10 +712,21 @@ func (c *batchControllerGRPCClient) CreateBatchOperation(name string) *CreateBat } } +// CreateBatchOperation returns a new CreateBatchOperation from a given name. +// The name must be that of a previously created CreateBatchOperation, possibly from a different process. +func (c *batchControllerRESTClient) CreateBatchOperation(name string) *CreateBatchOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateBatchOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateBatchOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*dataprocpb.Batch, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp dataprocpb.Batch if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -372,6 +744,7 @@ func (op *CreateBatchOperation) Wait(ctx context.Context, opts ...gax.CallOption // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateBatchOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*dataprocpb.Batch, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp dataprocpb.Batch if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/dataproc/apiv1/batch_controller_client_example_test.go b/dataproc/apiv1/batch_controller_client_example_test.go index 09a9ea5e0073..98130acc6082 100644 --- a/dataproc/apiv1/batch_controller_client_example_test.go +++ b/dataproc/apiv1/batch_controller_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewBatchControllerClient() { _ = c } +func ExampleNewBatchControllerRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := dataproc.NewBatchControllerRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleBatchControllerClient_CreateBatch() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/dataproc/apiv1/cluster_controller_client.go b/dataproc/apiv1/cluster_controller_client.go index 1536a7d3538c..13aab204742c 100644 --- a/dataproc/apiv1/cluster_controller_client.go +++ b/dataproc/apiv1/cluster_controller_client.go @@ -17,9 +17,12 @@ package dataproc import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,14 +30,17 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -141,6 +147,77 @@ func defaultClusterControllerCallOptions() *ClusterControllerCallOptions { } } +func defaultClusterControllerRESTCallOptions() *ClusterControllerCallOptions { + return &ClusterControllerCallOptions{ + CreateCluster: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UpdateCluster: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + StopCluster: []gax.CallOption{}, + StartCluster: []gax.CallOption{}, + DeleteCluster: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetCluster: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusInternalServerError, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + ListClusters: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusInternalServerError, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + DiagnoseCluster: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + } +} + // internalClusterControllerClient is an interface that defines the methods available from Cloud Dataproc API. type internalClusterControllerClient interface { Close() error @@ -391,6 +468,90 @@ func (c *clusterControllerGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type clusterControllerRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing ClusterControllerClient + CallOptions **ClusterControllerCallOptions +} + +// NewClusterControllerRESTClient creates a new cluster controller rest client. +// +// The ClusterControllerService provides methods to manage clusters +// of Compute Engine instances. +func NewClusterControllerRESTClient(ctx context.Context, opts ...option.ClientOption) (*ClusterControllerClient, error) { + clientOpts := append(defaultClusterControllerRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultClusterControllerRESTCallOptions() + c := &clusterControllerRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &ClusterControllerClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultClusterControllerRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://dataproc.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://dataproc.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://dataproc.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *clusterControllerRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *clusterControllerRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *clusterControllerRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *clusterControllerGRPCClient) CreateCluster(ctx context.Context, req *dataprocpb.CreateClusterRequest, opts ...gax.CallOption) (*CreateClusterOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 300000*time.Millisecond) @@ -592,9 +753,606 @@ func (c *clusterControllerGRPCClient) DiagnoseCluster(ctx context.Context, req * }, nil } +// CreateCluster creates a cluster in a project. The returned +// Operation.metadata will be +// ClusterOperationMetadata (at https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#clusteroperationmetadata). +func (c *clusterControllerRESTClient) CreateCluster(ctx context.Context, req *dataprocpb.CreateClusterRequest, opts ...gax.CallOption) (*CreateClusterOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetCluster() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/projects/%v/regions/%v/clusters", req.GetProjectId(), req.GetRegion()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetActionOnFailedPrimaryWorkers() != 0 { + params.Add("actionOnFailedPrimaryWorkers", fmt.Sprintf("%v", req.GetActionOnFailedPrimaryWorkers())) + } + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "region", url.QueryEscape(req.GetRegion()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateClusterOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateCluster updates a cluster in a project. The returned +// Operation.metadata will be +// ClusterOperationMetadata (at https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#clusteroperationmetadata). +// The cluster must be in a [RUNNING][google.cloud.dataproc.v1.ClusterStatus.State] state or an error +// is returned. +func (c *clusterControllerRESTClient) UpdateCluster(ctx context.Context, req *dataprocpb.UpdateClusterRequest, opts ...gax.CallOption) (*UpdateClusterOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetCluster() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/projects/%v/regions/%v/clusters/%v", req.GetProjectId(), req.GetRegion(), req.GetClusterName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetGracefulDecommissionTimeout() != nil { + gracefulDecommissionTimeout, err := protojson.Marshal(req.GetGracefulDecommissionTimeout()) + if err != nil { + return nil, err + } + params.Add("gracefulDecommissionTimeout", string(gracefulDecommissionTimeout)) + } + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "region", url.QueryEscape(req.GetRegion()), "cluster_name", url.QueryEscape(req.GetClusterName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateClusterOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// StopCluster stops a cluster in a project. +func (c *clusterControllerRESTClient) StopCluster(ctx context.Context, req *dataprocpb.StopClusterRequest, opts ...gax.CallOption) (*StopClusterOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/projects/%v/regions/%v/clusters/%v:stop", req.GetProjectId(), req.GetRegion(), req.GetClusterName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "region", url.QueryEscape(req.GetRegion()), "cluster_name", url.QueryEscape(req.GetClusterName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &StopClusterOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// StartCluster starts a cluster in a project. +func (c *clusterControllerRESTClient) StartCluster(ctx context.Context, req *dataprocpb.StartClusterRequest, opts ...gax.CallOption) (*StartClusterOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/projects/%v/regions/%v/clusters/%v:start", req.GetProjectId(), req.GetRegion(), req.GetClusterName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "region", url.QueryEscape(req.GetRegion()), "cluster_name", url.QueryEscape(req.GetClusterName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &StartClusterOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteCluster deletes a cluster in a project. The returned +// Operation.metadata will be +// ClusterOperationMetadata (at https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#clusteroperationmetadata). +func (c *clusterControllerRESTClient) DeleteCluster(ctx context.Context, req *dataprocpb.DeleteClusterRequest, opts ...gax.CallOption) (*DeleteClusterOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/projects/%v/regions/%v/clusters/%v", req.GetProjectId(), req.GetRegion(), req.GetClusterName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetClusterUuid() != "" { + params.Add("clusterUuid", fmt.Sprintf("%v", req.GetClusterUuid())) + } + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "region", url.QueryEscape(req.GetRegion()), "cluster_name", url.QueryEscape(req.GetClusterName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteClusterOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetCluster gets the resource representation for a cluster in a project. +func (c *clusterControllerRESTClient) GetCluster(ctx context.Context, req *dataprocpb.GetClusterRequest, opts ...gax.CallOption) (*dataprocpb.Cluster, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/projects/%v/regions/%v/clusters/%v", req.GetProjectId(), req.GetRegion(), req.GetClusterName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "region", url.QueryEscape(req.GetRegion()), "cluster_name", url.QueryEscape(req.GetClusterName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetCluster[0:len((*c.CallOptions).GetCluster):len((*c.CallOptions).GetCluster)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dataprocpb.Cluster{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListClusters lists all regions/{region}/clusters in a project alphabetically. +func (c *clusterControllerRESTClient) ListClusters(ctx context.Context, req *dataprocpb.ListClustersRequest, opts ...gax.CallOption) *ClusterIterator { + it := &ClusterIterator{} + req = proto.Clone(req).(*dataprocpb.ListClustersRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*dataprocpb.Cluster, string, error) { + resp := &dataprocpb.ListClustersResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/projects/%v/regions/%v/clusters", req.GetProjectId(), req.GetRegion()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetClusters(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// DiagnoseCluster gets cluster diagnostic information. The returned +// Operation.metadata will be +// ClusterOperationMetadata (at https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#clusteroperationmetadata). +// After the operation completes, +// Operation.response +// contains +// DiagnoseClusterResults (at https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#diagnoseclusterresults). +func (c *clusterControllerRESTClient) DiagnoseCluster(ctx context.Context, req *dataprocpb.DiagnoseClusterRequest, opts ...gax.CallOption) (*DiagnoseClusterOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/projects/%v/regions/%v/clusters/%v:diagnose", req.GetProjectId(), req.GetRegion(), req.GetClusterName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "region", url.QueryEscape(req.GetRegion()), "cluster_name", url.QueryEscape(req.GetClusterName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DiagnoseClusterOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + // CreateClusterOperation manages a long-running operation from CreateCluster. type CreateClusterOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateClusterOperation returns a new CreateClusterOperation from a given name. @@ -605,10 +1363,21 @@ func (c *clusterControllerGRPCClient) CreateClusterOperation(name string) *Creat } } +// CreateClusterOperation returns a new CreateClusterOperation from a given name. +// The name must be that of a previously created CreateClusterOperation, possibly from a different process. +func (c *clusterControllerRESTClient) CreateClusterOperation(name string) *CreateClusterOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateClusterOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateClusterOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*dataprocpb.Cluster, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp dataprocpb.Cluster if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -626,6 +1395,7 @@ func (op *CreateClusterOperation) Wait(ctx context.Context, opts ...gax.CallOpti // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateClusterOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*dataprocpb.Cluster, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp dataprocpb.Cluster if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -663,7 +1433,8 @@ func (op *CreateClusterOperation) Name() string { // DeleteClusterOperation manages a long-running operation from DeleteCluster. type DeleteClusterOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteClusterOperation returns a new DeleteClusterOperation from a given name. @@ -674,10 +1445,21 @@ func (c *clusterControllerGRPCClient) DeleteClusterOperation(name string) *Delet } } +// DeleteClusterOperation returns a new DeleteClusterOperation from a given name. +// The name must be that of a previously created DeleteClusterOperation, possibly from a different process. +func (c *clusterControllerRESTClient) DeleteClusterOperation(name string) *DeleteClusterOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteClusterOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteClusterOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -691,6 +1473,7 @@ func (op *DeleteClusterOperation) Wait(ctx context.Context, opts ...gax.CallOpti // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteClusterOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -721,7 +1504,8 @@ func (op *DeleteClusterOperation) Name() string { // DiagnoseClusterOperation manages a long-running operation from DiagnoseCluster. type DiagnoseClusterOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DiagnoseClusterOperation returns a new DiagnoseClusterOperation from a given name. @@ -732,10 +1516,21 @@ func (c *clusterControllerGRPCClient) DiagnoseClusterOperation(name string) *Dia } } +// DiagnoseClusterOperation returns a new DiagnoseClusterOperation from a given name. +// The name must be that of a previously created DiagnoseClusterOperation, possibly from a different process. +func (c *clusterControllerRESTClient) DiagnoseClusterOperation(name string) *DiagnoseClusterOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DiagnoseClusterOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DiagnoseClusterOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*dataprocpb.DiagnoseClusterResults, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp dataprocpb.DiagnoseClusterResults if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -753,6 +1548,7 @@ func (op *DiagnoseClusterOperation) Wait(ctx context.Context, opts ...gax.CallOp // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DiagnoseClusterOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*dataprocpb.DiagnoseClusterResults, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp dataprocpb.DiagnoseClusterResults if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -790,7 +1586,8 @@ func (op *DiagnoseClusterOperation) Name() string { // StartClusterOperation manages a long-running operation from StartCluster. type StartClusterOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // StartClusterOperation returns a new StartClusterOperation from a given name. @@ -801,10 +1598,21 @@ func (c *clusterControllerGRPCClient) StartClusterOperation(name string) *StartC } } +// StartClusterOperation returns a new StartClusterOperation from a given name. +// The name must be that of a previously created StartClusterOperation, possibly from a different process. +func (c *clusterControllerRESTClient) StartClusterOperation(name string) *StartClusterOperation { + override := fmt.Sprintf("/v1/%s", name) + return &StartClusterOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *StartClusterOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*dataprocpb.Cluster, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp dataprocpb.Cluster if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -822,6 +1630,7 @@ func (op *StartClusterOperation) Wait(ctx context.Context, opts ...gax.CallOptio // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *StartClusterOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*dataprocpb.Cluster, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp dataprocpb.Cluster if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -859,7 +1668,8 @@ func (op *StartClusterOperation) Name() string { // StopClusterOperation manages a long-running operation from StopCluster. type StopClusterOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // StopClusterOperation returns a new StopClusterOperation from a given name. @@ -870,10 +1680,21 @@ func (c *clusterControllerGRPCClient) StopClusterOperation(name string) *StopClu } } +// StopClusterOperation returns a new StopClusterOperation from a given name. +// The name must be that of a previously created StopClusterOperation, possibly from a different process. +func (c *clusterControllerRESTClient) StopClusterOperation(name string) *StopClusterOperation { + override := fmt.Sprintf("/v1/%s", name) + return &StopClusterOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *StopClusterOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*dataprocpb.Cluster, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp dataprocpb.Cluster if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -891,6 +1712,7 @@ func (op *StopClusterOperation) Wait(ctx context.Context, opts ...gax.CallOption // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *StopClusterOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*dataprocpb.Cluster, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp dataprocpb.Cluster if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -928,7 +1750,8 @@ func (op *StopClusterOperation) Name() string { // UpdateClusterOperation manages a long-running operation from UpdateCluster. type UpdateClusterOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateClusterOperation returns a new UpdateClusterOperation from a given name. @@ -939,10 +1762,21 @@ func (c *clusterControllerGRPCClient) UpdateClusterOperation(name string) *Updat } } +// UpdateClusterOperation returns a new UpdateClusterOperation from a given name. +// The name must be that of a previously created UpdateClusterOperation, possibly from a different process. +func (c *clusterControllerRESTClient) UpdateClusterOperation(name string) *UpdateClusterOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateClusterOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateClusterOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*dataprocpb.Cluster, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp dataprocpb.Cluster if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -960,6 +1794,7 @@ func (op *UpdateClusterOperation) Wait(ctx context.Context, opts ...gax.CallOpti // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateClusterOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*dataprocpb.Cluster, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp dataprocpb.Cluster if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/dataproc/apiv1/cluster_controller_client_example_test.go b/dataproc/apiv1/cluster_controller_client_example_test.go index f0eca6853606..d16e179bcc9b 100644 --- a/dataproc/apiv1/cluster_controller_client_example_test.go +++ b/dataproc/apiv1/cluster_controller_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewClusterControllerClient() { _ = c } +func ExampleNewClusterControllerRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := dataproc.NewClusterControllerRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClusterControllerClient_CreateCluster() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/dataproc/apiv1/dataprocpb/autoscaling_policies.pb.go b/dataproc/apiv1/dataprocpb/autoscaling_policies.pb.go index 922b62079e3e..da5ce19ee682 100644 --- a/dataproc/apiv1/dataprocpb/autoscaling_policies.pb.go +++ b/dataproc/apiv1/dataprocpb/autoscaling_policies.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dataproc/v1/autoscaling_policies.proto package dataprocpb @@ -53,22 +53,22 @@ type AutoscalingPolicy struct { // The id must contain only letters (a-z, A-Z), numbers (0-9), // underscores (_), and hyphens (-). Cannot begin or end with underscore // or hyphen. Must consist of between 3 and 50 characters. + // Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` // Output only. The "resource name" of the autoscaling policy, as described // in https://cloud.google.com/apis/design/resource_names. // - // - For `projects.regions.autoscalingPolicies`, the resource name of the - // policy has the following format: - // `projects/{project_id}/regions/{region}/autoscalingPolicies/{policy_id}` + // * For `projects.regions.autoscalingPolicies`, the resource name of the + // policy has the following format: + // `projects/{project_id}/regions/{region}/autoscalingPolicies/{policy_id}` // - // - For `projects.locations.autoscalingPolicies`, the resource name of the - // policy has the following format: - // `projects/{project_id}/locations/{location}/autoscalingPolicies/{policy_id}` + // * For `projects.locations.autoscalingPolicies`, the resource name of the + // policy has the following format: + // `projects/{project_id}/locations/{location}/autoscalingPolicies/{policy_id}` Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` // Autoscaling algorithm for policy. // // Types that are assignable to Algorithm: - // // *AutoscalingPolicy_BasicAlgorithm Algorithm isAutoscalingPolicy_Algorithm `protobuf_oneof:"algorithm"` // Required. Describes how the autoscaler will operate for primary workers. @@ -183,7 +183,6 @@ type BasicAutoscalingAlgorithm struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Config: - // // *BasicAutoscalingAlgorithm_YarnConfig Config isBasicAutoscalingAlgorithm_Config `protobuf_oneof:"config"` // Optional. Duration between scaling events. A scaling period starts after @@ -479,13 +478,13 @@ type CreateAutoscalingPolicyRequest struct { // Required. The "resource name" of the region or location, as described // in https://cloud.google.com/apis/design/resource_names. // - // - For `projects.regions.autoscalingPolicies.create`, the resource name - // of the region has the following format: - // `projects/{project_id}/regions/{region}` + // * For `projects.regions.autoscalingPolicies.create`, the resource name + // of the region has the following format: + // `projects/{project_id}/regions/{region}` // - // - For `projects.locations.autoscalingPolicies.create`, the resource name - // of the location has the following format: - // `projects/{project_id}/locations/{location}` + // * For `projects.locations.autoscalingPolicies.create`, the resource name + // of the location has the following format: + // `projects/{project_id}/locations/{location}` Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // Required. The autoscaling policy to create. Policy *AutoscalingPolicy `protobuf:"bytes,2,opt,name=policy,proto3" json:"policy,omitempty"` @@ -546,13 +545,13 @@ type GetAutoscalingPolicyRequest struct { // Required. The "resource name" of the autoscaling policy, as described // in https://cloud.google.com/apis/design/resource_names. // - // - For `projects.regions.autoscalingPolicies.get`, the resource name - // of the policy has the following format: - // `projects/{project_id}/regions/{region}/autoscalingPolicies/{policy_id}` + // * For `projects.regions.autoscalingPolicies.get`, the resource name + // of the policy has the following format: + // `projects/{project_id}/regions/{region}/autoscalingPolicies/{policy_id}` // - // - For `projects.locations.autoscalingPolicies.get`, the resource name - // of the policy has the following format: - // `projects/{project_id}/locations/{location}/autoscalingPolicies/{policy_id}` + // * For `projects.locations.autoscalingPolicies.get`, the resource name + // of the policy has the following format: + // `projects/{project_id}/locations/{location}/autoscalingPolicies/{policy_id}` Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` } @@ -655,13 +654,13 @@ type DeleteAutoscalingPolicyRequest struct { // Required. The "resource name" of the autoscaling policy, as described // in https://cloud.google.com/apis/design/resource_names. // - // - For `projects.regions.autoscalingPolicies.delete`, the resource name - // of the policy has the following format: - // `projects/{project_id}/regions/{region}/autoscalingPolicies/{policy_id}` + // * For `projects.regions.autoscalingPolicies.delete`, the resource name + // of the policy has the following format: + // `projects/{project_id}/regions/{region}/autoscalingPolicies/{policy_id}` // - // - For `projects.locations.autoscalingPolicies.delete`, the resource name - // of the policy has the following format: - // `projects/{project_id}/locations/{location}/autoscalingPolicies/{policy_id}` + // * For `projects.locations.autoscalingPolicies.delete`, the resource name + // of the policy has the following format: + // `projects/{project_id}/locations/{location}/autoscalingPolicies/{policy_id}` Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` } @@ -713,13 +712,13 @@ type ListAutoscalingPoliciesRequest struct { // Required. The "resource name" of the region or location, as described // in https://cloud.google.com/apis/design/resource_names. // - // - For `projects.regions.autoscalingPolicies.list`, the resource name - // of the region has the following format: - // `projects/{project_id}/regions/{region}` + // * For `projects.regions.autoscalingPolicies.list`, the resource name + // of the region has the following format: + // `projects/{project_id}/regions/{region}` // - // - For `projects.locations.autoscalingPolicies.list`, the resource name - // of the location has the following format: - // `projects/{project_id}/locations/{location}` + // * For `projects.locations.autoscalingPolicies.list`, the resource name + // of the location has the following format: + // `projects/{project_id}/locations/{location}` Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // Optional. The maximum number of results to return in each response. // Must be less than or equal to 1000. Defaults to 100. diff --git a/dataproc/apiv1/dataprocpb/batches.pb.go b/dataproc/apiv1/dataprocpb/batches.pb.go index 16110524d2aa..edb232849e22 100644 --- a/dataproc/apiv1/dataprocpb/batches.pb.go +++ b/dataproc/apiv1/dataprocpb/batches.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dataproc/v1/batches.proto package dataprocpb @@ -445,7 +445,6 @@ type Batch struct { // The application/framework-specific portion of the batch configuration. // // Types that are assignable to BatchConfig: - // // *Batch_PysparkBatch // *Batch_SparkBatch // *Batch_SparkRBatch @@ -789,7 +788,6 @@ type SparkBatch struct { // name in `main_class`. // // Types that are assignable to Driver: - // // *SparkBatch_MainJarFileUri // *SparkBatch_MainClass Driver isSparkBatch_Driver `protobuf_oneof:"driver"` diff --git a/dataproc/apiv1/dataprocpb/clusters.pb.go b/dataproc/apiv1/dataprocpb/clusters.pb.go index 70089e040b0b..bea71b9d89f6 100644 --- a/dataproc/apiv1/dataprocpb/clusters.pb.go +++ b/dataproc/apiv1/dataprocpb/clusters.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dataproc/v1/clusters.proto package dataprocpb @@ -642,13 +642,13 @@ type ClusterConfig struct { // a master or worker node, as shown below using `curl` (you can also use // `wget`): // - // ROLE=$(curl -H Metadata-Flavor:Google - // http://metadata/computeMetadata/v1/instance/attributes/dataproc-role) - // if [[ "${ROLE}" == 'Master' ]]; then - // ... master specific actions ... - // else - // ... worker specific actions ... - // fi + // ROLE=$(curl -H Metadata-Flavor:Google + // http://metadata/computeMetadata/v1/instance/attributes/dataproc-role) + // if [[ "${ROLE}" == 'Master' ]]; then + // ... master specific actions ... + // else + // ... worker specific actions ... + // fi InitializationActions []*NodeInitializationAction `protobuf:"bytes,11,rep,name=initialization_actions,json=initializationActions,proto3" json:"initialization_actions,omitempty"` // Optional. Encryption settings for the cluster. EncryptionConfig *EncryptionConfig `protobuf:"bytes,15,opt,name=encryption_config,json=encryptionConfig,proto3" json:"encryption_config,omitempty"` @@ -825,7 +825,6 @@ type VirtualClusterConfig struct { // a Cloud Storage bucket.** StagingBucket string `protobuf:"bytes,1,opt,name=staging_bucket,json=stagingBucket,proto3" json:"staging_bucket,omitempty"` // Types that are assignable to InfrastructureConfig: - // // *VirtualClusterConfig_KubernetesClusterConfig InfrastructureConfig isVirtualClusterConfig_InfrastructureConfig `protobuf_oneof:"infrastructure_config"` // Optional. Configuration of auxiliary services used by this cluster. @@ -2479,7 +2478,6 @@ type LifecycleConfig struct { // the cluster maximum age. // // Types that are assignable to Ttl: - // // *LifecycleConfig_AutoDeleteTime // *LifecycleConfig_AutoDeleteTtl Ttl isLifecycleConfig_Ttl `protobuf_oneof:"ttl"` @@ -2869,53 +2867,51 @@ type UpdateClusterRequest struct { // specified as `config.worker_config.num_instances`, // and the `PATCH` request body would specify the new value, as follows: // - // { - // "config":{ - // "workerConfig":{ - // "numInstances":"5" - // } - // } - // } - // + // { + // "config":{ + // "workerConfig":{ + // "numInstances":"5" + // } + // } + // } // Similarly, to change the number of preemptible workers in a cluster to 5, // the `update_mask` parameter would be // `config.secondary_worker_config.num_instances`, and the `PATCH` request // body would be set as follows: // - // { - // "config":{ - // "secondaryWorkerConfig":{ - // "numInstances":"5" - // } - // } - // } - // + // { + // "config":{ + // "secondaryWorkerConfig":{ + // "numInstances":"5" + // } + // } + // } // Note: Currently, only the following fields can be updated: // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - //
MaskPurpose
labelsUpdate labels
config.worker_config.num_instancesResize primary worker group
config.secondary_worker_config.num_instancesResize secondary worker group
config.autoscaling_config.policy_uriUse, stop using, or - // change autoscaling policies
+ // + // + // + // + // + // + // + // + // + // + // + // + // + // + // + // + // + // + // + // + // + // + //
MaskPurpose
labelsUpdate labels
config.worker_config.num_instancesResize primary worker group
config.secondary_worker_config.num_instancesResize secondary worker group
config.autoscaling_config.policy_uriUse, stop using, or + // change autoscaling policies
UpdateMask *fieldmaskpb.FieldMask `protobuf:"bytes,4,opt,name=update_mask,json=updateMask,proto3" json:"update_mask,omitempty"` // Optional. A unique ID used to identify the request. If the server // receives two @@ -3758,13 +3754,13 @@ type DataprocMetricConfig_Metric struct { // // Notes: // - // - Only the specified overridden metrics will be collected for the - // metric source. For example, if one or more `spark:executive` metrics - // are listed as metric overrides, other `SPARK` metrics will not be - // collected. The collection of the default metrics for other OSS metric - // sources is unaffected. For example, if both `SPARK` andd `YARN` metric - // sources are enabled, and overrides are provided for Spark metrics only, - // all default YARN metrics will be collected. + // * Only the specified overridden metrics will be collected for the + // metric source. For example, if one or more `spark:executive` metrics + // are listed as metric overrides, other `SPARK` metrics will not be + // collected. The collection of the default metrics for other OSS metric + // sources is unaffected. For example, if both `SPARK` andd `YARN` metric + // sources are enabled, and overrides are provided for Spark metrics only, + // all default YARN metrics will be collected. MetricOverrides []string `protobuf:"bytes,2,rep,name=metric_overrides,json=metricOverrides,proto3" json:"metric_overrides,omitempty"` } diff --git a/dataproc/apiv1/dataprocpb/jobs.pb.go b/dataproc/apiv1/dataprocpb/jobs.pb.go index 8ae2ad6a0341..042024c6821a 100644 --- a/dataproc/apiv1/dataprocpb/jobs.pb.go +++ b/dataproc/apiv1/dataprocpb/jobs.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dataproc/v1/jobs.proto package dataprocpb @@ -417,8 +417,7 @@ type LoggingConfig struct { // The per-package log levels for the driver. This may include // "root" package name to configure rootLogger. // Examples: - // - // 'com.google = FATAL', 'root = INFO', 'org.apache = DEBUG' + // 'com.google = FATAL', 'root = INFO', 'org.apache = DEBUG' DriverLogLevels map[string]LoggingConfig_Level `protobuf:"bytes,2,rep,name=driver_log_levels,json=driverLogLevels,proto3" json:"driver_log_levels,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"varint,2,opt,name=value,proto3,enum=google.cloud.dataproc.v1.LoggingConfig_Level"` } @@ -477,7 +476,6 @@ type HadoopJob struct { // the main class name in this property. // // Types that are assignable to Driver: - // // *HadoopJob_MainJarFileUri // *HadoopJob_MainClass Driver isHadoopJob_Driver `protobuf_oneof:"driver"` @@ -608,10 +606,9 @@ type isHadoopJob_Driver interface { type HadoopJob_MainJarFileUri struct { // The HCFS URI of the jar file containing the main class. // Examples: - // - // 'gs://foo-bucket/analytics-binaries/extract-useful-metrics-mr.jar' - // 'hdfs:/tmp/test-samples/custom-wordcount.jar' - // 'file:///home/usr/lib/hadoop-mapreduce/hadoop-mapreduce-examples.jar' + // 'gs://foo-bucket/analytics-binaries/extract-useful-metrics-mr.jar' + // 'hdfs:/tmp/test-samples/custom-wordcount.jar' + // 'file:///home/usr/lib/hadoop-mapreduce/hadoop-mapreduce-examples.jar' MainJarFileUri string `protobuf:"bytes,1,opt,name=main_jar_file_uri,json=mainJarFileUri,proto3,oneof"` } @@ -639,7 +636,6 @@ type SparkJob struct { // `main_class`. // // Types that are assignable to Driver: - // // *SparkJob_MainJarFileUri // *SparkJob_MainClass Driver isSparkJob_Driver `protobuf_oneof:"driver"` @@ -917,15 +913,15 @@ type QueryList struct { // string by separating each with a semicolon. Here is an example of a // Dataproc API snippet that uses a QueryList to specify a HiveJob: // - // "hiveJob": { - // "queryList": { - // "queries": [ - // "query1", - // "query2", - // "query3;query4", - // ] - // } - // } + // "hiveJob": { + // "queryList": { + // "queries": [ + // "query1", + // "query2", + // "query3;query4", + // ] + // } + // } Queries []string `protobuf:"bytes,1,rep,name=queries,proto3" json:"queries,omitempty"` } @@ -979,7 +975,6 @@ type HiveJob struct { // an HCFS file URI or a list of queries. // // Types that are assignable to Queries: - // // *HiveJob_QueryFileUri // *HiveJob_QueryList Queries isHiveJob_Queries `protobuf_oneof:"queries"` @@ -1111,7 +1106,6 @@ type SparkSqlJob struct { // either an HCFS file URI or as a list of queries. // // Types that are assignable to Queries: - // // *SparkSqlJob_QueryFileUri // *SparkSqlJob_QueryList Queries isSparkSqlJob_Queries `protobuf_oneof:"queries"` @@ -1238,7 +1232,6 @@ type PigJob struct { // file URI or a list of queries. // // Types that are assignable to Queries: - // // *PigJob_QueryFileUri // *PigJob_QueryList Queries isPigJob_Queries `protobuf_oneof:"queries"` @@ -1486,7 +1479,6 @@ type PrestoJob struct { // either an HCFS file URI or as a list of queries. // // Types that are assignable to Queries: - // // *PrestoJob_QueryFileUri // *PrestoJob_QueryList Queries isPrestoJob_Queries `protobuf_oneof:"queries"` @@ -1923,7 +1915,6 @@ type Job struct { // Required. The application/framework-specific portion of the job. // // Types that are assignable to TypeJob: - // // *Job_HadoopJob // *Job_SparkJob // *Job_PysparkJob diff --git a/dataproc/apiv1/dataprocpb/operations.pb.go b/dataproc/apiv1/dataprocpb/operations.pb.go index b36fbe97df45..aa495256ebea 100644 --- a/dataproc/apiv1/dataprocpb/operations.pb.go +++ b/dataproc/apiv1/dataprocpb/operations.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dataproc/v1/operations.proto package dataprocpb diff --git a/dataproc/apiv1/dataprocpb/shared.pb.go b/dataproc/apiv1/dataprocpb/shared.pb.go index 1e09a91e12d5..33b1e3145160 100644 --- a/dataproc/apiv1/dataprocpb/shared.pb.go +++ b/dataproc/apiv1/dataprocpb/shared.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dataproc/v1/shared.proto package dataprocpb @@ -390,7 +390,6 @@ type ExecutionConfig struct { // Network configuration for workload execution. // // Types that are assignable to Network: - // // *ExecutionConfig_NetworkUri // *ExecutionConfig_SubnetworkUri Network isExecutionConfig_Network `protobuf_oneof:"network"` @@ -752,7 +751,6 @@ type KubernetesClusterConfig struct { // into it. If not specified, the name of the Dataproc Cluster is used. KubernetesNamespace string `protobuf:"bytes,1,opt,name=kubernetes_namespace,json=kubernetesNamespace,proto3" json:"kubernetes_namespace,omitempty"` // Types that are assignable to Config: - // // *KubernetesClusterConfig_GkeClusterConfig Config isKubernetesClusterConfig_Config `protobuf_oneof:"config"` // Optional. The software configuration for this Dataproc cluster running on Kubernetes. diff --git a/dataproc/apiv1/dataprocpb/workflow_templates.pb.go b/dataproc/apiv1/dataprocpb/workflow_templates.pb.go index 7e43de8934c5..3ec8761fe7b6 100644 --- a/dataproc/apiv1/dataprocpb/workflow_templates.pb.go +++ b/dataproc/apiv1/dataprocpb/workflow_templates.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dataproc/v1/workflow_templates.proto package dataprocpb @@ -177,13 +177,13 @@ type WorkflowTemplate struct { // Output only. The resource name of the workflow template, as described // in https://cloud.google.com/apis/design/resource_names. // - // - For `projects.regions.workflowTemplates`, the resource name of the - // template has the following format: - // `projects/{project_id}/regions/{region}/workflowTemplates/{template_id}` + // * For `projects.regions.workflowTemplates`, the resource name of the + // template has the following format: + // `projects/{project_id}/regions/{region}/workflowTemplates/{template_id}` // - // - For `projects.locations.workflowTemplates`, the resource name of the - // template has the following format: - // `projects/{project_id}/locations/{location}/workflowTemplates/{template_id}` + // * For `projects.locations.workflowTemplates`, the resource name of the + // template has the following format: + // `projects/{project_id}/locations/{location}/workflowTemplates/{template_id}` Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Optional. Used to perform a consistent read-modify-write. // @@ -347,7 +347,6 @@ type WorkflowTemplatePlacement struct { // cluster or an existing cluster chosen by labels. // // Types that are assignable to Placement: - // // *WorkflowTemplatePlacement_ManagedCluster // *WorkflowTemplatePlacement_ClusterSelector Placement isWorkflowTemplatePlacement_Placement `protobuf_oneof:"placement"` @@ -592,7 +591,6 @@ type OrderedJob struct { // Required. The job definition. // // Types that are assignable to JobType: - // // *OrderedJob_HadoopJob // *OrderedJob_SparkJob // *OrderedJob_PysparkJob @@ -837,30 +835,30 @@ type TemplateParameter struct { // Also, field paths can reference fields using the following syntax: // // * Values in maps can be referenced by key: - // - labels['key'] - // - placement.clusterSelector.clusterLabels['key'] - // - placement.managedCluster.labels['key'] - // - placement.clusterSelector.clusterLabels['key'] - // - jobs['step-id'].labels['key'] + // * labels['key'] + // * placement.clusterSelector.clusterLabels['key'] + // * placement.managedCluster.labels['key'] + // * placement.clusterSelector.clusterLabels['key'] + // * jobs['step-id'].labels['key'] // // * Jobs in the jobs list can be referenced by step-id: - // - jobs['step-id'].hadoopJob.mainJarFileUri - // - jobs['step-id'].hiveJob.queryFileUri - // - jobs['step-id'].pySparkJob.mainPythonFileUri - // - jobs['step-id'].hadoopJob.jarFileUris[0] - // - jobs['step-id'].hadoopJob.archiveUris[0] - // - jobs['step-id'].hadoopJob.fileUris[0] - // - jobs['step-id'].pySparkJob.pythonFileUris[0] + // * jobs['step-id'].hadoopJob.mainJarFileUri + // * jobs['step-id'].hiveJob.queryFileUri + // * jobs['step-id'].pySparkJob.mainPythonFileUri + // * jobs['step-id'].hadoopJob.jarFileUris[0] + // * jobs['step-id'].hadoopJob.archiveUris[0] + // * jobs['step-id'].hadoopJob.fileUris[0] + // * jobs['step-id'].pySparkJob.pythonFileUris[0] // // * Items in repeated fields can be referenced by a zero-based index: - // - jobs['step-id'].sparkJob.args[0] + // * jobs['step-id'].sparkJob.args[0] // // * Other examples: - // - jobs['step-id'].hadoopJob.properties['key'] - // - jobs['step-id'].hadoopJob.args[0] - // - jobs['step-id'].hiveJob.scriptVariables['key'] - // - jobs['step-id'].hadoopJob.mainJarFileUri - // - placement.clusterSelector.zone + // * jobs['step-id'].hadoopJob.properties['key'] + // * jobs['step-id'].hadoopJob.args[0] + // * jobs['step-id'].hiveJob.scriptVariables['key'] + // * jobs['step-id'].hadoopJob.mainJarFileUri + // * placement.clusterSelector.zone // // It may not be possible to parameterize maps and repeated fields in their // entirety since only individual map values and individual items in repeated @@ -946,7 +944,6 @@ type ParameterValidation struct { // Required. The type of validation to be performed. // // Types that are assignable to ValidationType: - // // *ParameterValidation_Regex // *ParameterValidation_Values ValidationType isParameterValidation_ValidationType `protobuf_oneof:"validation_type"` @@ -1132,13 +1129,13 @@ type WorkflowMetadata struct { // Output only. The resource name of the workflow template as described // in https://cloud.google.com/apis/design/resource_names. // - // - For `projects.regions.workflowTemplates`, the resource name of the - // template has the following format: - // `projects/{project_id}/regions/{region}/workflowTemplates/{template_id}` + // * For `projects.regions.workflowTemplates`, the resource name of the + // template has the following format: + // `projects/{project_id}/regions/{region}/workflowTemplates/{template_id}` // - // - For `projects.locations.workflowTemplates`, the resource name of the - // template has the following format: - // `projects/{project_id}/locations/{location}/workflowTemplates/{template_id}` + // * For `projects.locations.workflowTemplates`, the resource name of the + // template has the following format: + // `projects/{project_id}/locations/{location}/workflowTemplates/{template_id}` Template string `protobuf:"bytes,1,opt,name=template,proto3" json:"template,omitempty"` // Output only. The version of template at the time of // workflow instantiation. @@ -1512,13 +1509,13 @@ type CreateWorkflowTemplateRequest struct { // Required. The resource name of the region or location, as described // in https://cloud.google.com/apis/design/resource_names. // - // - For `projects.regions.workflowTemplates.create`, the resource name of the - // region has the following format: - // `projects/{project_id}/regions/{region}` + // * For `projects.regions.workflowTemplates.create`, the resource name of the + // region has the following format: + // `projects/{project_id}/regions/{region}` // - // - For `projects.locations.workflowTemplates.create`, the resource name of - // the location has the following format: - // `projects/{project_id}/locations/{location}` + // * For `projects.locations.workflowTemplates.create`, the resource name of + // the location has the following format: + // `projects/{project_id}/locations/{location}` Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // Required. The Dataproc workflow template to create. Template *WorkflowTemplate `protobuf:"bytes,2,opt,name=template,proto3" json:"template,omitempty"` @@ -1579,13 +1576,13 @@ type GetWorkflowTemplateRequest struct { // Required. The resource name of the workflow template, as described // in https://cloud.google.com/apis/design/resource_names. // - // - For `projects.regions.workflowTemplates.get`, the resource name of the - // template has the following format: - // `projects/{project_id}/regions/{region}/workflowTemplates/{template_id}` + // * For `projects.regions.workflowTemplates.get`, the resource name of the + // template has the following format: + // `projects/{project_id}/regions/{region}/workflowTemplates/{template_id}` // - // - For `projects.locations.workflowTemplates.get`, the resource name of the - // template has the following format: - // `projects/{project_id}/locations/{location}/workflowTemplates/{template_id}` + // * For `projects.locations.workflowTemplates.get`, the resource name of the + // template has the following format: + // `projects/{project_id}/locations/{location}/workflowTemplates/{template_id}` Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Optional. The version of workflow template to retrieve. Only previously // instantiated versions can be retrieved. @@ -1651,12 +1648,11 @@ type InstantiateWorkflowTemplateRequest struct { // // * For `projects.regions.workflowTemplates.instantiate`, the resource name // of the template has the following format: + // `projects/{project_id}/regions/{region}/workflowTemplates/{template_id}` // - // `projects/{project_id}/regions/{region}/workflowTemplates/{template_id}` - // - // - For `projects.locations.workflowTemplates.instantiate`, the resource name - // of the template has the following format: - // `projects/{project_id}/locations/{location}/workflowTemplates/{template_id}` + // * For `projects.locations.workflowTemplates.instantiate`, the resource name + // of the template has the following format: + // `projects/{project_id}/locations/{location}/workflowTemplates/{template_id}` Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Optional. The version of workflow template to instantiate. If specified, // the workflow will be instantiated only if the current version of @@ -1749,13 +1745,13 @@ type InstantiateInlineWorkflowTemplateRequest struct { // Required. The resource name of the region or location, as described // in https://cloud.google.com/apis/design/resource_names. // - // - For `projects.regions.workflowTemplates,instantiateinline`, the resource - // name of the region has the following format: - // `projects/{project_id}/regions/{region}` + // * For `projects.regions.workflowTemplates,instantiateinline`, the resource + // name of the region has the following format: + // `projects/{project_id}/regions/{region}` // - // - For `projects.locations.workflowTemplates.instantiateinline`, the - // resource name of the location has the following format: - // `projects/{project_id}/locations/{location}` + // * For `projects.locations.workflowTemplates.instantiateinline`, the + // resource name of the location has the following format: + // `projects/{project_id}/locations/{location}` Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // Required. The workflow template to instantiate. Template *WorkflowTemplate `protobuf:"bytes,2,opt,name=template,proto3" json:"template,omitempty"` @@ -1884,13 +1880,13 @@ type ListWorkflowTemplatesRequest struct { // Required. The resource name of the region or location, as described // in https://cloud.google.com/apis/design/resource_names. // - // - For `projects.regions.workflowTemplates,list`, the resource - // name of the region has the following format: - // `projects/{project_id}/regions/{region}` + // * For `projects.regions.workflowTemplates,list`, the resource + // name of the region has the following format: + // `projects/{project_id}/regions/{region}` // - // - For `projects.locations.workflowTemplates.list`, the - // resource name of the location has the following format: - // `projects/{project_id}/locations/{location}` + // * For `projects.locations.workflowTemplates.list`, the + // resource name of the location has the following format: + // `projects/{project_id}/locations/{location}` Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // Optional. The maximum number of results to return in each response. PageSize int32 `protobuf:"varint,2,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"` @@ -2025,12 +2021,11 @@ type DeleteWorkflowTemplateRequest struct { // // * For `projects.regions.workflowTemplates.delete`, the resource name // of the template has the following format: + // `projects/{project_id}/regions/{region}/workflowTemplates/{template_id}` // - // `projects/{project_id}/regions/{region}/workflowTemplates/{template_id}` - // - // - For `projects.locations.workflowTemplates.instantiate`, the resource name - // of the template has the following format: - // `projects/{project_id}/locations/{location}/workflowTemplates/{template_id}` + // * For `projects.locations.workflowTemplates.instantiate`, the resource name + // of the template has the following format: + // `projects/{project_id}/locations/{location}/workflowTemplates/{template_id}` Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Optional. The version of workflow template to delete. If specified, // will only delete the template if the current server version matches diff --git a/dataproc/apiv1/doc.go b/dataproc/apiv1/doc.go index 07728120628c..04d92c1fea27 100644 --- a/dataproc/apiv1/doc.go +++ b/dataproc/apiv1/doc.go @@ -80,6 +80,8 @@ package dataproc // import "cloud.google.com/go/dataproc/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -168,3 +170,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/dataproc/apiv1/gapic_metadata.json b/dataproc/apiv1/gapic_metadata.json index 5a2ad2f2bb1c..4ba8949bc088 100644 --- a/dataproc/apiv1/gapic_metadata.json +++ b/dataproc/apiv1/gapic_metadata.json @@ -36,6 +36,36 @@ ] } } + }, + "rest": { + "libraryClient": "AutoscalingPolicyClient", + "rpcs": { + "CreateAutoscalingPolicy": { + "methods": [ + "CreateAutoscalingPolicy" + ] + }, + "DeleteAutoscalingPolicy": { + "methods": [ + "DeleteAutoscalingPolicy" + ] + }, + "GetAutoscalingPolicy": { + "methods": [ + "GetAutoscalingPolicy" + ] + }, + "ListAutoscalingPolicies": { + "methods": [ + "ListAutoscalingPolicies" + ] + }, + "UpdateAutoscalingPolicy": { + "methods": [ + "UpdateAutoscalingPolicy" + ] + } + } } } }, @@ -65,6 +95,31 @@ ] } } + }, + "rest": { + "libraryClient": "BatchControllerClient", + "rpcs": { + "CreateBatch": { + "methods": [ + "CreateBatch" + ] + }, + "DeleteBatch": { + "methods": [ + "DeleteBatch" + ] + }, + "GetBatch": { + "methods": [ + "GetBatch" + ] + }, + "ListBatches": { + "methods": [ + "ListBatches" + ] + } + } } } }, @@ -114,6 +169,51 @@ ] } } + }, + "rest": { + "libraryClient": "ClusterControllerClient", + "rpcs": { + "CreateCluster": { + "methods": [ + "CreateCluster" + ] + }, + "DeleteCluster": { + "methods": [ + "DeleteCluster" + ] + }, + "DiagnoseCluster": { + "methods": [ + "DiagnoseCluster" + ] + }, + "GetCluster": { + "methods": [ + "GetCluster" + ] + }, + "ListClusters": { + "methods": [ + "ListClusters" + ] + }, + "StartCluster": { + "methods": [ + "StartCluster" + ] + }, + "StopCluster": { + "methods": [ + "StopCluster" + ] + }, + "UpdateCluster": { + "methods": [ + "UpdateCluster" + ] + } + } } } }, @@ -158,6 +258,46 @@ ] } } + }, + "rest": { + "libraryClient": "JobControllerClient", + "rpcs": { + "CancelJob": { + "methods": [ + "CancelJob" + ] + }, + "DeleteJob": { + "methods": [ + "DeleteJob" + ] + }, + "GetJob": { + "methods": [ + "GetJob" + ] + }, + "ListJobs": { + "methods": [ + "ListJobs" + ] + }, + "SubmitJob": { + "methods": [ + "SubmitJob" + ] + }, + "SubmitJobAsOperation": { + "methods": [ + "SubmitJobAsOperation" + ] + }, + "UpdateJob": { + "methods": [ + "UpdateJob" + ] + } + } } } }, @@ -202,6 +342,46 @@ ] } } + }, + "rest": { + "libraryClient": "WorkflowTemplateClient", + "rpcs": { + "CreateWorkflowTemplate": { + "methods": [ + "CreateWorkflowTemplate" + ] + }, + "DeleteWorkflowTemplate": { + "methods": [ + "DeleteWorkflowTemplate" + ] + }, + "GetWorkflowTemplate": { + "methods": [ + "GetWorkflowTemplate" + ] + }, + "InstantiateInlineWorkflowTemplate": { + "methods": [ + "InstantiateInlineWorkflowTemplate" + ] + }, + "InstantiateWorkflowTemplate": { + "methods": [ + "InstantiateWorkflowTemplate" + ] + }, + "ListWorkflowTemplates": { + "methods": [ + "ListWorkflowTemplates" + ] + }, + "UpdateWorkflowTemplate": { + "methods": [ + "UpdateWorkflowTemplate" + ] + } + } } } } diff --git a/dataproc/apiv1/job_controller_client.go b/dataproc/apiv1/job_controller_client.go index adfd7ef91b9b..e559dcaee4d7 100644 --- a/dataproc/apiv1/job_controller_client.go +++ b/dataproc/apiv1/job_controller_client.go @@ -17,9 +17,12 @@ package dataproc import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,14 +30,17 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -151,6 +157,87 @@ func defaultJobControllerCallOptions() *JobControllerCallOptions { } } +func defaultJobControllerRESTCallOptions() *JobControllerCallOptions { + return &JobControllerCallOptions{ + SubmitJob: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + SubmitJobAsOperation: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetJob: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusInternalServerError, + http.StatusServiceUnavailable) + }), + }, + ListJobs: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusInternalServerError, + http.StatusServiceUnavailable) + }), + }, + UpdateJob: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CancelJob: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusInternalServerError, + http.StatusServiceUnavailable) + }), + }, + DeleteJob: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + } +} + // internalJobControllerClient is an interface that defines the methods available from Cloud Dataproc API. type internalJobControllerClient interface { Close() error @@ -349,6 +436,89 @@ func (c *jobControllerGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type jobControllerRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing JobControllerClient + CallOptions **JobControllerCallOptions +} + +// NewJobControllerRESTClient creates a new job controller rest client. +// +// The JobController provides methods to manage jobs. +func NewJobControllerRESTClient(ctx context.Context, opts ...option.ClientOption) (*JobControllerClient, error) { + clientOpts := append(defaultJobControllerRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultJobControllerRESTCallOptions() + c := &jobControllerRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &JobControllerClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultJobControllerRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://dataproc.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://dataproc.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://dataproc.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *jobControllerRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *jobControllerRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *jobControllerRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *jobControllerGRPCClient) SubmitJob(ctx context.Context, req *dataprocpb.SubmitJobRequest, opts ...gax.CallOption) (*dataprocpb.Job, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 900000*time.Millisecond) @@ -524,9 +694,478 @@ func (c *jobControllerGRPCClient) DeleteJob(ctx context.Context, req *dataprocpb return err } +// SubmitJob submits a job to a cluster. +func (c *jobControllerRESTClient) SubmitJob(ctx context.Context, req *dataprocpb.SubmitJobRequest, opts ...gax.CallOption) (*dataprocpb.Job, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/projects/%v/regions/%v/jobs:submit", req.GetProjectId(), req.GetRegion()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "region", url.QueryEscape(req.GetRegion()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SubmitJob[0:len((*c.CallOptions).SubmitJob):len((*c.CallOptions).SubmitJob)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dataprocpb.Job{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SubmitJobAsOperation submits job to a cluster. +func (c *jobControllerRESTClient) SubmitJobAsOperation(ctx context.Context, req *dataprocpb.SubmitJobRequest, opts ...gax.CallOption) (*SubmitJobAsOperationOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/projects/%v/regions/%v/jobs:submitAsOperation", req.GetProjectId(), req.GetRegion()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "region", url.QueryEscape(req.GetRegion()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &SubmitJobAsOperationOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetJob gets the resource representation for a job in a project. +func (c *jobControllerRESTClient) GetJob(ctx context.Context, req *dataprocpb.GetJobRequest, opts ...gax.CallOption) (*dataprocpb.Job, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/projects/%v/regions/%v/jobs/%v", req.GetProjectId(), req.GetRegion(), req.GetJobId()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "region", url.QueryEscape(req.GetRegion()), "job_id", url.QueryEscape(req.GetJobId()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetJob[0:len((*c.CallOptions).GetJob):len((*c.CallOptions).GetJob)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dataprocpb.Job{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListJobs lists regions/{region}/jobs in a project. +func (c *jobControllerRESTClient) ListJobs(ctx context.Context, req *dataprocpb.ListJobsRequest, opts ...gax.CallOption) *JobIterator { + it := &JobIterator{} + req = proto.Clone(req).(*dataprocpb.ListJobsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*dataprocpb.Job, string, error) { + resp := &dataprocpb.ListJobsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/projects/%v/regions/%v/jobs", req.GetProjectId(), req.GetRegion()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetClusterName() != "" { + params.Add("clusterName", fmt.Sprintf("%v", req.GetClusterName())) + } + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetJobStateMatcher() != 0 { + params.Add("jobStateMatcher", fmt.Sprintf("%v", req.GetJobStateMatcher())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetJobs(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// UpdateJob updates a job in a project. +func (c *jobControllerRESTClient) UpdateJob(ctx context.Context, req *dataprocpb.UpdateJobRequest, opts ...gax.CallOption) (*dataprocpb.Job, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetJob() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/projects/%v/regions/%v/jobs/%v", req.GetProjectId(), req.GetRegion(), req.GetJobId()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "region", url.QueryEscape(req.GetRegion()), "job_id", url.QueryEscape(req.GetJobId()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateJob[0:len((*c.CallOptions).UpdateJob):len((*c.CallOptions).UpdateJob)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dataprocpb.Job{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CancelJob starts a job cancellation request. To access the job resource +// after cancellation, call +// regions/{region}/jobs.list (at https://cloud.google.com/dataproc/docs/reference/rest/v1/projects.regions.jobs/list) +// or +// regions/{region}/jobs.get (at https://cloud.google.com/dataproc/docs/reference/rest/v1/projects.regions.jobs/get). +func (c *jobControllerRESTClient) CancelJob(ctx context.Context, req *dataprocpb.CancelJobRequest, opts ...gax.CallOption) (*dataprocpb.Job, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/projects/%v/regions/%v/jobs/%v:cancel", req.GetProjectId(), req.GetRegion(), req.GetJobId()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "region", url.QueryEscape(req.GetRegion()), "job_id", url.QueryEscape(req.GetJobId()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CancelJob[0:len((*c.CallOptions).CancelJob):len((*c.CallOptions).CancelJob)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dataprocpb.Job{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteJob deletes the job from the project. If the job is active, the delete fails, +// and the response returns FAILED_PRECONDITION. +func (c *jobControllerRESTClient) DeleteJob(ctx context.Context, req *dataprocpb.DeleteJobRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/projects/%v/regions/%v/jobs/%v", req.GetProjectId(), req.GetRegion(), req.GetJobId()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "region", url.QueryEscape(req.GetRegion()), "job_id", url.QueryEscape(req.GetJobId()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + // SubmitJobAsOperationOperation manages a long-running operation from SubmitJobAsOperation. type SubmitJobAsOperationOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // SubmitJobAsOperationOperation returns a new SubmitJobAsOperationOperation from a given name. @@ -537,10 +1176,21 @@ func (c *jobControllerGRPCClient) SubmitJobAsOperationOperation(name string) *Su } } +// SubmitJobAsOperationOperation returns a new SubmitJobAsOperationOperation from a given name. +// The name must be that of a previously created SubmitJobAsOperationOperation, possibly from a different process. +func (c *jobControllerRESTClient) SubmitJobAsOperationOperation(name string) *SubmitJobAsOperationOperation { + override := fmt.Sprintf("/v1/%s", name) + return &SubmitJobAsOperationOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *SubmitJobAsOperationOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*dataprocpb.Job, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp dataprocpb.Job if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -558,6 +1208,7 @@ func (op *SubmitJobAsOperationOperation) Wait(ctx context.Context, opts ...gax.C // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *SubmitJobAsOperationOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*dataprocpb.Job, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp dataprocpb.Job if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/dataproc/apiv1/job_controller_client_example_test.go b/dataproc/apiv1/job_controller_client_example_test.go index da8df069b478..41de5951f25f 100644 --- a/dataproc/apiv1/job_controller_client_example_test.go +++ b/dataproc/apiv1/job_controller_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewJobControllerClient() { _ = c } +func ExampleNewJobControllerRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := dataproc.NewJobControllerRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleJobControllerClient_SubmitJob() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/dataproc/apiv1/workflow_template_client.go b/dataproc/apiv1/workflow_template_client.go index 68ca178cbbc1..a1a1a3d857d0 100644 --- a/dataproc/apiv1/workflow_template_client.go +++ b/dataproc/apiv1/workflow_template_client.go @@ -17,9 +17,12 @@ package dataproc import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,14 +30,17 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -149,6 +155,85 @@ func defaultWorkflowTemplateCallOptions() *WorkflowTemplateCallOptions { } } +func defaultWorkflowTemplateRESTCallOptions() *WorkflowTemplateCallOptions { + return &WorkflowTemplateCallOptions{ + CreateWorkflowTemplate: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetWorkflowTemplate: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusInternalServerError, + http.StatusServiceUnavailable) + }), + }, + InstantiateWorkflowTemplate: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + InstantiateInlineWorkflowTemplate: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UpdateWorkflowTemplate: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListWorkflowTemplates: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusInternalServerError, + http.StatusServiceUnavailable) + }), + }, + DeleteWorkflowTemplate: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + } +} + // internalWorkflowTemplateClient is an interface that defines the methods available from Cloud Dataproc API. type internalWorkflowTemplateClient interface { Close() error @@ -397,6 +482,90 @@ func (c *workflowTemplateGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type workflowTemplateRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing WorkflowTemplateClient + CallOptions **WorkflowTemplateCallOptions +} + +// NewWorkflowTemplateRESTClient creates a new workflow template service rest client. +// +// The API interface for managing Workflow Templates in the +// Dataproc API. +func NewWorkflowTemplateRESTClient(ctx context.Context, opts ...option.ClientOption) (*WorkflowTemplateClient, error) { + clientOpts := append(defaultWorkflowTemplateRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultWorkflowTemplateRESTCallOptions() + c := &workflowTemplateRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &WorkflowTemplateClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultWorkflowTemplateRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://dataproc.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://dataproc.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://dataproc.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *workflowTemplateRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *workflowTemplateRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *workflowTemplateRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *workflowTemplateGRPCClient) CreateWorkflowTemplate(ctx context.Context, req *dataprocpb.CreateWorkflowTemplateRequest, opts ...gax.CallOption) (*dataprocpb.WorkflowTemplate, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) @@ -574,9 +743,518 @@ func (c *workflowTemplateGRPCClient) DeleteWorkflowTemplate(ctx context.Context, return err } +// CreateWorkflowTemplate creates new workflow template. +func (c *workflowTemplateRESTClient) CreateWorkflowTemplate(ctx context.Context, req *dataprocpb.CreateWorkflowTemplateRequest, opts ...gax.CallOption) (*dataprocpb.WorkflowTemplate, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetTemplate() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/workflowTemplates", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateWorkflowTemplate[0:len((*c.CallOptions).CreateWorkflowTemplate):len((*c.CallOptions).CreateWorkflowTemplate)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dataprocpb.WorkflowTemplate{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetWorkflowTemplate retrieves the latest workflow template. +// +// Can retrieve previously instantiated template by specifying optional +// version parameter. +func (c *workflowTemplateRESTClient) GetWorkflowTemplate(ctx context.Context, req *dataprocpb.GetWorkflowTemplateRequest, opts ...gax.CallOption) (*dataprocpb.WorkflowTemplate, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetVersion() != 0 { + params.Add("version", fmt.Sprintf("%v", req.GetVersion())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetWorkflowTemplate[0:len((*c.CallOptions).GetWorkflowTemplate):len((*c.CallOptions).GetWorkflowTemplate)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dataprocpb.WorkflowTemplate{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// InstantiateWorkflowTemplate instantiates a template and begins execution. +// +// The returned Operation can be used to track execution of +// workflow by polling +// operations.get. +// The Operation will complete when entire workflow is finished. +// +// The running workflow can be aborted via +// operations.cancel. +// This will cause any inflight jobs to be cancelled and workflow-owned +// clusters to be deleted. +// +// The Operation.metadata will be +// WorkflowMetadata (at https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#workflowmetadata). +// Also see Using +// WorkflowMetadata (at https://cloud.google.com/dataproc/docs/concepts/workflows/debugging#using_workflowmetadata). +// +// On successful completion, +// Operation.response will be +// Empty. +func (c *workflowTemplateRESTClient) InstantiateWorkflowTemplate(ctx context.Context, req *dataprocpb.InstantiateWorkflowTemplateRequest, opts ...gax.CallOption) (*InstantiateWorkflowTemplateOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:instantiate", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &InstantiateWorkflowTemplateOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// InstantiateInlineWorkflowTemplate instantiates a template and begins execution. +// +// This method is equivalent to executing the sequence +// CreateWorkflowTemplate, InstantiateWorkflowTemplate, +// DeleteWorkflowTemplate. +// +// The returned Operation can be used to track execution of +// workflow by polling +// operations.get. +// The Operation will complete when entire workflow is finished. +// +// The running workflow can be aborted via +// operations.cancel. +// This will cause any inflight jobs to be cancelled and workflow-owned +// clusters to be deleted. +// +// The Operation.metadata will be +// WorkflowMetadata (at https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#workflowmetadata). +// Also see Using +// WorkflowMetadata (at https://cloud.google.com/dataproc/docs/concepts/workflows/debugging#using_workflowmetadata). +// +// On successful completion, +// Operation.response will be +// Empty. +func (c *workflowTemplateRESTClient) InstantiateInlineWorkflowTemplate(ctx context.Context, req *dataprocpb.InstantiateInlineWorkflowTemplateRequest, opts ...gax.CallOption) (*InstantiateInlineWorkflowTemplateOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetTemplate() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/workflowTemplates:instantiateInline", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &InstantiateInlineWorkflowTemplateOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateWorkflowTemplate updates (replaces) workflow template. The updated template +// must contain version that matches the current server version. +func (c *workflowTemplateRESTClient) UpdateWorkflowTemplate(ctx context.Context, req *dataprocpb.UpdateWorkflowTemplateRequest, opts ...gax.CallOption) (*dataprocpb.WorkflowTemplate, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetTemplate() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetTemplate().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "template.name", url.QueryEscape(req.GetTemplate().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateWorkflowTemplate[0:len((*c.CallOptions).UpdateWorkflowTemplate):len((*c.CallOptions).UpdateWorkflowTemplate)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dataprocpb.WorkflowTemplate{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PUT", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListWorkflowTemplates lists workflows that match the specified filter in the request. +func (c *workflowTemplateRESTClient) ListWorkflowTemplates(ctx context.Context, req *dataprocpb.ListWorkflowTemplatesRequest, opts ...gax.CallOption) *WorkflowTemplateIterator { + it := &WorkflowTemplateIterator{} + req = proto.Clone(req).(*dataprocpb.ListWorkflowTemplatesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*dataprocpb.WorkflowTemplate, string, error) { + resp := &dataprocpb.ListWorkflowTemplatesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/workflowTemplates", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetTemplates(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// DeleteWorkflowTemplate deletes a workflow template. It does not cancel in-progress workflows. +func (c *workflowTemplateRESTClient) DeleteWorkflowTemplate(ctx context.Context, req *dataprocpb.DeleteWorkflowTemplateRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetVersion() != 0 { + params.Add("version", fmt.Sprintf("%v", req.GetVersion())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + // InstantiateInlineWorkflowTemplateOperation manages a long-running operation from InstantiateInlineWorkflowTemplate. type InstantiateInlineWorkflowTemplateOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // InstantiateInlineWorkflowTemplateOperation returns a new InstantiateInlineWorkflowTemplateOperation from a given name. @@ -587,10 +1265,21 @@ func (c *workflowTemplateGRPCClient) InstantiateInlineWorkflowTemplateOperation( } } +// InstantiateInlineWorkflowTemplateOperation returns a new InstantiateInlineWorkflowTemplateOperation from a given name. +// The name must be that of a previously created InstantiateInlineWorkflowTemplateOperation, possibly from a different process. +func (c *workflowTemplateRESTClient) InstantiateInlineWorkflowTemplateOperation(name string) *InstantiateInlineWorkflowTemplateOperation { + override := fmt.Sprintf("/v1/%s", name) + return &InstantiateInlineWorkflowTemplateOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *InstantiateInlineWorkflowTemplateOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -604,6 +1293,7 @@ func (op *InstantiateInlineWorkflowTemplateOperation) Wait(ctx context.Context, // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *InstantiateInlineWorkflowTemplateOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -634,7 +1324,8 @@ func (op *InstantiateInlineWorkflowTemplateOperation) Name() string { // InstantiateWorkflowTemplateOperation manages a long-running operation from InstantiateWorkflowTemplate. type InstantiateWorkflowTemplateOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // InstantiateWorkflowTemplateOperation returns a new InstantiateWorkflowTemplateOperation from a given name. @@ -645,10 +1336,21 @@ func (c *workflowTemplateGRPCClient) InstantiateWorkflowTemplateOperation(name s } } +// InstantiateWorkflowTemplateOperation returns a new InstantiateWorkflowTemplateOperation from a given name. +// The name must be that of a previously created InstantiateWorkflowTemplateOperation, possibly from a different process. +func (c *workflowTemplateRESTClient) InstantiateWorkflowTemplateOperation(name string) *InstantiateWorkflowTemplateOperation { + override := fmt.Sprintf("/v1/%s", name) + return &InstantiateWorkflowTemplateOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *InstantiateWorkflowTemplateOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -662,6 +1364,7 @@ func (op *InstantiateWorkflowTemplateOperation) Wait(ctx context.Context, opts . // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *InstantiateWorkflowTemplateOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } diff --git a/dataproc/apiv1/workflow_template_client_example_test.go b/dataproc/apiv1/workflow_template_client_example_test.go index 2431377056bc..ca3ba446468f 100644 --- a/dataproc/apiv1/workflow_template_client_example_test.go +++ b/dataproc/apiv1/workflow_template_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewWorkflowTemplateClient() { _ = c } +func ExampleNewWorkflowTemplateRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := dataproc.NewWorkflowTemplateRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleWorkflowTemplateClient_CreateWorkflowTemplate() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/dataqna/apiv1alpha/dataqnapb/annotated_string.pb.go b/dataqna/apiv1alpha/dataqnapb/annotated_string.pb.go index 0e6b090048dc..41017bff8d49 100644 --- a/dataqna/apiv1alpha/dataqnapb/annotated_string.pb.go +++ b/dataqna/apiv1alpha/dataqnapb/annotated_string.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dataqna/v1alpha/annotated_string.proto package dataqnapb diff --git a/dataqna/apiv1alpha/dataqnapb/auto_suggestion_service.pb.go b/dataqna/apiv1alpha/dataqnapb/auto_suggestion_service.pb.go index 5f65dc1eb3f5..89a40b78dd3e 100644 --- a/dataqna/apiv1alpha/dataqnapb/auto_suggestion_service.pb.go +++ b/dataqna/apiv1alpha/dataqnapb/auto_suggestion_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dataqna/v1alpha/auto_suggestion_service.proto package dataqnapb diff --git a/dataqna/apiv1alpha/dataqnapb/question.pb.go b/dataqna/apiv1alpha/dataqnapb/question.pb.go index 7a55ccd5ae70..5ec3b21334ca 100644 --- a/dataqna/apiv1alpha/dataqnapb/question.pb.go +++ b/dataqna/apiv1alpha/dataqnapb/question.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dataqna/v1alpha/question.proto package dataqnapb @@ -698,8 +698,7 @@ type Interpretation struct { // considered a low confidence. Confidence float64 `protobuf:"fixed64,2,opt,name=confidence,proto3" json:"confidence,omitempty"` // A list of unused phrases. Clients should display a Did You Mean (DYM) - // - // dialog if this is non-empty, even if this is the only interpretation. + // dialog if this is non-empty, even if this is the only interpretation. UnusedPhrases []string `protobuf:"bytes,3,rep,name=unused_phrases,json=unusedPhrases,proto3" json:"unused_phrases,omitempty"` // Human readable representation of the query. HumanReadable *HumanReadable `protobuf:"bytes,4,opt,name=human_readable,json=humanReadable,proto3" json:"human_readable,omitempty"` diff --git a/dataqna/apiv1alpha/dataqnapb/question_service.pb.go b/dataqna/apiv1alpha/dataqnapb/question_service.pb.go index 7205ac505d41..8765d85baa8d 100644 --- a/dataqna/apiv1alpha/dataqnapb/question_service.pb.go +++ b/dataqna/apiv1alpha/dataqnapb/question_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dataqna/v1alpha/question_service.proto package dataqnapb diff --git a/dataqna/apiv1alpha/dataqnapb/user_feedback.pb.go b/dataqna/apiv1alpha/dataqnapb/user_feedback.pb.go index 06ccbb8d5ecc..98ade0f83973 100644 --- a/dataqna/apiv1alpha/dataqnapb/user_feedback.pb.go +++ b/dataqna/apiv1alpha/dataqnapb/user_feedback.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dataqna/v1alpha/user_feedback.proto package dataqnapb diff --git a/datastore/admin/apiv1/adminpb/datastore_admin.pb.go b/datastore/admin/apiv1/adminpb/datastore_admin.pb.go index 00cffa2cfb80..0bf7b63da358 100644 --- a/datastore/admin/apiv1/adminpb/datastore_admin.pb.go +++ b/datastore/admin/apiv1/adminpb/datastore_admin.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/datastore/admin/v1/datastore_admin.proto package adminpb diff --git a/datastore/admin/apiv1/adminpb/index.pb.go b/datastore/admin/apiv1/adminpb/index.pb.go index 7b8ed7fbcd8c..ce3db20f20f7 100644 --- a/datastore/admin/apiv1/adminpb/index.pb.go +++ b/datastore/admin/apiv1/adminpb/index.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/datastore/admin/v1/index.proto package adminpb diff --git a/datastore/admin/apiv1/adminpb/migration.pb.go b/datastore/admin/apiv1/adminpb/migration.pb.go index 74a6a93b3c1f..03c4ed7b01e2 100644 --- a/datastore/admin/apiv1/adminpb/migration.pb.go +++ b/datastore/admin/apiv1/adminpb/migration.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/datastore/admin/v1/migration.proto package adminpb @@ -290,7 +290,6 @@ type MigrationProgressEvent struct { // Details about this step. // // Types that are assignable to StepDetails: - // // *MigrationProgressEvent_PrepareStepDetails_ // *MigrationProgressEvent_RedirectWritesStepDetails_ StepDetails isMigrationProgressEvent_StepDetails `protobuf_oneof:"step_details"` diff --git a/datastore/admin/apiv1/datastore_admin_client.go b/datastore/admin/apiv1/datastore_admin_client.go index 765bc92268bf..a4211f34b2ab 100644 --- a/datastore/admin/apiv1/datastore_admin_client.go +++ b/datastore/admin/apiv1/datastore_admin_client.go @@ -17,9 +17,12 @@ package admin import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,14 +30,17 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -103,6 +109,41 @@ func defaultDatastoreAdminCallOptions() *DatastoreAdminCallOptions { } } +func defaultDatastoreAdminRESTCallOptions() *DatastoreAdminCallOptions { + return &DatastoreAdminCallOptions{ + ExportEntities: []gax.CallOption{}, + ImportEntities: []gax.CallOption{}, + CreateIndex: []gax.CallOption{}, + DeleteIndex: []gax.CallOption{}, + GetIndex: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + ListIndexes: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + CancelOperation: []gax.CallOption{}, + DeleteOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalDatastoreAdminClient is an interface that defines the methods available from Cloud Datastore API. type internalDatastoreAdminClient interface { Close() error @@ -467,6 +508,136 @@ func (c *datastoreAdminGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type datastoreAdminRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing DatastoreAdminClient + CallOptions **DatastoreAdminCallOptions +} + +// NewDatastoreAdminRESTClient creates a new datastore admin rest client. +// +// # Google Cloud Datastore Admin API +// +// The Datastore Admin API provides several admin services for Cloud Datastore. +// +// ConceptsProject, namespace, kind, and entity as defined in the Google Cloud Datastore +// API. +// +// Operation: An Operation represents work being performed in the background. +// +// EntityFilter: Allows specifying a subset of entities in a project. This is +// specified as a combination of kinds and namespaces (either or both of which +// may be all). +// +// ServicesExport/ImportThe Export/Import service provides the ability to copy all or a subset of +// entities to/from Google Cloud Storage. +// +// Exported data may be imported into Cloud Datastore for any Google Cloud +// Platform project. It is not restricted to the export source project. It is +// possible to export from one project and then import into another. +// +// Exported data can also be loaded into Google BigQuery for analysis. +// +// Exports and imports are performed asynchronously. An Operation resource is +// created for each export/import. The state (including any errors encountered) +// of the export/import may be queried via the Operation resource. +// +// IndexThe index service manages Cloud Datastore composite indexes. +// +// Index creation and deletion are performed asynchronously. +// An Operation resource is created for each such asynchronous operation. +// The state of the operation (including any errors encountered) +// may be queried via the Operation resource. +// +// OperationThe Operations collection provides a record of actions performed for the +// specified project (including any operations in progress). Operations are not +// created directly but through calls on other collections or resources. +// +// An operation that is not yet done may be cancelled. The request to cancel is +// asynchronous and the operation may continue to run for some time after the +// request to cancel is made. +// +// An operation that is done may be deleted so that it is no longer listed as +// part of the Operation collection. +// +// ListOperations returns all pending operations, but not completed operations. +// +// Operations are created by service DatastoreAdmin, +// but are accessed via service google.longrunning.Operations. +func NewDatastoreAdminRESTClient(ctx context.Context, opts ...option.ClientOption) (*DatastoreAdminClient, error) { + clientOpts := append(defaultDatastoreAdminRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultDatastoreAdminRESTCallOptions() + c := &datastoreAdminRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &DatastoreAdminClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultDatastoreAdminRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://datastore.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://datastore.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://datastore.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *datastoreAdminRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *datastoreAdminRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *datastoreAdminRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *datastoreAdminGRPCClient) ExportEntities(ctx context.Context, req *adminpb.ExportEntitiesRequest, opts ...gax.CallOption) (*ExportEntitiesOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) @@ -718,120 +889,826 @@ func (c *datastoreAdminGRPCClient) ListOperations(ctx context.Context, req *long return it } -// CreateIndexOperation manages a long-running operation from CreateIndex. -type CreateIndexOperation struct { - lro *longrunning.Operation -} - -// CreateIndexOperation returns a new CreateIndexOperation from a given name. -// The name must be that of a previously created CreateIndexOperation, possibly from a different process. -func (c *datastoreAdminGRPCClient) CreateIndexOperation(name string) *CreateIndexOperation { - return &CreateIndexOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} - -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *CreateIndexOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*adminpb.Index, error) { - var resp adminpb.Index - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { +// ExportEntities exports a copy of all or a subset of entities from Google Cloud Datastore +// to another storage system, such as Google Cloud Storage. Recent updates to +// entities may not be reflected in the export. The export occurs in the +// background and its progress can be monitored and managed via the +// Operation resource that is created. The output of an export may only be +// used once the associated operation is done. If an export operation is +// cancelled before completion it may leave partial data behind in Google +// Cloud Storage. +func (c *datastoreAdminRESTClient) ExportEntities(ctx context.Context, req *adminpb.ExportEntitiesRequest, opts ...gax.CallOption) (*ExportEntitiesOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { return nil, err } - return &resp, nil -} -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *CreateIndexOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*adminpb.Index, error) { - var resp adminpb.Index - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - if !op.Done() { - return nil, nil - } - return &resp, nil -} + baseUrl.Path += fmt.Sprintf("/v1/projects/%v:export", req.GetProjectId()) -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *CreateIndexOperation) Metadata() (*adminpb.IndexOperationMetadata, error) { - var meta adminpb.IndexOperationMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { - return nil, err - } - return &meta, nil -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") -// Done reports whether the long-running operation has completed. -func (op *CreateIndexOperation) Done() bool { - return op.lro.Done() -} + baseUrl.RawQuery = params.Encode() -// 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 *CreateIndexOperation) Name() string { - return op.lro.Name() -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "project_id", url.QueryEscape(req.GetProjectId()))) -// DeleteIndexOperation manages a long-running operation from DeleteIndex. -type DeleteIndexOperation struct { - lro *longrunning.Operation -} + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers -// DeleteIndexOperation returns a new DeleteIndexOperation from a given name. -// The name must be that of a previously created DeleteIndexOperation, possibly from a different process. -func (c *datastoreAdminGRPCClient) DeleteIndexOperation(name string) *DeleteIndexOperation { - return &DeleteIndexOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &ExportEntitiesOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil } -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *DeleteIndexOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*adminpb.Index, error) { - var resp adminpb.Index - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { +// ImportEntities imports entities into Google Cloud Datastore. Existing entities with the +// same key are overwritten. The import occurs in the background and its +// progress can be monitored and managed via the Operation resource that is +// created. If an ImportEntities operation is cancelled, it is possible +// that a subset of the data has already been imported to Cloud Datastore. +func (c *datastoreAdminRESTClient) ImportEntities(ctx context.Context, req *adminpb.ImportEntitiesRequest, opts ...gax.CallOption) (*ImportEntitiesOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { return nil, err } - return &resp, nil -} -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *DeleteIndexOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*adminpb.Index, error) { - var resp adminpb.Index - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - if !op.Done() { - return nil, nil - } - return &resp, nil -} + baseUrl.Path += fmt.Sprintf("/v1/projects/%v:import", req.GetProjectId()) -// Metadata returns metadata associated with the long-running operation. + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "project_id", url.QueryEscape(req.GetProjectId()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &ImportEntitiesOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// CreateIndex creates the specified index. +// A newly created index’s initial state is CREATING. On completion of the +// returned google.longrunning.Operation, the state will be READY. +// If the index already exists, the call will return an ALREADY_EXISTS +// status. +// +// During index creation, the process could result in an error, in which +// case the index will move to the ERROR state. The process can be recovered +// by fixing the data that caused the error, removing the index with +// delete, then +// re-creating the index with [create] +// [google.datastore.admin.v1.DatastoreAdmin.CreateIndex]. +// +// Indexes with a single property cannot be created. +func (c *datastoreAdminRESTClient) CreateIndex(ctx context.Context, req *adminpb.CreateIndexRequest, opts ...gax.CallOption) (*CreateIndexOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetIndex() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/projects/%v/indexes", req.GetProjectId()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "project_id", url.QueryEscape(req.GetProjectId()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateIndexOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteIndex deletes an existing index. +// An index can only be deleted if it is in a READY or ERROR state. On +// successful execution of the request, the index will be in a DELETING +// state. And on completion of the +// returned google.longrunning.Operation, the index will be removed. +// +// During index deletion, the process could result in an error, in which +// case the index will move to the ERROR state. The process can be recovered +// by fixing the data that caused the error, followed by calling +// delete again. +func (c *datastoreAdminRESTClient) DeleteIndex(ctx context.Context, req *adminpb.DeleteIndexRequest, opts ...gax.CallOption) (*DeleteIndexOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/projects/%v/indexes/%v", req.GetProjectId(), req.GetIndexId()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "index_id", url.QueryEscape(req.GetIndexId()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteIndexOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetIndex gets an index. +func (c *datastoreAdminRESTClient) GetIndex(ctx context.Context, req *adminpb.GetIndexRequest, opts ...gax.CallOption) (*adminpb.Index, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/projects/%v/indexes/%v", req.GetProjectId(), req.GetIndexId()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "index_id", url.QueryEscape(req.GetIndexId()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetIndex[0:len((*c.CallOptions).GetIndex):len((*c.CallOptions).GetIndex)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &adminpb.Index{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListIndexes lists the indexes that match the specified filters. Datastore uses an +// eventually consistent query to fetch the list of indexes and may +// occasionally return stale results. +func (c *datastoreAdminRESTClient) ListIndexes(ctx context.Context, req *adminpb.ListIndexesRequest, opts ...gax.CallOption) *IndexIterator { + it := &IndexIterator{} + req = proto.Clone(req).(*adminpb.ListIndexesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*adminpb.Index, string, error) { + resp := &adminpb.ListIndexesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/projects/%v/indexes", req.GetProjectId()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetIndexes(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *datastoreAdminRESTClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// DeleteOperation is a utility method from google.longrunning.Operations. +func (c *datastoreAdminRESTClient) DeleteOperation(ctx context.Context, req *longrunningpb.DeleteOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *datastoreAdminRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *datastoreAdminRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CreateIndexOperation manages a long-running operation from CreateIndex. +type CreateIndexOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateIndexOperation returns a new CreateIndexOperation from a given name. +// The name must be that of a previously created CreateIndexOperation, possibly from a different process. +func (c *datastoreAdminGRPCClient) CreateIndexOperation(name string) *CreateIndexOperation { + return &CreateIndexOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateIndexOperation returns a new CreateIndexOperation from a given name. +// The name must be that of a previously created CreateIndexOperation, possibly from a different process. +func (c *datastoreAdminRESTClient) CreateIndexOperation(name string) *CreateIndexOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateIndexOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CreateIndexOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*adminpb.Index, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp adminpb.Index + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *CreateIndexOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*adminpb.Index, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp adminpb.Index + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *CreateIndexOperation) Metadata() (*adminpb.IndexOperationMetadata, error) { + var meta adminpb.IndexOperationMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *CreateIndexOperation) Done() bool { + return op.lro.Done() +} + +// 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 *CreateIndexOperation) Name() string { + return op.lro.Name() +} + +// DeleteIndexOperation manages a long-running operation from DeleteIndex. +type DeleteIndexOperation struct { + lro *longrunning.Operation + pollPath string +} + +// DeleteIndexOperation returns a new DeleteIndexOperation from a given name. +// The name must be that of a previously created DeleteIndexOperation, possibly from a different process. +func (c *datastoreAdminGRPCClient) DeleteIndexOperation(name string) *DeleteIndexOperation { + return &DeleteIndexOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// DeleteIndexOperation returns a new DeleteIndexOperation from a given name. +// The name must be that of a previously created DeleteIndexOperation, possibly from a different process. +func (c *datastoreAdminRESTClient) DeleteIndexOperation(name string) *DeleteIndexOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteIndexOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *DeleteIndexOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*adminpb.Index, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp adminpb.Index + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *DeleteIndexOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*adminpb.Index, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp adminpb.Index + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. // Metadata itself does not contact the server, but Poll does. // To get the latest metadata, call this method after a successful call to Poll. // If the metadata is not available, the returned metadata and error are both nil. @@ -858,7 +1735,8 @@ func (op *DeleteIndexOperation) Name() string { // ExportEntitiesOperation manages a long-running operation from ExportEntities. type ExportEntitiesOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // ExportEntitiesOperation returns a new ExportEntitiesOperation from a given name. @@ -869,10 +1747,21 @@ func (c *datastoreAdminGRPCClient) ExportEntitiesOperation(name string) *ExportE } } +// ExportEntitiesOperation returns a new ExportEntitiesOperation from a given name. +// The name must be that of a previously created ExportEntitiesOperation, possibly from a different process. +func (c *datastoreAdminRESTClient) ExportEntitiesOperation(name string) *ExportEntitiesOperation { + override := fmt.Sprintf("/v1/%s", name) + return &ExportEntitiesOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *ExportEntitiesOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*adminpb.ExportEntitiesResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp adminpb.ExportEntitiesResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -890,6 +1779,7 @@ func (op *ExportEntitiesOperation) Wait(ctx context.Context, opts ...gax.CallOpt // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *ExportEntitiesOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*adminpb.ExportEntitiesResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp adminpb.ExportEntitiesResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -927,7 +1817,8 @@ func (op *ExportEntitiesOperation) Name() string { // ImportEntitiesOperation manages a long-running operation from ImportEntities. type ImportEntitiesOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // ImportEntitiesOperation returns a new ImportEntitiesOperation from a given name. @@ -938,10 +1829,21 @@ func (c *datastoreAdminGRPCClient) ImportEntitiesOperation(name string) *ImportE } } +// ImportEntitiesOperation returns a new ImportEntitiesOperation from a given name. +// The name must be that of a previously created ImportEntitiesOperation, possibly from a different process. +func (c *datastoreAdminRESTClient) ImportEntitiesOperation(name string) *ImportEntitiesOperation { + override := fmt.Sprintf("/v1/%s", name) + return &ImportEntitiesOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *ImportEntitiesOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -955,6 +1857,7 @@ func (op *ImportEntitiesOperation) Wait(ctx context.Context, opts ...gax.CallOpt // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *ImportEntitiesOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } diff --git a/datastore/admin/apiv1/datastore_admin_client_example_test.go b/datastore/admin/apiv1/datastore_admin_client_example_test.go index 9a12a946818f..4daa56ed44aa 100644 --- a/datastore/admin/apiv1/datastore_admin_client_example_test.go +++ b/datastore/admin/apiv1/datastore_admin_client_example_test.go @@ -42,6 +42,23 @@ func ExampleNewDatastoreAdminClient() { _ = c } +func ExampleNewDatastoreAdminRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := admin.NewDatastoreAdminRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleDatastoreAdminClient_ExportEntities() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/datastore/admin/apiv1/doc.go b/datastore/admin/apiv1/doc.go index 60e769e3b184..1bc97d1374ca 100644 --- a/datastore/admin/apiv1/doc.go +++ b/datastore/admin/apiv1/doc.go @@ -88,6 +88,8 @@ package admin // import "cloud.google.com/go/datastore/admin/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -177,3 +179,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/datastore/admin/apiv1/gapic_metadata.json b/datastore/admin/apiv1/gapic_metadata.json index 42c61aaa1aa5..dc752845f8f5 100644 --- a/datastore/admin/apiv1/gapic_metadata.json +++ b/datastore/admin/apiv1/gapic_metadata.json @@ -61,6 +61,61 @@ ] } } + }, + "rest": { + "libraryClient": "DatastoreAdminClient", + "rpcs": { + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "CreateIndex": { + "methods": [ + "CreateIndex" + ] + }, + "DeleteIndex": { + "methods": [ + "DeleteIndex" + ] + }, + "DeleteOperation": { + "methods": [ + "DeleteOperation" + ] + }, + "ExportEntities": { + "methods": [ + "ExportEntities" + ] + }, + "GetIndex": { + "methods": [ + "GetIndex" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ImportEntities": { + "methods": [ + "ImportEntities" + ] + }, + "ListIndexes": { + "methods": [ + "ListIndexes" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + } + } } } } diff --git a/datastream/apiv1/datastream_client.go b/datastream/apiv1/datastream_client.go index f13e6b7d8687..d8a67444c929 100644 --- a/datastream/apiv1/datastream_client.go +++ b/datastream/apiv1/datastream_client.go @@ -17,9 +17,12 @@ package datastream import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,15 +30,18 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -274,6 +280,177 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + ListConnectionProfiles: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetConnectionProfile: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateConnectionProfile: []gax.CallOption{}, + UpdateConnectionProfile: []gax.CallOption{}, + DeleteConnectionProfile: []gax.CallOption{}, + DiscoverConnectionProfile: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListStreams: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetStream: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateStream: []gax.CallOption{}, + UpdateStream: []gax.CallOption{}, + DeleteStream: []gax.CallOption{}, + GetStreamObject: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + LookupStreamObject: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListStreamObjects: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + StartBackfillJob: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + StopBackfillJob: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + FetchStaticIps: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreatePrivateConnection: []gax.CallOption{}, + GetPrivateConnection: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListPrivateConnections: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeletePrivateConnection: []gax.CallOption{}, + CreateRoute: []gax.CallOption{}, + GetRoute: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListRoutes: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeleteRoute: []gax.CallOption{}, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + CancelOperation: []gax.CallOption{}, + DeleteOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalClient is an interface that defines the methods available from Datastream API. type internalClient interface { Close() error @@ -688,6 +865,89 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new datastream rest client. +// +// Datastream service +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://datastream.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://datastream.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://datastream.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) ListConnectionProfiles(ctx context.Context, req *datastreampb.ListConnectionProfilesRequest, opts ...gax.CallOption) *ConnectionProfileIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1546,55 +1806,2295 @@ func (c *gRPCClient) ListOperations(ctx context.Context, req *longrunningpb.List return it } -// CreateConnectionProfileOperation manages a long-running operation from CreateConnectionProfile. -type CreateConnectionProfileOperation struct { - lro *longrunning.Operation -} +// ListConnectionProfiles use this method to list connection profiles created in a project and +// location. +func (c *restClient) ListConnectionProfiles(ctx context.Context, req *datastreampb.ListConnectionProfilesRequest, opts ...gax.CallOption) *ConnectionProfileIterator { + it := &ConnectionProfileIterator{} + req = proto.Clone(req).(*datastreampb.ListConnectionProfilesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*datastreampb.ConnectionProfile, string, error) { + resp := &datastreampb.ListConnectionProfilesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/connectionProfiles", req.GetParent()) -// CreateConnectionProfileOperation returns a new CreateConnectionProfileOperation from a given name. -// The name must be that of a previously created CreateConnectionProfileOperation, possibly from a different process. -func (c *gRPCClient) CreateConnectionProfileOperation(name string) *CreateConnectionProfileOperation { - return &CreateConnectionProfileOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetConnectionProfiles(), resp.GetNextPageToken(), nil } -} -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *CreateConnectionProfileOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*datastreampb.ConnectionProfile, error) { - var resp datastreampb.ConnectionProfile - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { - return nil, err + 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 } - return &resp, nil + + it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it } -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *CreateConnectionProfileOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*datastreampb.ConnectionProfile, error) { - var resp datastreampb.ConnectionProfile - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { +// GetConnectionProfile use this method to get details about a connection profile. +func (c *restClient) GetConnectionProfile(ctx context.Context, req *datastreampb.GetConnectionProfileRequest, opts ...gax.CallOption) (*datastreampb.ConnectionProfile, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - if !op.Done() { - return nil, nil - } - return &resp, nil -} + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *CreateConnectionProfileOperation) Metadata() (*datastreampb.OperationMetadata, error) { + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetConnectionProfile[0:len((*c.CallOptions).GetConnectionProfile):len((*c.CallOptions).GetConnectionProfile)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &datastreampb.ConnectionProfile{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateConnectionProfile use this method to create a connection profile in a project and location. +func (c *restClient) CreateConnectionProfile(ctx context.Context, req *datastreampb.CreateConnectionProfileRequest, opts ...gax.CallOption) (*CreateConnectionProfileOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetConnectionProfile() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/connectionProfiles", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("connectionProfileId", fmt.Sprintf("%v", req.GetConnectionProfileId())) + if req.GetForce() { + params.Add("force", fmt.Sprintf("%v", req.GetForce())) + } + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateConnectionProfileOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateConnectionProfile use this method to update the parameters of a connection profile. +func (c *restClient) UpdateConnectionProfile(ctx context.Context, req *datastreampb.UpdateConnectionProfileRequest, opts ...gax.CallOption) (*UpdateConnectionProfileOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetConnectionProfile() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetConnectionProfile().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetForce() { + params.Add("force", fmt.Sprintf("%v", req.GetForce())) + } + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "connection_profile.name", url.QueryEscape(req.GetConnectionProfile().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateConnectionProfileOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteConnectionProfile use this method to delete a connection profile. +func (c *restClient) DeleteConnectionProfile(ctx context.Context, req *datastreampb.DeleteConnectionProfileRequest, opts ...gax.CallOption) (*DeleteConnectionProfileOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteConnectionProfileOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DiscoverConnectionProfile use this method to discover a connection profile. +// The discover API call exposes the data objects and metadata belonging to +// the profile. Typically, a request returns children data objects of a +// parent data object that’s optionally supplied in the request. +func (c *restClient) DiscoverConnectionProfile(ctx context.Context, req *datastreampb.DiscoverConnectionProfileRequest, opts ...gax.CallOption) (*datastreampb.DiscoverConnectionProfileResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/connectionProfiles:discover", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).DiscoverConnectionProfile[0:len((*c.CallOptions).DiscoverConnectionProfile):len((*c.CallOptions).DiscoverConnectionProfile)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &datastreampb.DiscoverConnectionProfileResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListStreams use this method to list streams in a project and location. +func (c *restClient) ListStreams(ctx context.Context, req *datastreampb.ListStreamsRequest, opts ...gax.CallOption) *StreamIterator { + it := &StreamIterator{} + req = proto.Clone(req).(*datastreampb.ListStreamsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*datastreampb.Stream, string, error) { + resp := &datastreampb.ListStreamsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/streams", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetStreams(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetStream use this method to get details about a stream. +func (c *restClient) GetStream(ctx context.Context, req *datastreampb.GetStreamRequest, opts ...gax.CallOption) (*datastreampb.Stream, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetStream[0:len((*c.CallOptions).GetStream):len((*c.CallOptions).GetStream)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &datastreampb.Stream{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateStream use this method to create a stream. +func (c *restClient) CreateStream(ctx context.Context, req *datastreampb.CreateStreamRequest, opts ...gax.CallOption) (*CreateStreamOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetStream() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/streams", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetForce() { + params.Add("force", fmt.Sprintf("%v", req.GetForce())) + } + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + params.Add("streamId", fmt.Sprintf("%v", req.GetStreamId())) + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateStreamOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateStream use this method to update the configuration of a stream. +func (c *restClient) UpdateStream(ctx context.Context, req *datastreampb.UpdateStreamRequest, opts ...gax.CallOption) (*UpdateStreamOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetStream() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetStream().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetForce() { + params.Add("force", fmt.Sprintf("%v", req.GetForce())) + } + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "stream.name", url.QueryEscape(req.GetStream().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateStreamOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteStream use this method to delete a stream. +func (c *restClient) DeleteStream(ctx context.Context, req *datastreampb.DeleteStreamRequest, opts ...gax.CallOption) (*DeleteStreamOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteStreamOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetStreamObject use this method to get details about a stream object. +func (c *restClient) GetStreamObject(ctx context.Context, req *datastreampb.GetStreamObjectRequest, opts ...gax.CallOption) (*datastreampb.StreamObject, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetStreamObject[0:len((*c.CallOptions).GetStreamObject):len((*c.CallOptions).GetStreamObject)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &datastreampb.StreamObject{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// LookupStreamObject use this method to look up a stream object by its source object identifier. +func (c *restClient) LookupStreamObject(ctx context.Context, req *datastreampb.LookupStreamObjectRequest, opts ...gax.CallOption) (*datastreampb.StreamObject, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/objects:lookup", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).LookupStreamObject[0:len((*c.CallOptions).LookupStreamObject):len((*c.CallOptions).LookupStreamObject)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &datastreampb.StreamObject{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListStreamObjects use this method to list the objects of a specific stream. +func (c *restClient) ListStreamObjects(ctx context.Context, req *datastreampb.ListStreamObjectsRequest, opts ...gax.CallOption) *StreamObjectIterator { + it := &StreamObjectIterator{} + req = proto.Clone(req).(*datastreampb.ListStreamObjectsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*datastreampb.StreamObject, string, error) { + resp := &datastreampb.ListStreamObjectsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/objects", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetStreamObjects(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// StartBackfillJob use this method to start a backfill job for the specified stream object. +func (c *restClient) StartBackfillJob(ctx context.Context, req *datastreampb.StartBackfillJobRequest, opts ...gax.CallOption) (*datastreampb.StartBackfillJobResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:startBackfillJob", req.GetObject()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "object", url.QueryEscape(req.GetObject()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).StartBackfillJob[0:len((*c.CallOptions).StartBackfillJob):len((*c.CallOptions).StartBackfillJob)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &datastreampb.StartBackfillJobResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// StopBackfillJob use this method to stop a backfill job for the specified stream object. +func (c *restClient) StopBackfillJob(ctx context.Context, req *datastreampb.StopBackfillJobRequest, opts ...gax.CallOption) (*datastreampb.StopBackfillJobResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:stopBackfillJob", req.GetObject()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "object", url.QueryEscape(req.GetObject()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).StopBackfillJob[0:len((*c.CallOptions).StopBackfillJob):len((*c.CallOptions).StopBackfillJob)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &datastreampb.StopBackfillJobResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// FetchStaticIps the FetchStaticIps API call exposes the static IP addresses used by +// Datastream. +func (c *restClient) FetchStaticIps(ctx context.Context, req *datastreampb.FetchStaticIpsRequest, opts ...gax.CallOption) *StringIterator { + it := &StringIterator{} + req = proto.Clone(req).(*datastreampb.FetchStaticIpsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]string, string, error) { + resp := &datastreampb.FetchStaticIpsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:fetchStaticIps", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetStaticIps(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CreatePrivateConnection use this method to create a private connectivity configuration. +func (c *restClient) CreatePrivateConnection(ctx context.Context, req *datastreampb.CreatePrivateConnectionRequest, opts ...gax.CallOption) (*CreatePrivateConnectionOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetPrivateConnection() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/privateConnections", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("privateConnectionId", fmt.Sprintf("%v", req.GetPrivateConnectionId())) + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreatePrivateConnectionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetPrivateConnection use this method to get details about a private connectivity configuration. +func (c *restClient) GetPrivateConnection(ctx context.Context, req *datastreampb.GetPrivateConnectionRequest, opts ...gax.CallOption) (*datastreampb.PrivateConnection, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetPrivateConnection[0:len((*c.CallOptions).GetPrivateConnection):len((*c.CallOptions).GetPrivateConnection)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &datastreampb.PrivateConnection{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListPrivateConnections use this method to list private connectivity configurations in a project +// and location. +func (c *restClient) ListPrivateConnections(ctx context.Context, req *datastreampb.ListPrivateConnectionsRequest, opts ...gax.CallOption) *PrivateConnectionIterator { + it := &PrivateConnectionIterator{} + req = proto.Clone(req).(*datastreampb.ListPrivateConnectionsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*datastreampb.PrivateConnection, string, error) { + resp := &datastreampb.ListPrivateConnectionsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/privateConnections", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetPrivateConnections(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// DeletePrivateConnection use this method to delete a private connectivity configuration. +func (c *restClient) DeletePrivateConnection(ctx context.Context, req *datastreampb.DeletePrivateConnectionRequest, opts ...gax.CallOption) (*DeletePrivateConnectionOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetForce() { + params.Add("force", fmt.Sprintf("%v", req.GetForce())) + } + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeletePrivateConnectionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// CreateRoute use this method to create a route for a private connectivity configuration +// in a project and location. +func (c *restClient) CreateRoute(ctx context.Context, req *datastreampb.CreateRouteRequest, opts ...gax.CallOption) (*CreateRouteOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetRoute() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/routes", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + params.Add("routeId", fmt.Sprintf("%v", req.GetRouteId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateRouteOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetRoute use this method to get details about a route. +func (c *restClient) GetRoute(ctx context.Context, req *datastreampb.GetRouteRequest, opts ...gax.CallOption) (*datastreampb.Route, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetRoute[0:len((*c.CallOptions).GetRoute):len((*c.CallOptions).GetRoute)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &datastreampb.Route{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListRoutes use this method to list routes created for a private connectivity +// configuration in a project and location. +func (c *restClient) ListRoutes(ctx context.Context, req *datastreampb.ListRoutesRequest, opts ...gax.CallOption) *RouteIterator { + it := &RouteIterator{} + req = proto.Clone(req).(*datastreampb.ListRoutesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*datastreampb.Route, string, error) { + resp := &datastreampb.ListRoutesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/routes", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetRoutes(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// DeleteRoute use this method to delete a route. +func (c *restClient) DeleteRoute(ctx context.Context, req *datastreampb.DeleteRouteRequest, opts ...gax.CallOption) (*DeleteRouteOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteRouteOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetLocation gets information about a location. +func (c *restClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *restClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *restClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// DeleteOperation is a utility method from google.longrunning.Operations. +func (c *restClient) DeleteOperation(ctx context.Context, req *longrunningpb.DeleteOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *restClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *restClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CreateConnectionProfileOperation manages a long-running operation from CreateConnectionProfile. +type CreateConnectionProfileOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateConnectionProfileOperation returns a new CreateConnectionProfileOperation from a given name. +// The name must be that of a previously created CreateConnectionProfileOperation, possibly from a different process. +func (c *gRPCClient) CreateConnectionProfileOperation(name string) *CreateConnectionProfileOperation { + return &CreateConnectionProfileOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateConnectionProfileOperation returns a new CreateConnectionProfileOperation from a given name. +// The name must be that of a previously created CreateConnectionProfileOperation, possibly from a different process. +func (c *restClient) CreateConnectionProfileOperation(name string) *CreateConnectionProfileOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateConnectionProfileOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CreateConnectionProfileOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*datastreampb.ConnectionProfile, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp datastreampb.ConnectionProfile + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *CreateConnectionProfileOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*datastreampb.ConnectionProfile, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp datastreampb.ConnectionProfile + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *CreateConnectionProfileOperation) Metadata() (*datastreampb.OperationMetadata, error) { var meta datastreampb.OperationMetadata if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { return nil, nil @@ -1617,7 +4117,8 @@ func (op *CreateConnectionProfileOperation) Name() string { // CreatePrivateConnectionOperation manages a long-running operation from CreatePrivateConnection. type CreatePrivateConnectionOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreatePrivateConnectionOperation returns a new CreatePrivateConnectionOperation from a given name. @@ -1628,10 +4129,21 @@ func (c *gRPCClient) CreatePrivateConnectionOperation(name string) *CreatePrivat } } +// CreatePrivateConnectionOperation returns a new CreatePrivateConnectionOperation from a given name. +// The name must be that of a previously created CreatePrivateConnectionOperation, possibly from a different process. +func (c *restClient) CreatePrivateConnectionOperation(name string) *CreatePrivateConnectionOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreatePrivateConnectionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreatePrivateConnectionOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*datastreampb.PrivateConnection, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp datastreampb.PrivateConnection if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1649,6 +4161,7 @@ func (op *CreatePrivateConnectionOperation) Wait(ctx context.Context, opts ...ga // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreatePrivateConnectionOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*datastreampb.PrivateConnection, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp datastreampb.PrivateConnection if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1686,7 +4199,8 @@ func (op *CreatePrivateConnectionOperation) Name() string { // CreateRouteOperation manages a long-running operation from CreateRoute. type CreateRouteOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateRouteOperation returns a new CreateRouteOperation from a given name. @@ -1697,10 +4211,21 @@ func (c *gRPCClient) CreateRouteOperation(name string) *CreateRouteOperation { } } +// CreateRouteOperation returns a new CreateRouteOperation from a given name. +// The name must be that of a previously created CreateRouteOperation, possibly from a different process. +func (c *restClient) CreateRouteOperation(name string) *CreateRouteOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateRouteOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateRouteOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*datastreampb.Route, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp datastreampb.Route if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1718,6 +4243,7 @@ func (op *CreateRouteOperation) Wait(ctx context.Context, opts ...gax.CallOption // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateRouteOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*datastreampb.Route, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp datastreampb.Route if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1755,7 +4281,8 @@ func (op *CreateRouteOperation) Name() string { // CreateStreamOperation manages a long-running operation from CreateStream. type CreateStreamOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateStreamOperation returns a new CreateStreamOperation from a given name. @@ -1766,10 +4293,21 @@ func (c *gRPCClient) CreateStreamOperation(name string) *CreateStreamOperation { } } +// CreateStreamOperation returns a new CreateStreamOperation from a given name. +// The name must be that of a previously created CreateStreamOperation, possibly from a different process. +func (c *restClient) CreateStreamOperation(name string) *CreateStreamOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateStreamOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateStreamOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*datastreampb.Stream, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp datastreampb.Stream if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1787,6 +4325,7 @@ func (op *CreateStreamOperation) Wait(ctx context.Context, opts ...gax.CallOptio // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateStreamOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*datastreampb.Stream, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp datastreampb.Stream if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1824,7 +4363,8 @@ func (op *CreateStreamOperation) Name() string { // DeleteConnectionProfileOperation manages a long-running operation from DeleteConnectionProfile. type DeleteConnectionProfileOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteConnectionProfileOperation returns a new DeleteConnectionProfileOperation from a given name. @@ -1835,10 +4375,21 @@ func (c *gRPCClient) DeleteConnectionProfileOperation(name string) *DeleteConnec } } +// DeleteConnectionProfileOperation returns a new DeleteConnectionProfileOperation from a given name. +// The name must be that of a previously created DeleteConnectionProfileOperation, possibly from a different process. +func (c *restClient) DeleteConnectionProfileOperation(name string) *DeleteConnectionProfileOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteConnectionProfileOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteConnectionProfileOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -1852,6 +4403,7 @@ func (op *DeleteConnectionProfileOperation) Wait(ctx context.Context, opts ...ga // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteConnectionProfileOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -1882,7 +4434,8 @@ func (op *DeleteConnectionProfileOperation) Name() string { // DeletePrivateConnectionOperation manages a long-running operation from DeletePrivateConnection. type DeletePrivateConnectionOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeletePrivateConnectionOperation returns a new DeletePrivateConnectionOperation from a given name. @@ -1893,10 +4446,21 @@ func (c *gRPCClient) DeletePrivateConnectionOperation(name string) *DeletePrivat } } +// DeletePrivateConnectionOperation returns a new DeletePrivateConnectionOperation from a given name. +// The name must be that of a previously created DeletePrivateConnectionOperation, possibly from a different process. +func (c *restClient) DeletePrivateConnectionOperation(name string) *DeletePrivateConnectionOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeletePrivateConnectionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeletePrivateConnectionOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -1910,6 +4474,7 @@ func (op *DeletePrivateConnectionOperation) Wait(ctx context.Context, opts ...ga // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeletePrivateConnectionOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -1940,7 +4505,8 @@ func (op *DeletePrivateConnectionOperation) Name() string { // DeleteRouteOperation manages a long-running operation from DeleteRoute. type DeleteRouteOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteRouteOperation returns a new DeleteRouteOperation from a given name. @@ -1951,10 +4517,21 @@ func (c *gRPCClient) DeleteRouteOperation(name string) *DeleteRouteOperation { } } +// DeleteRouteOperation returns a new DeleteRouteOperation from a given name. +// The name must be that of a previously created DeleteRouteOperation, possibly from a different process. +func (c *restClient) DeleteRouteOperation(name string) *DeleteRouteOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteRouteOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteRouteOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -1968,6 +4545,7 @@ func (op *DeleteRouteOperation) Wait(ctx context.Context, opts ...gax.CallOption // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteRouteOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -1998,7 +4576,8 @@ func (op *DeleteRouteOperation) Name() string { // DeleteStreamOperation manages a long-running operation from DeleteStream. type DeleteStreamOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteStreamOperation returns a new DeleteStreamOperation from a given name. @@ -2009,10 +4588,21 @@ func (c *gRPCClient) DeleteStreamOperation(name string) *DeleteStreamOperation { } } +// DeleteStreamOperation returns a new DeleteStreamOperation from a given name. +// The name must be that of a previously created DeleteStreamOperation, possibly from a different process. +func (c *restClient) DeleteStreamOperation(name string) *DeleteStreamOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteStreamOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteStreamOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -2026,6 +4616,7 @@ func (op *DeleteStreamOperation) Wait(ctx context.Context, opts ...gax.CallOptio // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteStreamOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -2056,7 +4647,8 @@ func (op *DeleteStreamOperation) Name() string { // UpdateConnectionProfileOperation manages a long-running operation from UpdateConnectionProfile. type UpdateConnectionProfileOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateConnectionProfileOperation returns a new UpdateConnectionProfileOperation from a given name. @@ -2067,10 +4659,21 @@ func (c *gRPCClient) UpdateConnectionProfileOperation(name string) *UpdateConnec } } +// UpdateConnectionProfileOperation returns a new UpdateConnectionProfileOperation from a given name. +// The name must be that of a previously created UpdateConnectionProfileOperation, possibly from a different process. +func (c *restClient) UpdateConnectionProfileOperation(name string) *UpdateConnectionProfileOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateConnectionProfileOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateConnectionProfileOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*datastreampb.ConnectionProfile, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp datastreampb.ConnectionProfile if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2088,6 +4691,7 @@ func (op *UpdateConnectionProfileOperation) Wait(ctx context.Context, opts ...ga // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateConnectionProfileOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*datastreampb.ConnectionProfile, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp datastreampb.ConnectionProfile if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2125,7 +4729,8 @@ func (op *UpdateConnectionProfileOperation) Name() string { // UpdateStreamOperation manages a long-running operation from UpdateStream. type UpdateStreamOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateStreamOperation returns a new UpdateStreamOperation from a given name. @@ -2136,10 +4741,21 @@ func (c *gRPCClient) UpdateStreamOperation(name string) *UpdateStreamOperation { } } +// UpdateStreamOperation returns a new UpdateStreamOperation from a given name. +// The name must be that of a previously created UpdateStreamOperation, possibly from a different process. +func (c *restClient) UpdateStreamOperation(name string) *UpdateStreamOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateStreamOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateStreamOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*datastreampb.Stream, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp datastreampb.Stream if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2157,6 +4773,7 @@ func (op *UpdateStreamOperation) Wait(ctx context.Context, opts ...gax.CallOptio // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateStreamOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*datastreampb.Stream, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp datastreampb.Stream if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/datastream/apiv1/datastream_client_example_test.go b/datastream/apiv1/datastream_client_example_test.go index 6ac84ddafc22..c5a4971c8bc8 100644 --- a/datastream/apiv1/datastream_client_example_test.go +++ b/datastream/apiv1/datastream_client_example_test.go @@ -43,6 +43,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := datastream.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_ListConnectionProfiles() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/datastream/apiv1/datastreampb/datastream.pb.go b/datastream/apiv1/datastreampb/datastream.pb.go index 5c7bd9b1500c..eb44a4b453ff 100644 --- a/datastream/apiv1/datastreampb/datastream.pb.go +++ b/datastream/apiv1/datastreampb/datastream.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/datastream/v1/datastream.proto package datastreampb @@ -55,21 +55,18 @@ type DiscoverConnectionProfileRequest struct { // The connection profile on which to run discover. // // Types that are assignable to Target: - // // *DiscoverConnectionProfileRequest_ConnectionProfile // *DiscoverConnectionProfileRequest_ConnectionProfileName Target isDiscoverConnectionProfileRequest_Target `protobuf_oneof:"target"` // The depth of the retrieved hierarchy of data objects. // // Types that are assignable to Hierarchy: - // // *DiscoverConnectionProfileRequest_FullHierarchy // *DiscoverConnectionProfileRequest_HierarchyDepth Hierarchy isDiscoverConnectionProfileRequest_Hierarchy `protobuf_oneof:"hierarchy"` // The data object to populate with child data objects and metadata. // // Types that are assignable to DataObject: - // // *DiscoverConnectionProfileRequest_OracleRdbms // *DiscoverConnectionProfileRequest_MysqlRdbms // *DiscoverConnectionProfileRequest_PostgresqlRdbms @@ -262,7 +259,6 @@ type DiscoverConnectionProfileResponse struct { // The data object that has been enriched by the discover API call. // // Types that are assignable to DataObject: - // // *DiscoverConnectionProfileResponse_OracleRdbms // *DiscoverConnectionProfileResponse_MysqlRdbms // *DiscoverConnectionProfileResponse_PostgresqlRdbms diff --git a/datastream/apiv1/datastreampb/datastream_resources.pb.go b/datastream/apiv1/datastreampb/datastream_resources.pb.go index f3ac758cf754..444b8b0d5598 100644 --- a/datastream/apiv1/datastreampb/datastream_resources.pb.go +++ b/datastream/apiv1/datastreampb/datastream_resources.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/datastream/v1/datastream_resources.proto package datastreampb @@ -943,7 +943,6 @@ type ForwardSshTunnelConnectivity struct { // Port for the SSH tunnel, default value is 22. Port int32 `protobuf:"varint,3,opt,name=port,proto3" json:"port,omitempty"` // Types that are assignable to AuthenticationMethod: - // // *ForwardSshTunnelConnectivity_Password // *ForwardSshTunnelConnectivity_PrivateKey AuthenticationMethod isForwardSshTunnelConnectivity_AuthenticationMethod `protobuf_oneof:"authentication_method"` @@ -1488,7 +1487,6 @@ type ConnectionProfile struct { // Connection configuration for the ConnectionProfile. // // Types that are assignable to Profile: - // // *ConnectionProfile_OracleProfile // *ConnectionProfile_GcsProfile // *ConnectionProfile_MysqlProfile @@ -1498,7 +1496,6 @@ type ConnectionProfile struct { // Connectivity options used to establish a connection to the profile. // // Types that are assignable to Connectivity: - // // *ConnectionProfile_StaticServiceIpConnectivity // *ConnectionProfile_ForwardSshConnectivity // *ConnectionProfile_PrivateConnectivity @@ -2010,7 +2007,6 @@ type OracleSourceConfig struct { // The configuration for handle Oracle large objects. // // Types that are assignable to LargeObjectsHandling: - // // *OracleSourceConfig_DropLargeObjects_ // *OracleSourceConfig_StreamLargeObjects_ LargeObjectsHandling isOracleSourceConfig_LargeObjectsHandling `protobuf_oneof:"large_objects_handling"` @@ -2816,7 +2812,6 @@ type SourceConfig struct { // Stream configuration that is specific to the data source type. // // Types that are assignable to SourceStreamConfig: - // // *SourceConfig_OracleSourceConfig // *SourceConfig_MysqlSourceConfig // *SourceConfig_PostgresqlSourceConfig @@ -3028,7 +3023,6 @@ type GcsDestinationConfig struct { // File Format that the data should be written in. // // Types that are assignable to FileFormat: - // // *GcsDestinationConfig_AvroFileFormat // *GcsDestinationConfig_JsonFileFormat FileFormat isGcsDestinationConfig_FileFormat `protobuf_oneof:"file_format"` @@ -3134,7 +3128,6 @@ type BigQueryDestinationConfig struct { // Target dataset(s) configuration. // // Types that are assignable to DatasetConfig: - // // *BigQueryDestinationConfig_SingleTargetDataset_ // *BigQueryDestinationConfig_SourceHierarchyDatasets_ DatasetConfig isBigQueryDestinationConfig_DatasetConfig `protobuf_oneof:"dataset_config"` @@ -3236,7 +3229,6 @@ type DestinationConfig struct { // Stream configuration that is specific to the data destination type. // // Types that are assignable to DestinationStreamConfig: - // // *DestinationConfig_GcsDestinationConfig // *DestinationConfig_BigqueryDestinationConfig DestinationStreamConfig isDestinationConfig_DestinationStreamConfig `protobuf_oneof:"destination_stream_config"` @@ -3345,7 +3337,6 @@ type Stream struct { // Stream backfill strategy. // // Types that are assignable to BackfillStrategy: - // // *Stream_BackfillAll // *Stream_BackfillNone BackfillStrategy isStream_BackfillStrategy `protobuf_oneof:"backfill_strategy"` @@ -3612,7 +3603,6 @@ type SourceObjectIdentifier struct { // The identifier for an object in the data source. // // Types that are assignable to SourceIdentifier: - // // *SourceObjectIdentifier_OracleIdentifier // *SourceObjectIdentifier_MysqlIdentifier // *SourceObjectIdentifier_PostgresqlIdentifier @@ -4339,7 +4329,6 @@ type Stream_BackfillAllStrategy struct { // List of objects to exclude. // // Types that are assignable to ExcludedObjects: - // // *Stream_BackfillAllStrategy_OracleExcludedObjects // *Stream_BackfillAllStrategy_MysqlExcludedObjects // *Stream_BackfillAllStrategy_PostgresqlExcludedObjects diff --git a/datastream/apiv1/doc.go b/datastream/apiv1/doc.go index f5fb4c27faae..a308d3fc6620 100644 --- a/datastream/apiv1/doc.go +++ b/datastream/apiv1/doc.go @@ -84,6 +84,8 @@ package datastream // import "cloud.google.com/go/datastream/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -172,3 +174,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/datastream/apiv1/gapic_metadata.json b/datastream/apiv1/gapic_metadata.json index a30fef7ec5d0..3da63c82f20d 100644 --- a/datastream/apiv1/gapic_metadata.json +++ b/datastream/apiv1/gapic_metadata.json @@ -166,6 +166,166 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "CreateConnectionProfile": { + "methods": [ + "CreateConnectionProfile" + ] + }, + "CreatePrivateConnection": { + "methods": [ + "CreatePrivateConnection" + ] + }, + "CreateRoute": { + "methods": [ + "CreateRoute" + ] + }, + "CreateStream": { + "methods": [ + "CreateStream" + ] + }, + "DeleteConnectionProfile": { + "methods": [ + "DeleteConnectionProfile" + ] + }, + "DeleteOperation": { + "methods": [ + "DeleteOperation" + ] + }, + "DeletePrivateConnection": { + "methods": [ + "DeletePrivateConnection" + ] + }, + "DeleteRoute": { + "methods": [ + "DeleteRoute" + ] + }, + "DeleteStream": { + "methods": [ + "DeleteStream" + ] + }, + "DiscoverConnectionProfile": { + "methods": [ + "DiscoverConnectionProfile" + ] + }, + "FetchStaticIps": { + "methods": [ + "FetchStaticIps" + ] + }, + "GetConnectionProfile": { + "methods": [ + "GetConnectionProfile" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "GetPrivateConnection": { + "methods": [ + "GetPrivateConnection" + ] + }, + "GetRoute": { + "methods": [ + "GetRoute" + ] + }, + "GetStream": { + "methods": [ + "GetStream" + ] + }, + "GetStreamObject": { + "methods": [ + "GetStreamObject" + ] + }, + "ListConnectionProfiles": { + "methods": [ + "ListConnectionProfiles" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "ListPrivateConnections": { + "methods": [ + "ListPrivateConnections" + ] + }, + "ListRoutes": { + "methods": [ + "ListRoutes" + ] + }, + "ListStreamObjects": { + "methods": [ + "ListStreamObjects" + ] + }, + "ListStreams": { + "methods": [ + "ListStreams" + ] + }, + "LookupStreamObject": { + "methods": [ + "LookupStreamObject" + ] + }, + "StartBackfillJob": { + "methods": [ + "StartBackfillJob" + ] + }, + "StopBackfillJob": { + "methods": [ + "StopBackfillJob" + ] + }, + "UpdateConnectionProfile": { + "methods": [ + "UpdateConnectionProfile" + ] + }, + "UpdateStream": { + "methods": [ + "UpdateStream" + ] + } + } } } } diff --git a/datastream/apiv1alpha1/datastream_client.go b/datastream/apiv1alpha1/datastream_client.go index 4720278866ab..9f4584b06cc6 100644 --- a/datastream/apiv1alpha1/datastream_client.go +++ b/datastream/apiv1alpha1/datastream_client.go @@ -1405,6 +1405,7 @@ func (c *restClient) ListConnectionProfiles(ctx context.Context, req *datastream baseUrl.Path += fmt.Sprintf("/v1alpha1/%v/connectionProfiles", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1484,6 +1485,11 @@ func (c *restClient) GetConnectionProfile(ctx context.Context, req *datastreampb } baseUrl.Path += fmt.Sprintf("/v1alpha1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1545,6 +1551,7 @@ func (c *restClient) CreateConnectionProfile(ctx context.Context, req *datastrea baseUrl.Path += fmt.Sprintf("/v1alpha1/%v/connectionProfiles", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("connectionProfileId", fmt.Sprintf("%v", req.GetConnectionProfileId())) if req.GetRequestId() != "" { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) @@ -1617,6 +1624,7 @@ func (c *restClient) UpdateConnectionProfile(ctx context.Context, req *datastrea baseUrl.Path += fmt.Sprintf("/v1alpha1/%v", req.GetConnectionProfile().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetRequestId() != "" { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -1688,6 +1696,7 @@ func (c *restClient) DeleteConnectionProfile(ctx context.Context, req *datastrea baseUrl.Path += fmt.Sprintf("/v1alpha1/%v", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetRequestId() != "" { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -1760,6 +1769,11 @@ func (c *restClient) DiscoverConnectionProfile(ctx context.Context, req *datastr } baseUrl.Path += fmt.Sprintf("/v1alpha1/%v/connectionProfiles:discover", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1827,6 +1841,7 @@ func (c *restClient) ListStreams(ctx context.Context, req *datastreampb.ListStre baseUrl.Path += fmt.Sprintf("/v1alpha1/%v/streams", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1906,6 +1921,11 @@ func (c *restClient) GetStream(ctx context.Context, req *datastreampb.GetStreamR } baseUrl.Path += fmt.Sprintf("/v1alpha1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1967,6 +1987,7 @@ func (c *restClient) CreateStream(ctx context.Context, req *datastreampb.CreateS baseUrl.Path += fmt.Sprintf("/v1alpha1/%v/streams", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetForce() { params.Add("force", fmt.Sprintf("%v", req.GetForce())) } @@ -2045,6 +2066,7 @@ func (c *restClient) UpdateStream(ctx context.Context, req *datastreampb.UpdateS baseUrl.Path += fmt.Sprintf("/v1alpha1/%v", req.GetStream().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetForce() { params.Add("force", fmt.Sprintf("%v", req.GetForce())) } @@ -2122,6 +2144,7 @@ func (c *restClient) DeleteStream(ctx context.Context, req *datastreampb.DeleteS baseUrl.Path += fmt.Sprintf("/v1alpha1/%v", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetRequestId() != "" { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -2191,6 +2214,11 @@ func (c *restClient) FetchErrors(ctx context.Context, req *datastreampb.FetchErr } baseUrl.Path += fmt.Sprintf("/v1alpha1/%v:fetchErrors", req.GetStream()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "stream", url.QueryEscape(req.GetStream()))) @@ -2264,6 +2292,7 @@ func (c *restClient) FetchStaticIps(ctx context.Context, req *datastreampb.Fetch baseUrl.Path += fmt.Sprintf("/v1alpha1/%v:fetchStaticIps", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -2345,6 +2374,7 @@ func (c *restClient) CreatePrivateConnection(ctx context.Context, req *datastrea baseUrl.Path += fmt.Sprintf("/v1alpha1/%v/privateConnections", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("privateConnectionId", fmt.Sprintf("%v", req.GetPrivateConnectionId())) if req.GetRequestId() != "" { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) @@ -2409,6 +2439,11 @@ func (c *restClient) GetPrivateConnection(ctx context.Context, req *datastreampb } baseUrl.Path += fmt.Sprintf("/v1alpha1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2477,6 +2512,7 @@ func (c *restClient) ListPrivateConnections(ctx context.Context, req *datastream baseUrl.Path += fmt.Sprintf("/v1alpha1/%v/privateConnections", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -2557,6 +2593,7 @@ func (c *restClient) DeletePrivateConnection(ctx context.Context, req *datastrea baseUrl.Path += fmt.Sprintf("/v1alpha1/%v", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetForce() { params.Add("force", fmt.Sprintf("%v", req.GetForce())) } @@ -2632,6 +2669,7 @@ func (c *restClient) CreateRoute(ctx context.Context, req *datastreampb.CreateRo baseUrl.Path += fmt.Sprintf("/v1alpha1/%v/routes", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetRequestId() != "" { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -2696,6 +2734,11 @@ func (c *restClient) GetRoute(ctx context.Context, req *datastreampb.GetRouteReq } baseUrl.Path += fmt.Sprintf("/v1alpha1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2764,6 +2807,7 @@ func (c *restClient) ListRoutes(ctx context.Context, req *datastreampb.ListRoute baseUrl.Path += fmt.Sprintf("/v1alpha1/%v/routes", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -2844,6 +2888,7 @@ func (c *restClient) DeleteRoute(ctx context.Context, req *datastreampb.DeleteRo baseUrl.Path += fmt.Sprintf("/v1alpha1/%v", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetRequestId() != "" { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } diff --git a/datastream/apiv1alpha1/datastreampb/datastream.pb.go b/datastream/apiv1alpha1/datastreampb/datastream.pb.go index e6432600b7f8..fb8244d89e74 100644 --- a/datastream/apiv1alpha1/datastreampb/datastream.pb.go +++ b/datastream/apiv1alpha1/datastreampb/datastream.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/datastream/v1alpha1/datastream.proto package datastreampb @@ -55,19 +55,16 @@ type DiscoverConnectionProfileRequest struct { // The connection profile on which to run discover. // // Types that are assignable to Target: - // // *DiscoverConnectionProfileRequest_ConnectionProfile // *DiscoverConnectionProfileRequest_ConnectionProfileName Target isDiscoverConnectionProfileRequest_Target `protobuf_oneof:"target"` // Types that are assignable to Depth: - // // *DiscoverConnectionProfileRequest_Recursive // *DiscoverConnectionProfileRequest_RecursionDepth Depth isDiscoverConnectionProfileRequest_Depth `protobuf_oneof:"depth"` // The data object to enrich with child data objects and metadata. // // Types that are assignable to DataObject: - // // *DiscoverConnectionProfileRequest_OracleRdbms // *DiscoverConnectionProfileRequest_MysqlRdbms DataObject isDiscoverConnectionProfileRequest_DataObject `protobuf_oneof:"data_object"` @@ -241,7 +238,6 @@ type DiscoverConnectionProfileResponse struct { // The data object that has been enriched by the discover API call. // // Types that are assignable to DataObject: - // // *DiscoverConnectionProfileResponse_OracleRdbms // *DiscoverConnectionProfileResponse_MysqlRdbms DataObject isDiscoverConnectionProfileResponse_DataObject `protobuf_oneof:"data_object"` diff --git a/datastream/apiv1alpha1/datastreampb/datastream_resources.pb.go b/datastream/apiv1alpha1/datastreampb/datastream_resources.pb.go index 0962da32b1ab..f422cf5519b4 100644 --- a/datastream/apiv1alpha1/datastreampb/datastream_resources.pb.go +++ b/datastream/apiv1alpha1/datastreampb/datastream_resources.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/datastream/v1alpha1/datastream_resources.proto package datastreampb @@ -771,7 +771,6 @@ type ForwardSshTunnelConnectivity struct { // Port for the SSH tunnel, default value is 22. Port int32 `protobuf:"varint,3,opt,name=port,proto3" json:"port,omitempty"` // Types that are assignable to AuthenticationMethod: - // // *ForwardSshTunnelConnectivity_Password // *ForwardSshTunnelConnectivity_PrivateKey AuthenticationMethod isForwardSshTunnelConnectivity_AuthenticationMethod `protobuf_oneof:"authentication_method"` @@ -1311,7 +1310,6 @@ type ConnectionProfile struct { // Connection configuration for the ConnectionProfile. // // Types that are assignable to Profile: - // // *ConnectionProfile_OracleProfile // *ConnectionProfile_GcsProfile // *ConnectionProfile_MysqlProfile @@ -1319,7 +1317,6 @@ type ConnectionProfile struct { // Connectivity options used to establish a connection to the profile. // // Types that are assignable to Connectivity: - // // *ConnectionProfile_NoConnectivity // *ConnectionProfile_StaticServiceIpConnectivity // *ConnectionProfile_ForwardSshConnectivity @@ -2200,7 +2197,6 @@ type SourceConfig struct { // Stream configuration that is specific to the data source type. // // Types that are assignable to SourceStreamConfig: - // // *SourceConfig_OracleSourceConfig // *SourceConfig_MysqlSourceConfig SourceStreamConfig isSourceConfig_SourceStreamConfig `protobuf_oneof:"source_stream_config"` @@ -2402,7 +2398,6 @@ type GcsDestinationConfig struct { // File Format that the data should be written in. // // Types that are assignable to FileFormat: - // // *GcsDestinationConfig_AvroFileFormat // *GcsDestinationConfig_JsonFileFormat FileFormat isGcsDestinationConfig_FileFormat `protobuf_oneof:"file_format"` @@ -2519,7 +2514,6 @@ type DestinationConfig struct { // Stream configuration that is specific to the data destination type. // // Types that are assignable to DestinationStreamConfig: - // // *DestinationConfig_GcsDestinationConfig DestinationStreamConfig isDestinationConfig_DestinationStreamConfig `protobuf_oneof:"destination_stream_config"` } @@ -2611,7 +2605,6 @@ type Stream struct { // Stream backfill strategy. // // Types that are assignable to BackfillStrategy: - // // *Stream_BackfillAll // *Stream_BackfillNone BackfillStrategy isStream_BackfillStrategy `protobuf_oneof:"backfill_strategy"` @@ -3051,7 +3044,6 @@ type Stream_BackfillAllStrategy struct { // List of objects to exclude. // // Types that are assignable to ExcludedObjects: - // // *Stream_BackfillAllStrategy_OracleExcludedObjects // *Stream_BackfillAllStrategy_MysqlExcludedObjects ExcludedObjects isStream_BackfillAllStrategy_ExcludedObjects `protobuf_oneof:"excluded_objects"` diff --git a/debugger/apiv2/controller2_client.go b/debugger/apiv2/controller2_client.go index fffd91125d4c..90a49672743e 100644 --- a/debugger/apiv2/controller2_client.go +++ b/debugger/apiv2/controller2_client.go @@ -17,20 +17,26 @@ package debugger import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" debuggerpb "cloud.google.com/go/debugger/apiv2/debuggerpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" ) var newController2ClientHook clientHook @@ -84,6 +90,34 @@ func defaultController2CallOptions() *Controller2CallOptions { } } +func defaultController2RESTCallOptions() *Controller2CallOptions { + return &Controller2CallOptions{ + RegisterDebuggee: []gax.CallOption{}, + ListActiveBreakpoints: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + UpdateActiveBreakpoint: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + } +} + // internalController2Client is an interface that defines the methods available from Stackdriver Debugger API. type internalController2Client interface { Close() error @@ -291,6 +325,93 @@ func (c *controller2GRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type controller2RESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Controller2Client + CallOptions **Controller2CallOptions +} + +// NewController2RESTClient creates a new controller2 rest client. +// +// The Controller service provides the API for orchestrating a collection of +// debugger agents to perform debugging tasks. These agents are each attached +// to a process of an application which may include one or more replicas. +// +// The debugger agents register with the Controller to identify the application +// being debugged, the Debuggee. All agents that register with the same data, +// represent the same Debuggee, and are assigned the same debuggee_id. +// +// The debugger agents call the Controller to retrieve the list of active +// Breakpoints. Agents with the same debuggee_id get the same breakpoints +// list. An agent that can fulfill the breakpoint request updates the +// Controller with the breakpoint result. The controller selects the first +// result received and discards the rest of the results. +// Agents that poll again for active breakpoints will no longer have +// the completed breakpoint in the list and should remove that breakpoint from +// their attached process. +// +// The Controller service does not provide a way to retrieve the results of +// a completed breakpoint. This functionality is available using the Debugger +// service. +func NewController2RESTClient(ctx context.Context, opts ...option.ClientOption) (*Controller2Client, error) { + clientOpts := append(defaultController2RESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultController2RESTCallOptions() + c := &controller2RESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &Controller2Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultController2RESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://clouddebugger.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://clouddebugger.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://clouddebugger.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *controller2RESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *controller2RESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *controller2RESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *controller2GRPCClient) RegisterDebuggee(ctx context.Context, req *debuggerpb.RegisterDebuggeeRequest, opts ...gax.CallOption) (*debuggerpb.RegisterDebuggeeResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) @@ -354,3 +475,221 @@ func (c *controller2GRPCClient) UpdateActiveBreakpoint(ctx context.Context, req } return resp, nil } + +// RegisterDebuggee registers the debuggee with the controller service. +// +// All agents attached to the same application must call this method with +// exactly the same request content to get back the same stable debuggee_id. +// Agents should call this method again whenever google.rpc.Code.NOT_FOUND +// is returned from any controller method. +// +// This protocol allows the controller service to disable debuggees, recover +// from data loss, or change the debuggee_id format. Agents must handle +// debuggee_id value changing upon re-registration. +func (c *controller2RESTClient) RegisterDebuggee(ctx context.Context, req *debuggerpb.RegisterDebuggeeRequest, opts ...gax.CallOption) (*debuggerpb.RegisterDebuggeeResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/controller/debuggees/register") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).RegisterDebuggee[0:len((*c.CallOptions).RegisterDebuggee):len((*c.CallOptions).RegisterDebuggee)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &debuggerpb.RegisterDebuggeeResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListActiveBreakpoints returns the list of all active breakpoints for the debuggee. +// +// The breakpoint specification (location, condition, and expressions +// fields) is semantically immutable, although the field values may +// change. For example, an agent may update the location line number +// to reflect the actual line where the breakpoint was set, but this +// doesn’t change the breakpoint semantics. +// +// This means that an agent does not need to check if a breakpoint has changed +// when it encounters the same breakpoint on a successive call. +// Moreover, an agent should remember the breakpoints that are completed +// until the controller removes them from the active list to avoid +// setting those breakpoints again. +func (c *controller2RESTClient) ListActiveBreakpoints(ctx context.Context, req *debuggerpb.ListActiveBreakpointsRequest, opts ...gax.CallOption) (*debuggerpb.ListActiveBreakpointsResponse, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/controller/debuggees/%v/breakpoints", req.GetDebuggeeId()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetSuccessOnTimeout() { + params.Add("successOnTimeout", fmt.Sprintf("%v", req.GetSuccessOnTimeout())) + } + if req.GetWaitToken() != "" { + params.Add("waitToken", fmt.Sprintf("%v", req.GetWaitToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "debuggee_id", url.QueryEscape(req.GetDebuggeeId()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).ListActiveBreakpoints[0:len((*c.CallOptions).ListActiveBreakpoints):len((*c.CallOptions).ListActiveBreakpoints)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &debuggerpb.ListActiveBreakpointsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateActiveBreakpoint updates the breakpoint state or mutable fields. +// The entire Breakpoint message must be sent back to the controller service. +// +// Updates to active breakpoint fields are only allowed if the new value +// does not change the breakpoint specification. Updates to the location, +// condition and expressions fields should not alter the breakpoint +// semantics. These may only make changes such as canonicalizing a value +// or snapping the location to the correct line of code. +func (c *controller2RESTClient) UpdateActiveBreakpoint(ctx context.Context, req *debuggerpb.UpdateActiveBreakpointRequest, opts ...gax.CallOption) (*debuggerpb.UpdateActiveBreakpointResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/controller/debuggees/%v/breakpoints/%v", req.GetDebuggeeId(), req.GetBreakpoint().GetId()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "debuggee_id", url.QueryEscape(req.GetDebuggeeId()), "breakpoint.id", url.QueryEscape(req.GetBreakpoint().GetId()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateActiveBreakpoint[0:len((*c.CallOptions).UpdateActiveBreakpoint):len((*c.CallOptions).UpdateActiveBreakpoint)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &debuggerpb.UpdateActiveBreakpointResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PUT", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} diff --git a/debugger/apiv2/controller2_client_example_test.go b/debugger/apiv2/controller2_client_example_test.go index 8d21361d821c..7e102bc0f39e 100644 --- a/debugger/apiv2/controller2_client_example_test.go +++ b/debugger/apiv2/controller2_client_example_test.go @@ -40,6 +40,23 @@ func ExampleNewController2Client() { _ = c } +func ExampleNewController2RESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := debugger.NewController2RESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleController2Client_RegisterDebuggee() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/debugger/apiv2/debugger2_client.go b/debugger/apiv2/debugger2_client.go index ded2e59f1720..87359e6f7775 100644 --- a/debugger/apiv2/debugger2_client.go +++ b/debugger/apiv2/debugger2_client.go @@ -17,20 +17,26 @@ package debugger import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" debuggerpb "cloud.google.com/go/debugger/apiv2/debuggerpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" ) var newDebugger2ClientHook clientHook @@ -110,6 +116,56 @@ func defaultDebugger2CallOptions() *Debugger2CallOptions { } } +func defaultDebugger2RESTCallOptions() *Debugger2CallOptions { + return &Debugger2CallOptions{ + SetBreakpoint: []gax.CallOption{}, + GetBreakpoint: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + DeleteBreakpoint: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + ListBreakpoints: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + ListDebuggees: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + } +} + // internalDebugger2Client is an interface that defines the methods available from Stackdriver Debugger API. type internalDebugger2Client interface { Close() error @@ -285,6 +341,85 @@ func (c *debugger2GRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type debugger2RESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Debugger2Client + CallOptions **Debugger2CallOptions +} + +// NewDebugger2RESTClient creates a new debugger2 rest client. +// +// The Debugger service provides the API that allows users to collect run-time +// information from a running application, without stopping or slowing it down +// and without modifying its state. An application may include one or +// more replicated processes performing the same work. +// +// A debugged application is represented using the Debuggee concept. The +// Debugger service provides a way to query for available debuggees, but does +// not provide a way to create one. A debuggee is created using the Controller +// service, usually by running a debugger agent with the application. +// +// The Debugger service enables the client to set one or more Breakpoints on a +// Debuggee and collect the results of the set Breakpoints. +func NewDebugger2RESTClient(ctx context.Context, opts ...option.ClientOption) (*Debugger2Client, error) { + clientOpts := append(defaultDebugger2RESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultDebugger2RESTCallOptions() + c := &debugger2RESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &Debugger2Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultDebugger2RESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://clouddebugger.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://clouddebugger.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://clouddebugger.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *debugger2RESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *debugger2RESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *debugger2RESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *debugger2GRPCClient) SetBreakpoint(ctx context.Context, req *debuggerpb.SetBreakpointRequest, opts ...gax.CallOption) (*debuggerpb.SetBreakpointResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) @@ -388,3 +523,304 @@ func (c *debugger2GRPCClient) ListDebuggees(ctx context.Context, req *debuggerpb } return resp, nil } + +// SetBreakpoint sets the breakpoint to the debuggee. +func (c *debugger2RESTClient) SetBreakpoint(ctx context.Context, req *debuggerpb.SetBreakpointRequest, opts ...gax.CallOption) (*debuggerpb.SetBreakpointResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetBreakpoint() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/debugger/debuggees/%v/breakpoints/set", req.GetDebuggeeId()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("clientVersion", fmt.Sprintf("%v", req.GetClientVersion())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "debuggee_id", url.QueryEscape(req.GetDebuggeeId()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetBreakpoint[0:len((*c.CallOptions).SetBreakpoint):len((*c.CallOptions).SetBreakpoint)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &debuggerpb.SetBreakpointResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetBreakpoint gets breakpoint information. +func (c *debugger2RESTClient) GetBreakpoint(ctx context.Context, req *debuggerpb.GetBreakpointRequest, opts ...gax.CallOption) (*debuggerpb.GetBreakpointResponse, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/debugger/debuggees/%v/breakpoints/%v", req.GetDebuggeeId(), req.GetBreakpointId()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("clientVersion", fmt.Sprintf("%v", req.GetClientVersion())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "debuggee_id", url.QueryEscape(req.GetDebuggeeId()), "breakpoint_id", url.QueryEscape(req.GetBreakpointId()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetBreakpoint[0:len((*c.CallOptions).GetBreakpoint):len((*c.CallOptions).GetBreakpoint)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &debuggerpb.GetBreakpointResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteBreakpoint deletes the breakpoint from the debuggee. +func (c *debugger2RESTClient) DeleteBreakpoint(ctx context.Context, req *debuggerpb.DeleteBreakpointRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2/debugger/debuggees/%v/breakpoints/%v", req.GetDebuggeeId(), req.GetBreakpointId()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("clientVersion", fmt.Sprintf("%v", req.GetClientVersion())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "debuggee_id", url.QueryEscape(req.GetDebuggeeId()), "breakpoint_id", url.QueryEscape(req.GetBreakpointId()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// ListBreakpoints lists all breakpoints for the debuggee. +func (c *debugger2RESTClient) ListBreakpoints(ctx context.Context, req *debuggerpb.ListBreakpointsRequest, opts ...gax.CallOption) (*debuggerpb.ListBreakpointsResponse, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/debugger/debuggees/%v/breakpoints", req.GetDebuggeeId()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetAction().GetValue() != 0 { + params.Add("action.value", fmt.Sprintf("%v", req.GetAction().GetValue())) + } + params.Add("clientVersion", fmt.Sprintf("%v", req.GetClientVersion())) + if req.GetIncludeAllUsers() { + params.Add("includeAllUsers", fmt.Sprintf("%v", req.GetIncludeAllUsers())) + } + if req.GetIncludeInactive() { + params.Add("includeInactive", fmt.Sprintf("%v", req.GetIncludeInactive())) + } + if req.GetStripResults() { + params.Add("stripResults", fmt.Sprintf("%v", req.GetStripResults())) + } + if req.GetWaitToken() != "" { + params.Add("waitToken", fmt.Sprintf("%v", req.GetWaitToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "debuggee_id", url.QueryEscape(req.GetDebuggeeId()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).ListBreakpoints[0:len((*c.CallOptions).ListBreakpoints):len((*c.CallOptions).ListBreakpoints)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &debuggerpb.ListBreakpointsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListDebuggees lists all the debuggees that the user has access to. +func (c *debugger2RESTClient) ListDebuggees(ctx context.Context, req *debuggerpb.ListDebuggeesRequest, opts ...gax.CallOption) (*debuggerpb.ListDebuggeesResponse, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/debugger/debuggees") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("clientVersion", fmt.Sprintf("%v", req.GetClientVersion())) + if req.GetIncludeInactive() { + params.Add("includeInactive", fmt.Sprintf("%v", req.GetIncludeInactive())) + } + params.Add("project", fmt.Sprintf("%v", req.GetProject())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).ListDebuggees[0:len((*c.CallOptions).ListDebuggees):len((*c.CallOptions).ListDebuggees)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &debuggerpb.ListDebuggeesResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} diff --git a/debugger/apiv2/debugger2_client_example_test.go b/debugger/apiv2/debugger2_client_example_test.go index 03a667224350..08862c635d28 100644 --- a/debugger/apiv2/debugger2_client_example_test.go +++ b/debugger/apiv2/debugger2_client_example_test.go @@ -40,6 +40,23 @@ func ExampleNewDebugger2Client() { _ = c } +func ExampleNewDebugger2RESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := debugger.NewDebugger2RESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleDebugger2Client_SetBreakpoint() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/debugger/apiv2/debuggerpb/controller.pb.go b/debugger/apiv2/debuggerpb/controller.pb.go index 6d74a0a3f4f0..562a907bf08c 100644 --- a/debugger/apiv2/debuggerpb/controller.pb.go +++ b/debugger/apiv2/debuggerpb/controller.pb.go @@ -15,8 +15,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/devtools/clouddebugger/v2/controller.proto package debuggerpb diff --git a/debugger/apiv2/debuggerpb/data.pb.go b/debugger/apiv2/debuggerpb/data.pb.go index bc37e6d203fa..de5dd6392648 100644 --- a/debugger/apiv2/debuggerpb/data.pb.go +++ b/debugger/apiv2/debuggerpb/data.pb.go @@ -15,8 +15,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/devtools/clouddebugger/v2/data.proto package debuggerpb @@ -226,9 +226,9 @@ type FormatMessage struct { // // Examples: // - // - `Failed to load '$0' which helps debug $1 the first time it + // * `Failed to load '$0' which helps debug $1 the first time it // is loaded. Again, $0 is very important.` - // - `Please pay $$10 to use $0 instead of $1.` + // * `Please pay $$10 to use $0 instead of $1.` Format string `protobuf:"bytes,1,opt,name=format,proto3" json:"format,omitempty"` // Optional parameters to be embedded into the message. Parameters []string `protobuf:"bytes,2,rep,name=parameters,proto3" json:"parameters,omitempty"` diff --git a/debugger/apiv2/debuggerpb/debugger.pb.go b/debugger/apiv2/debuggerpb/debugger.pb.go index 36f62edbf575..52c278f1fe31 100644 --- a/debugger/apiv2/debuggerpb/debugger.pb.go +++ b/debugger/apiv2/debuggerpb/debugger.pb.go @@ -15,8 +15,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/devtools/clouddebugger/v2/debugger.proto package debuggerpb diff --git a/debugger/apiv2/doc.go b/debugger/apiv2/doc.go index 5f5061d2d53a..8fc38d0a967c 100644 --- a/debugger/apiv2/doc.go +++ b/debugger/apiv2/doc.go @@ -81,6 +81,8 @@ package debugger // import "cloud.google.com/go/debugger/apiv2" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -170,3 +172,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/debugger/apiv2/gapic_metadata.json b/debugger/apiv2/gapic_metadata.json index e0790b9e7f7a..1289468617f5 100644 --- a/debugger/apiv2/gapic_metadata.json +++ b/debugger/apiv2/gapic_metadata.json @@ -26,6 +26,26 @@ ] } } + }, + "rest": { + "libraryClient": "Controller2Client", + "rpcs": { + "ListActiveBreakpoints": { + "methods": [ + "ListActiveBreakpoints" + ] + }, + "RegisterDebuggee": { + "methods": [ + "RegisterDebuggee" + ] + }, + "UpdateActiveBreakpoint": { + "methods": [ + "UpdateActiveBreakpoint" + ] + } + } } } }, @@ -60,6 +80,36 @@ ] } } + }, + "rest": { + "libraryClient": "Debugger2Client", + "rpcs": { + "DeleteBreakpoint": { + "methods": [ + "DeleteBreakpoint" + ] + }, + "GetBreakpoint": { + "methods": [ + "GetBreakpoint" + ] + }, + "ListBreakpoints": { + "methods": [ + "ListBreakpoints" + ] + }, + "ListDebuggees": { + "methods": [ + "ListDebuggees" + ] + }, + "SetBreakpoint": { + "methods": [ + "SetBreakpoint" + ] + } + } } } } diff --git a/deploy/apiv1/cloud_deploy_client.go b/deploy/apiv1/cloud_deploy_client.go index 0de4288f0a5e..804a3d618bab 100644 --- a/deploy/apiv1/cloud_deploy_client.go +++ b/deploy/apiv1/cloud_deploy_client.go @@ -17,9 +17,12 @@ package deploy import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,16 +30,19 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" iampb "google.golang.org/genproto/googleapis/iam/v1" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -235,6 +241,141 @@ func defaultCloudDeployCallOptions() *CloudDeployCallOptions { } } +func defaultCloudDeployRESTCallOptions() *CloudDeployCallOptions { + return &CloudDeployCallOptions{ + ListDeliveryPipelines: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetDeliveryPipeline: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateDeliveryPipeline: []gax.CallOption{}, + UpdateDeliveryPipeline: []gax.CallOption{}, + DeleteDeliveryPipeline: []gax.CallOption{}, + ListTargets: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetTarget: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateTarget: []gax.CallOption{}, + UpdateTarget: []gax.CallOption{}, + DeleteTarget: []gax.CallOption{}, + ListReleases: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetRelease: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateRelease: []gax.CallOption{}, + AbandonRelease: []gax.CallOption{}, + ApproveRollout: []gax.CallOption{}, + ListRollouts: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetRollout: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateRollout: []gax.CallOption{}, + RetryJob: []gax.CallOption{}, + ListJobRuns: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetJobRun: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetConfig: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + GetIamPolicy: []gax.CallOption{}, + SetIamPolicy: []gax.CallOption{}, + TestIamPermissions: []gax.CallOption{}, + CancelOperation: []gax.CallOption{}, + DeleteOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalCloudDeployClient is an interface that defines the methods available from Google Cloud Deploy API. type internalCloudDeployClient interface { Close() error @@ -643,6 +784,90 @@ func (c *cloudDeployGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type cloudDeployRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing CloudDeployClient + CallOptions **CloudDeployCallOptions +} + +// NewCloudDeployRESTClient creates a new cloud deploy rest client. +// +// CloudDeploy service creates and manages Continuous Delivery operations +// on Google Cloud Platform via Skaffold (https://skaffold.dev (at https://skaffold.dev)). +func NewCloudDeployRESTClient(ctx context.Context, opts ...option.ClientOption) (*CloudDeployClient, error) { + clientOpts := append(defaultCloudDeployRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultCloudDeployRESTCallOptions() + c := &cloudDeployRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &CloudDeployClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultCloudDeployRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://clouddeploy.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://clouddeploy.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://clouddeploy.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *cloudDeployRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *cloudDeployRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *cloudDeployRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *cloudDeployGRPCClient) ListDeliveryPipelines(ctx context.Context, req *deploypb.ListDeliveryPipelinesRequest, opts ...gax.CallOption) *DeliveryPipelineIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1459,92 +1684,2336 @@ func (c *cloudDeployGRPCClient) ListOperations(ctx context.Context, req *longrun return it } -// CreateDeliveryPipelineOperation manages a long-running operation from CreateDeliveryPipeline. -type CreateDeliveryPipelineOperation struct { - lro *longrunning.Operation -} +// ListDeliveryPipelines lists DeliveryPipelines in a given project and location. +func (c *cloudDeployRESTClient) ListDeliveryPipelines(ctx context.Context, req *deploypb.ListDeliveryPipelinesRequest, opts ...gax.CallOption) *DeliveryPipelineIterator { + it := &DeliveryPipelineIterator{} + req = proto.Clone(req).(*deploypb.ListDeliveryPipelinesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*deploypb.DeliveryPipeline, string, error) { + resp := &deploypb.ListDeliveryPipelinesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/deliveryPipelines", req.GetParent()) -// CreateDeliveryPipelineOperation returns a new CreateDeliveryPipelineOperation from a given name. -// The name must be that of a previously created CreateDeliveryPipelineOperation, possibly from a different process. -func (c *cloudDeployGRPCClient) CreateDeliveryPipelineOperation(name string) *CreateDeliveryPipelineOperation { - return &CreateDeliveryPipelineOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *CreateDeliveryPipelineOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*deploypb.DeliveryPipeline, error) { - var resp deploypb.DeliveryPipeline - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { - return nil, err + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetDeliveryPipelines(), resp.GetNextPageToken(), nil } - return &resp, nil -} -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *CreateDeliveryPipelineOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*deploypb.DeliveryPipeline, error) { - var resp deploypb.DeliveryPipeline - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { - return nil, err - } - if !op.Done() { - return nil, 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 } - return &resp, nil + + it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it } -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *CreateDeliveryPipelineOperation) Metadata() (*deploypb.OperationMetadata, error) { - var meta deploypb.OperationMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { +// GetDeliveryPipeline gets details of a single DeliveryPipeline. +func (c *cloudDeployRESTClient) GetDeliveryPipeline(ctx context.Context, req *deploypb.GetDeliveryPipelineRequest, opts ...gax.CallOption) (*deploypb.DeliveryPipeline, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - return &meta, nil -} + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) -// Done reports whether the long-running operation has completed. -func (op *CreateDeliveryPipelineOperation) Done() bool { - return op.lro.Done() -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") -// 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 *CreateDeliveryPipelineOperation) Name() string { - return op.lro.Name() -} + baseUrl.RawQuery = params.Encode() -// CreateReleaseOperation manages a long-running operation from CreateRelease. -type CreateReleaseOperation struct { - lro *longrunning.Operation -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) -// CreateReleaseOperation returns a new CreateReleaseOperation from a given name. -// The name must be that of a previously created CreateReleaseOperation, possibly from a different process. -func (c *cloudDeployGRPCClient) CreateReleaseOperation(name string) *CreateReleaseOperation { - return &CreateReleaseOperation{ + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetDeliveryPipeline[0:len((*c.CallOptions).GetDeliveryPipeline):len((*c.CallOptions).GetDeliveryPipeline)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &deploypb.DeliveryPipeline{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateDeliveryPipeline creates a new DeliveryPipeline in a given project and location. +func (c *cloudDeployRESTClient) CreateDeliveryPipeline(ctx context.Context, req *deploypb.CreateDeliveryPipelineRequest, opts ...gax.CallOption) (*CreateDeliveryPipelineOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetDeliveryPipeline() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/deliveryPipelines", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("deliveryPipelineId", fmt.Sprintf("%v", req.GetDeliveryPipelineId())) + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateDeliveryPipelineOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateDeliveryPipeline updates the parameters of a single DeliveryPipeline. +func (c *cloudDeployRESTClient) UpdateDeliveryPipeline(ctx context.Context, req *deploypb.UpdateDeliveryPipelineRequest, opts ...gax.CallOption) (*UpdateDeliveryPipelineOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetDeliveryPipeline() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetDeliveryPipeline().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetAllowMissing() { + params.Add("allowMissing", fmt.Sprintf("%v", req.GetAllowMissing())) + } + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "delivery_pipeline.name", url.QueryEscape(req.GetDeliveryPipeline().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateDeliveryPipelineOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteDeliveryPipeline deletes a single DeliveryPipeline. +func (c *cloudDeployRESTClient) DeleteDeliveryPipeline(ctx context.Context, req *deploypb.DeleteDeliveryPipelineRequest, opts ...gax.CallOption) (*DeleteDeliveryPipelineOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetAllowMissing() { + params.Add("allowMissing", fmt.Sprintf("%v", req.GetAllowMissing())) + } + if req.GetEtag() != "" { + params.Add("etag", fmt.Sprintf("%v", req.GetEtag())) + } + if req.GetForce() { + params.Add("force", fmt.Sprintf("%v", req.GetForce())) + } + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteDeliveryPipelineOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListTargets lists Targets in a given project and location. +func (c *cloudDeployRESTClient) ListTargets(ctx context.Context, req *deploypb.ListTargetsRequest, opts ...gax.CallOption) *TargetIterator { + it := &TargetIterator{} + req = proto.Clone(req).(*deploypb.ListTargetsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*deploypb.Target, string, error) { + resp := &deploypb.ListTargetsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/targets", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetTargets(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetTarget gets details of a single Target. +func (c *cloudDeployRESTClient) GetTarget(ctx context.Context, req *deploypb.GetTargetRequest, opts ...gax.CallOption) (*deploypb.Target, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetTarget[0:len((*c.CallOptions).GetTarget):len((*c.CallOptions).GetTarget)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &deploypb.Target{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateTarget creates a new Target in a given project and location. +func (c *cloudDeployRESTClient) CreateTarget(ctx context.Context, req *deploypb.CreateTargetRequest, opts ...gax.CallOption) (*CreateTargetOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetTarget() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/targets", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + params.Add("targetId", fmt.Sprintf("%v", req.GetTargetId())) + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateTargetOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateTarget updates the parameters of a single Target. +func (c *cloudDeployRESTClient) UpdateTarget(ctx context.Context, req *deploypb.UpdateTargetRequest, opts ...gax.CallOption) (*UpdateTargetOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetTarget() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetTarget().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetAllowMissing() { + params.Add("allowMissing", fmt.Sprintf("%v", req.GetAllowMissing())) + } + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "target.name", url.QueryEscape(req.GetTarget().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateTargetOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteTarget deletes a single Target. +func (c *cloudDeployRESTClient) DeleteTarget(ctx context.Context, req *deploypb.DeleteTargetRequest, opts ...gax.CallOption) (*DeleteTargetOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetAllowMissing() { + params.Add("allowMissing", fmt.Sprintf("%v", req.GetAllowMissing())) + } + if req.GetEtag() != "" { + params.Add("etag", fmt.Sprintf("%v", req.GetEtag())) + } + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteTargetOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListReleases lists Releases in a given project and location. +func (c *cloudDeployRESTClient) ListReleases(ctx context.Context, req *deploypb.ListReleasesRequest, opts ...gax.CallOption) *ReleaseIterator { + it := &ReleaseIterator{} + req = proto.Clone(req).(*deploypb.ListReleasesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*deploypb.Release, string, error) { + resp := &deploypb.ListReleasesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/releases", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetReleases(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetRelease gets details of a single Release. +func (c *cloudDeployRESTClient) GetRelease(ctx context.Context, req *deploypb.GetReleaseRequest, opts ...gax.CallOption) (*deploypb.Release, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetRelease[0:len((*c.CallOptions).GetRelease):len((*c.CallOptions).GetRelease)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &deploypb.Release{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateRelease creates a new Release in a given project and location. +func (c *cloudDeployRESTClient) CreateRelease(ctx context.Context, req *deploypb.CreateReleaseRequest, opts ...gax.CallOption) (*CreateReleaseOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetRelease() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/releases", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("releaseId", fmt.Sprintf("%v", req.GetReleaseId())) + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateReleaseOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// AbandonRelease abandons a Release in the Delivery Pipeline. +func (c *cloudDeployRESTClient) AbandonRelease(ctx context.Context, req *deploypb.AbandonReleaseRequest, opts ...gax.CallOption) (*deploypb.AbandonReleaseResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:abandon", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).AbandonRelease[0:len((*c.CallOptions).AbandonRelease):len((*c.CallOptions).AbandonRelease)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &deploypb.AbandonReleaseResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ApproveRollout approves a Rollout. +func (c *cloudDeployRESTClient) ApproveRollout(ctx context.Context, req *deploypb.ApproveRolloutRequest, opts ...gax.CallOption) (*deploypb.ApproveRolloutResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:approve", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).ApproveRollout[0:len((*c.CallOptions).ApproveRollout):len((*c.CallOptions).ApproveRollout)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &deploypb.ApproveRolloutResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListRollouts lists Rollouts in a given project and location. +func (c *cloudDeployRESTClient) ListRollouts(ctx context.Context, req *deploypb.ListRolloutsRequest, opts ...gax.CallOption) *RolloutIterator { + it := &RolloutIterator{} + req = proto.Clone(req).(*deploypb.ListRolloutsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*deploypb.Rollout, string, error) { + resp := &deploypb.ListRolloutsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/rollouts", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetRollouts(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetRollout gets details of a single Rollout. +func (c *cloudDeployRESTClient) GetRollout(ctx context.Context, req *deploypb.GetRolloutRequest, opts ...gax.CallOption) (*deploypb.Rollout, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetRollout[0:len((*c.CallOptions).GetRollout):len((*c.CallOptions).GetRollout)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &deploypb.Rollout{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateRollout creates a new Rollout in a given project and location. +func (c *cloudDeployRESTClient) CreateRollout(ctx context.Context, req *deploypb.CreateRolloutRequest, opts ...gax.CallOption) (*CreateRolloutOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetRollout() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/rollouts", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + params.Add("rolloutId", fmt.Sprintf("%v", req.GetRolloutId())) + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateRolloutOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// RetryJob retries the specified Job in a Rollout. +func (c *cloudDeployRESTClient) RetryJob(ctx context.Context, req *deploypb.RetryJobRequest, opts ...gax.CallOption) (*deploypb.RetryJobResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:retryJob", req.GetRollout()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "rollout", url.QueryEscape(req.GetRollout()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).RetryJob[0:len((*c.CallOptions).RetryJob):len((*c.CallOptions).RetryJob)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &deploypb.RetryJobResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListJobRuns lists JobRuns in a given project and location. +func (c *cloudDeployRESTClient) ListJobRuns(ctx context.Context, req *deploypb.ListJobRunsRequest, opts ...gax.CallOption) *JobRunIterator { + it := &JobRunIterator{} + req = proto.Clone(req).(*deploypb.ListJobRunsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*deploypb.JobRun, string, error) { + resp := &deploypb.ListJobRunsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/jobRuns", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetJobRuns(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetJobRun gets details of a single JobRun. +func (c *cloudDeployRESTClient) GetJobRun(ctx context.Context, req *deploypb.GetJobRunRequest, opts ...gax.CallOption) (*deploypb.JobRun, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetJobRun[0:len((*c.CallOptions).GetJobRun):len((*c.CallOptions).GetJobRun)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &deploypb.JobRun{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetConfig gets the configuration for a location. +func (c *cloudDeployRESTClient) GetConfig(ctx context.Context, req *deploypb.GetConfigRequest, opts ...gax.CallOption) (*deploypb.Config, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetConfig[0:len((*c.CallOptions).GetConfig):len((*c.CallOptions).GetConfig)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &deploypb.Config{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetLocation gets information about a location. +func (c *cloudDeployRESTClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *cloudDeployRESTClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetIamPolicy gets the access control policy for a resource. Returns an empty policy +// if the resource exists and does not have a policy set. +func (c *cloudDeployRESTClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:getIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetOptions().GetRequestedPolicyVersion() != 0 { + params.Add("options.requestedPolicyVersion", fmt.Sprintf("%v", req.GetOptions().GetRequestedPolicyVersion())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SetIamPolicy sets the access control policy on the specified resource. Replaces +// any existing policy. +// +// Can return NOT_FOUND, INVALID_ARGUMENT, and PERMISSION_DENIED +// errors. +func (c *cloudDeployRESTClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:setIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// TestIamPermissions returns permissions that a caller has on the specified resource. If the +// resource does not exist, this will return an empty set of +// permissions, not a NOT_FOUND error. +// +// Note: This operation is designed to be used for building +// permission-aware UIs and command-line tools, not for authorization +// checking. This operation may “fail open” without warning. +func (c *cloudDeployRESTClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:testIamPermissions", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.TestIamPermissionsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *cloudDeployRESTClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// DeleteOperation is a utility method from google.longrunning.Operations. +func (c *cloudDeployRESTClient) DeleteOperation(ctx context.Context, req *longrunningpb.DeleteOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *cloudDeployRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *cloudDeployRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CreateDeliveryPipelineOperation manages a long-running operation from CreateDeliveryPipeline. +type CreateDeliveryPipelineOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateDeliveryPipelineOperation returns a new CreateDeliveryPipelineOperation from a given name. +// The name must be that of a previously created CreateDeliveryPipelineOperation, possibly from a different process. +func (c *cloudDeployGRPCClient) CreateDeliveryPipelineOperation(name string) *CreateDeliveryPipelineOperation { + return &CreateDeliveryPipelineOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateDeliveryPipelineOperation returns a new CreateDeliveryPipelineOperation from a given name. +// The name must be that of a previously created CreateDeliveryPipelineOperation, possibly from a different process. +func (c *cloudDeployRESTClient) CreateDeliveryPipelineOperation(name string) *CreateDeliveryPipelineOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateDeliveryPipelineOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CreateDeliveryPipelineOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*deploypb.DeliveryPipeline, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp deploypb.DeliveryPipeline + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *CreateDeliveryPipelineOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*deploypb.DeliveryPipeline, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp deploypb.DeliveryPipeline + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *CreateDeliveryPipelineOperation) Metadata() (*deploypb.OperationMetadata, error) { + var meta deploypb.OperationMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *CreateDeliveryPipelineOperation) Done() bool { + return op.lro.Done() +} + +// 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 *CreateDeliveryPipelineOperation) Name() string { + return op.lro.Name() +} + +// CreateReleaseOperation manages a long-running operation from CreateRelease. +type CreateReleaseOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateReleaseOperation returns a new CreateReleaseOperation from a given name. +// The name must be that of a previously created CreateReleaseOperation, possibly from a different process. +func (c *cloudDeployGRPCClient) CreateReleaseOperation(name string) *CreateReleaseOperation { + return &CreateReleaseOperation{ lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } +// CreateReleaseOperation returns a new CreateReleaseOperation from a given name. +// The name must be that of a previously created CreateReleaseOperation, possibly from a different process. +func (c *cloudDeployRESTClient) CreateReleaseOperation(name string) *CreateReleaseOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateReleaseOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateReleaseOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*deploypb.Release, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp deploypb.Release if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1562,6 +4031,7 @@ func (op *CreateReleaseOperation) Wait(ctx context.Context, opts ...gax.CallOpti // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateReleaseOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*deploypb.Release, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp deploypb.Release if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1599,7 +4069,8 @@ func (op *CreateReleaseOperation) Name() string { // CreateRolloutOperation manages a long-running operation from CreateRollout. type CreateRolloutOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateRolloutOperation returns a new CreateRolloutOperation from a given name. @@ -1610,10 +4081,21 @@ func (c *cloudDeployGRPCClient) CreateRolloutOperation(name string) *CreateRollo } } +// CreateRolloutOperation returns a new CreateRolloutOperation from a given name. +// The name must be that of a previously created CreateRolloutOperation, possibly from a different process. +func (c *cloudDeployRESTClient) CreateRolloutOperation(name string) *CreateRolloutOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateRolloutOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateRolloutOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*deploypb.Rollout, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp deploypb.Rollout if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1631,6 +4113,7 @@ func (op *CreateRolloutOperation) Wait(ctx context.Context, opts ...gax.CallOpti // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateRolloutOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*deploypb.Rollout, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp deploypb.Rollout if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1668,7 +4151,8 @@ func (op *CreateRolloutOperation) Name() string { // CreateTargetOperation manages a long-running operation from CreateTarget. type CreateTargetOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateTargetOperation returns a new CreateTargetOperation from a given name. @@ -1679,10 +4163,21 @@ func (c *cloudDeployGRPCClient) CreateTargetOperation(name string) *CreateTarget } } +// CreateTargetOperation returns a new CreateTargetOperation from a given name. +// The name must be that of a previously created CreateTargetOperation, possibly from a different process. +func (c *cloudDeployRESTClient) CreateTargetOperation(name string) *CreateTargetOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateTargetOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateTargetOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*deploypb.Target, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp deploypb.Target if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1700,6 +4195,7 @@ func (op *CreateTargetOperation) Wait(ctx context.Context, opts ...gax.CallOptio // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateTargetOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*deploypb.Target, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp deploypb.Target if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1737,7 +4233,8 @@ func (op *CreateTargetOperation) Name() string { // DeleteDeliveryPipelineOperation manages a long-running operation from DeleteDeliveryPipeline. type DeleteDeliveryPipelineOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteDeliveryPipelineOperation returns a new DeleteDeliveryPipelineOperation from a given name. @@ -1748,10 +4245,21 @@ func (c *cloudDeployGRPCClient) DeleteDeliveryPipelineOperation(name string) *De } } +// DeleteDeliveryPipelineOperation returns a new DeleteDeliveryPipelineOperation from a given name. +// The name must be that of a previously created DeleteDeliveryPipelineOperation, possibly from a different process. +func (c *cloudDeployRESTClient) DeleteDeliveryPipelineOperation(name string) *DeleteDeliveryPipelineOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteDeliveryPipelineOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteDeliveryPipelineOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -1765,6 +4273,7 @@ func (op *DeleteDeliveryPipelineOperation) Wait(ctx context.Context, opts ...gax // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteDeliveryPipelineOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -1795,7 +4304,8 @@ func (op *DeleteDeliveryPipelineOperation) Name() string { // DeleteTargetOperation manages a long-running operation from DeleteTarget. type DeleteTargetOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteTargetOperation returns a new DeleteTargetOperation from a given name. @@ -1806,10 +4316,21 @@ func (c *cloudDeployGRPCClient) DeleteTargetOperation(name string) *DeleteTarget } } +// DeleteTargetOperation returns a new DeleteTargetOperation from a given name. +// The name must be that of a previously created DeleteTargetOperation, possibly from a different process. +func (c *cloudDeployRESTClient) DeleteTargetOperation(name string) *DeleteTargetOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteTargetOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteTargetOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -1823,6 +4344,7 @@ func (op *DeleteTargetOperation) Wait(ctx context.Context, opts ...gax.CallOptio // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteTargetOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -1853,7 +4375,8 @@ func (op *DeleteTargetOperation) Name() string { // UpdateDeliveryPipelineOperation manages a long-running operation from UpdateDeliveryPipeline. type UpdateDeliveryPipelineOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateDeliveryPipelineOperation returns a new UpdateDeliveryPipelineOperation from a given name. @@ -1864,10 +4387,21 @@ func (c *cloudDeployGRPCClient) UpdateDeliveryPipelineOperation(name string) *Up } } +// UpdateDeliveryPipelineOperation returns a new UpdateDeliveryPipelineOperation from a given name. +// The name must be that of a previously created UpdateDeliveryPipelineOperation, possibly from a different process. +func (c *cloudDeployRESTClient) UpdateDeliveryPipelineOperation(name string) *UpdateDeliveryPipelineOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateDeliveryPipelineOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateDeliveryPipelineOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*deploypb.DeliveryPipeline, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp deploypb.DeliveryPipeline if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1885,6 +4419,7 @@ func (op *UpdateDeliveryPipelineOperation) Wait(ctx context.Context, opts ...gax // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateDeliveryPipelineOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*deploypb.DeliveryPipeline, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp deploypb.DeliveryPipeline if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1922,7 +4457,8 @@ func (op *UpdateDeliveryPipelineOperation) Name() string { // UpdateTargetOperation manages a long-running operation from UpdateTarget. type UpdateTargetOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateTargetOperation returns a new UpdateTargetOperation from a given name. @@ -1933,10 +4469,21 @@ func (c *cloudDeployGRPCClient) UpdateTargetOperation(name string) *UpdateTarget } } +// UpdateTargetOperation returns a new UpdateTargetOperation from a given name. +// The name must be that of a previously created UpdateTargetOperation, possibly from a different process. +func (c *cloudDeployRESTClient) UpdateTargetOperation(name string) *UpdateTargetOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateTargetOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateTargetOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*deploypb.Target, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp deploypb.Target if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1954,6 +4501,7 @@ func (op *UpdateTargetOperation) Wait(ctx context.Context, opts ...gax.CallOptio // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateTargetOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*deploypb.Target, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp deploypb.Target if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/deploy/apiv1/cloud_deploy_client_example_test.go b/deploy/apiv1/cloud_deploy_client_example_test.go index 2594e290b67a..d68777273a1a 100644 --- a/deploy/apiv1/cloud_deploy_client_example_test.go +++ b/deploy/apiv1/cloud_deploy_client_example_test.go @@ -44,6 +44,23 @@ func ExampleNewCloudDeployClient() { _ = c } +func ExampleNewCloudDeployRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := deploy.NewCloudDeployRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleCloudDeployClient_ListDeliveryPipelines() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/deploy/apiv1/deploypb/cloud_deploy.pb.go b/deploy/apiv1/deploypb/cloud_deploy.pb.go index afa844bebea4..352e2f299810 100644 --- a/deploy/apiv1/deploypb/cloud_deploy.pb.go +++ b/deploy/apiv1/deploypb/cloud_deploy.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/deploy/v1/cloud_deploy.proto package deploypb @@ -833,7 +833,6 @@ type DeliveryPipeline struct { // The ordering configuration of the `DeliveryPipeline`. // // Types that are assignable to Pipeline: - // // *DeliveryPipeline_SerialPipeline Pipeline isDeliveryPipeline_Pipeline `protobuf_oneof:"pipeline"` // Output only. Information around the state of the Delivery Pipeline. @@ -1107,7 +1106,6 @@ type Strategy struct { // Deployment strategy details. // // Types that are assignable to DeploymentStrategy: - // // *Strategy_Standard DeploymentStrategy isStrategy_DeploymentStrategy `protobuf_oneof:"deployment_strategy"` } @@ -1981,7 +1979,6 @@ type Target struct { // rollout. // // Types that are assignable to DeploymentTarget: - // // *Target_Gke // *Target_AnthosCluster // *Target_Run @@ -2173,7 +2170,6 @@ type ExecutionConfig struct { // Details of the environment. // // Types that are assignable to ExecutionEnvironment: - // // *ExecutionConfig_DefaultPool // *ExecutionConfig_PrivatePool ExecutionEnvironment isExecutionConfig_ExecutionEnvironment `protobuf_oneof:"execution_environment"` @@ -3426,7 +3422,6 @@ type TargetArtifact struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Uri: - // // *TargetArtifact_ArtifactUri Uri isTargetArtifact_Uri `protobuf_oneof:"uri"` // Output only. File path of the resolved Skaffold configuration relative to the URI. @@ -4234,7 +4229,6 @@ type Phase struct { // The job composition of this Phase. // // Types that are assignable to Jobs: - // // *Phase_DeploymentJobs Jobs isPhase_Jobs `protobuf_oneof:"jobs"` } @@ -4384,7 +4378,6 @@ type Job struct { // The type of Job. // // Types that are assignable to JobType: - // // *Job_DeployJob // *Job_VerifyJob JobType isJob_JobType `protobuf_oneof:"job_type"` @@ -5302,7 +5295,6 @@ type JobRun struct { // The `JobRun` type and the information for that type. // // Types that are assignable to JobRun: - // // *JobRun_DeployJobRun // *JobRun_VerifyJobRun JobRun isJobRun_JobRun `protobuf_oneof:"job_run"` diff --git a/deploy/apiv1/deploypb/deliverypipeline_notification_payload.pb.go b/deploy/apiv1/deploypb/deliverypipeline_notification_payload.pb.go index 1f213753864b..c410201fa1a4 100644 --- a/deploy/apiv1/deploypb/deliverypipeline_notification_payload.pb.go +++ b/deploy/apiv1/deploypb/deliverypipeline_notification_payload.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/deploy/v1/deliverypipeline_notification_payload.proto package deploypb diff --git a/deploy/apiv1/deploypb/jobrun_notification_payload.pb.go b/deploy/apiv1/deploypb/jobrun_notification_payload.pb.go index 7964003dd9e3..8e90bea47674 100644 --- a/deploy/apiv1/deploypb/jobrun_notification_payload.pb.go +++ b/deploy/apiv1/deploypb/jobrun_notification_payload.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/deploy/v1/jobrun_notification_payload.proto package deploypb diff --git a/deploy/apiv1/deploypb/log_enums.pb.go b/deploy/apiv1/deploypb/log_enums.pb.go index a2373e2266ee..d67320d7736b 100644 --- a/deploy/apiv1/deploypb/log_enums.pb.go +++ b/deploy/apiv1/deploypb/log_enums.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/deploy/v1/log_enums.proto package deploypb diff --git a/deploy/apiv1/deploypb/release_notification_payload.pb.go b/deploy/apiv1/deploypb/release_notification_payload.pb.go index 460fe39bc429..13248b586b68 100644 --- a/deploy/apiv1/deploypb/release_notification_payload.pb.go +++ b/deploy/apiv1/deploypb/release_notification_payload.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/deploy/v1/release_notification_payload.proto package deploypb diff --git a/deploy/apiv1/deploypb/release_render_payload.pb.go b/deploy/apiv1/deploypb/release_render_payload.pb.go index 596036b41425..7eed5c7347af 100644 --- a/deploy/apiv1/deploypb/release_render_payload.pb.go +++ b/deploy/apiv1/deploypb/release_render_payload.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/deploy/v1/release_render_payload.proto package deploypb diff --git a/deploy/apiv1/deploypb/rollout_notification_payload.pb.go b/deploy/apiv1/deploypb/rollout_notification_payload.pb.go index 393ec6f3bf22..a6030cb2cd3f 100644 --- a/deploy/apiv1/deploypb/rollout_notification_payload.pb.go +++ b/deploy/apiv1/deploypb/rollout_notification_payload.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/deploy/v1/rollout_notification_payload.proto package deploypb diff --git a/deploy/apiv1/deploypb/target_notification_payload.pb.go b/deploy/apiv1/deploypb/target_notification_payload.pb.go index 353b8d1031fd..40eba49e4f06 100644 --- a/deploy/apiv1/deploypb/target_notification_payload.pb.go +++ b/deploy/apiv1/deploypb/target_notification_payload.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/deploy/v1/target_notification_payload.proto package deploypb diff --git a/deploy/apiv1/doc.go b/deploy/apiv1/doc.go index 6c15c34e5a94..e8b89754aabf 100644 --- a/deploy/apiv1/doc.go +++ b/deploy/apiv1/doc.go @@ -84,6 +84,8 @@ package deploy // import "cloud.google.com/go/deploy/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -172,3 +174,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/deploy/apiv1/gapic_metadata.json b/deploy/apiv1/gapic_metadata.json index bd26eda83a46..e2d8aace47c7 100644 --- a/deploy/apiv1/gapic_metadata.json +++ b/deploy/apiv1/gapic_metadata.json @@ -166,6 +166,166 @@ ] } } + }, + "rest": { + "libraryClient": "CloudDeployClient", + "rpcs": { + "AbandonRelease": { + "methods": [ + "AbandonRelease" + ] + }, + "ApproveRollout": { + "methods": [ + "ApproveRollout" + ] + }, + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "CreateDeliveryPipeline": { + "methods": [ + "CreateDeliveryPipeline" + ] + }, + "CreateRelease": { + "methods": [ + "CreateRelease" + ] + }, + "CreateRollout": { + "methods": [ + "CreateRollout" + ] + }, + "CreateTarget": { + "methods": [ + "CreateTarget" + ] + }, + "DeleteDeliveryPipeline": { + "methods": [ + "DeleteDeliveryPipeline" + ] + }, + "DeleteOperation": { + "methods": [ + "DeleteOperation" + ] + }, + "DeleteTarget": { + "methods": [ + "DeleteTarget" + ] + }, + "GetConfig": { + "methods": [ + "GetConfig" + ] + }, + "GetDeliveryPipeline": { + "methods": [ + "GetDeliveryPipeline" + ] + }, + "GetIamPolicy": { + "methods": [ + "GetIamPolicy" + ] + }, + "GetJobRun": { + "methods": [ + "GetJobRun" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "GetRelease": { + "methods": [ + "GetRelease" + ] + }, + "GetRollout": { + "methods": [ + "GetRollout" + ] + }, + "GetTarget": { + "methods": [ + "GetTarget" + ] + }, + "ListDeliveryPipelines": { + "methods": [ + "ListDeliveryPipelines" + ] + }, + "ListJobRuns": { + "methods": [ + "ListJobRuns" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "ListReleases": { + "methods": [ + "ListReleases" + ] + }, + "ListRollouts": { + "methods": [ + "ListRollouts" + ] + }, + "ListTargets": { + "methods": [ + "ListTargets" + ] + }, + "RetryJob": { + "methods": [ + "RetryJob" + ] + }, + "SetIamPolicy": { + "methods": [ + "SetIamPolicy" + ] + }, + "TestIamPermissions": { + "methods": [ + "TestIamPermissions" + ] + }, + "UpdateDeliveryPipeline": { + "methods": [ + "UpdateDeliveryPipeline" + ] + }, + "UpdateTarget": { + "methods": [ + "UpdateTarget" + ] + } + } } } } diff --git a/dialogflow/apiv2/agents_client.go b/dialogflow/apiv2/agents_client.go index 188d228254de..f736b1074ce6 100644 --- a/dialogflow/apiv2/agents_client.go +++ b/dialogflow/apiv2/agents_client.go @@ -17,9 +17,12 @@ package dialogflow import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,15 +30,18 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" structpb "google.golang.org/protobuf/types/known/structpb" ) @@ -181,6 +187,106 @@ func defaultAgentsCallOptions() *AgentsCallOptions { } } +func defaultAgentsRESTCallOptions() *AgentsCallOptions { + return &AgentsCallOptions{ + GetAgent: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + SetAgent: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeleteAgent: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + SearchAgents: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + TrainAgent: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ExportAgent: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ImportAgent: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + RestoreAgent: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetValidationResult: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + CancelOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalAgentsClient is an interface that defines the methods available from Dialogflow API. type internalAgentsClient interface { Close() error @@ -526,6 +632,89 @@ func (c *agentsGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type agentsRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing AgentsClient + CallOptions **AgentsCallOptions +} + +// NewAgentsRESTClient creates a new agents rest client. +// +// Service for managing Agents. +func NewAgentsRESTClient(ctx context.Context, opts ...option.ClientOption) (*AgentsClient, error) { + clientOpts := append(defaultAgentsRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultAgentsRESTCallOptions() + c := &agentsRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &AgentsClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultAgentsRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://dialogflow.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://dialogflow.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://dialogflow.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *agentsRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *agentsRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *agentsRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *agentsGRPCClient) GetAgent(ctx context.Context, req *dialogflowpb.GetAgentRequest, opts ...gax.CallOption) (*dialogflowpb.Agent, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) @@ -888,98 +1077,1135 @@ func (c *agentsGRPCClient) ListOperations(ctx context.Context, req *longrunningp return it } -// ExportAgentOperation manages a long-running operation from ExportAgent. -type ExportAgentOperation struct { - lro *longrunning.Operation -} +// GetAgent retrieves the specified agent. +func (c *agentsRESTClient) GetAgent(ctx context.Context, req *dialogflowpb.GetAgentRequest, opts ...gax.CallOption) (*dialogflowpb.Agent, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/agent", req.GetParent()) -// ExportAgentOperation returns a new ExportAgentOperation from a given name. -// The name must be that of a previously created ExportAgentOperation, possibly from a different process. -func (c *agentsGRPCClient) ExportAgentOperation(name string) *ExportAgentOperation { - return &ExportAgentOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetAgent[0:len((*c.CallOptions).GetAgent):len((*c.CallOptions).GetAgent)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dialogflowpb.Agent{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e } + return resp, nil } -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// SetAgent creates/updates the specified agent. // -// See documentation of Poll for error-handling information. -func (op *ExportAgentOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*dialogflowpb.ExportAgentResponse, error) { - var resp dialogflowpb.ExportAgentResponse - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { +// Note: You should always train an agent prior to sending it queries. See the +// training +// documentation (at https://cloud.google.com/dialogflow/es/docs/training). +func (c *agentsRESTClient) SetAgent(ctx context.Context, req *dialogflowpb.SetAgentRequest, opts ...gax.CallOption) (*dialogflowpb.Agent, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetAgent() + jsonReq, err := m.Marshal(body) + if err != nil { return nil, err } - return &resp, nil -} -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *ExportAgentOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*dialogflowpb.ExportAgentResponse, error) { - var resp dialogflowpb.ExportAgentResponse - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - if !op.Done() { - return nil, nil - } - return &resp, nil -} + baseUrl.Path += fmt.Sprintf("/v2/%v/agent", req.GetAgent().GetParent()) -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *ExportAgentOperation) Metadata() (*structpb.Struct, error) { - var meta structpb.Struct - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { - return nil, err + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) } - return &meta, nil -} -// Done reports whether the long-running operation has completed. -func (op *ExportAgentOperation) Done() bool { - return op.lro.Done() -} + baseUrl.RawQuery = params.Encode() -// 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 *ExportAgentOperation) Name() string { - return op.lro.Name() -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "agent.parent", url.QueryEscape(req.GetAgent().GetParent()))) -// ImportAgentOperation manages a long-running operation from ImportAgent. -type ImportAgentOperation struct { - lro *longrunning.Operation -} + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetAgent[0:len((*c.CallOptions).SetAgent):len((*c.CallOptions).SetAgent)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dialogflowpb.Agent{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers -// ImportAgentOperation returns a new ImportAgentOperation from a given name. -// The name must be that of a previously created ImportAgentOperation, possibly from a different process. -func (c *agentsGRPCClient) ImportAgentOperation(name string) *ImportAgentOperation { - return &ImportAgentOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e } + return resp, nil } -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *ImportAgentOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { - return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) -} +// DeleteAgent deletes the specified agent. +func (c *agentsRESTClient) DeleteAgent(ctx context.Context, req *dialogflowpb.DeleteAgentRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/agent", req.GetParent()) -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// SearchAgents returns the list of agents. +// +// Since there is at most one conversational agent per project, this method is +// useful primarily for listing all agents across projects the caller has +// access to. One can achieve that with a wildcard project collection id “-”. +// Refer to List +// Sub-Collections (at https://cloud.google.com/apis/design/design_patterns#list_sub-collections). +func (c *agentsRESTClient) SearchAgents(ctx context.Context, req *dialogflowpb.SearchAgentsRequest, opts ...gax.CallOption) *AgentIterator { + it := &AgentIterator{} + req = proto.Clone(req).(*dialogflowpb.SearchAgentsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*dialogflowpb.Agent, string, error) { + resp := &dialogflowpb.SearchAgentsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/agent:search", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetAgents(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// TrainAgent trains the specified agent. +// +// This method is a long-running +// operation (at https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). +// The returned Operation type has the following method-specific fields: +// +// metadata: An empty Struct +// message (at https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) +// +// response: An Empty +// message (at https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) +// +// Note: You should always train an agent prior to sending it queries. See the +// training +// documentation (at https://cloud.google.com/dialogflow/es/docs/training). +func (c *agentsRESTClient) TrainAgent(ctx context.Context, req *dialogflowpb.TrainAgentRequest, opts ...gax.CallOption) (*TrainAgentOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/agent:train", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &TrainAgentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ExportAgent exports the specified agent to a ZIP file. +// +// This method is a long-running +// operation (at https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). +// The returned Operation type has the following method-specific fields: +// +// metadata: An empty Struct +// message (at https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) +// +// response: ExportAgentResponse +func (c *agentsRESTClient) ExportAgent(ctx context.Context, req *dialogflowpb.ExportAgentRequest, opts ...gax.CallOption) (*ExportAgentOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/agent:export", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &ExportAgentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ImportAgent imports the specified agent from a ZIP file. +// +// Uploads new intents and entity types without deleting the existing ones. +// Intents and entity types with the same name are replaced with the new +// versions from ImportAgentRequest. After the import, the imported draft +// agent will be trained automatically (unless disabled in agent settings). +// However, once the import is done, training may not be completed yet. Please +// call TrainAgent and wait for the operation it returns in order to train +// explicitly. +// +// This method is a long-running +// operation (at https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). +// The returned Operation type has the following method-specific fields: +// +// metadata: An empty Struct +// message (at https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) +// +// response: An Empty +// message (at https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) +// +// The operation only tracks when importing is complete, not when it is done +// training. +// +// Note: You should always train an agent prior to sending it queries. See the +// training +// documentation (at https://cloud.google.com/dialogflow/es/docs/training). +func (c *agentsRESTClient) ImportAgent(ctx context.Context, req *dialogflowpb.ImportAgentRequest, opts ...gax.CallOption) (*ImportAgentOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/agent:import", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &ImportAgentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// RestoreAgent restores the specified agent from a ZIP file. +// +// Replaces the current agent version with a new one. All the intents and +// entity types in the older version are deleted. After the restore, the +// restored draft agent will be trained automatically (unless disabled in +// agent settings). However, once the restore is done, training may not be +// completed yet. Please call TrainAgent and wait for the operation it +// returns in order to train explicitly. +// +// This method is a long-running +// operation (at https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). +// The returned Operation type has the following method-specific fields: +// +// metadata: An empty Struct +// message (at https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) +// +// response: An Empty +// message (at https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) +// +// The operation only tracks when restoring is complete, not when it is done +// training. +// +// Note: You should always train an agent prior to sending it queries. See the +// training +// documentation (at https://cloud.google.com/dialogflow/es/docs/training). +func (c *agentsRESTClient) RestoreAgent(ctx context.Context, req *dialogflowpb.RestoreAgentRequest, opts ...gax.CallOption) (*RestoreAgentOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/agent:restore", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &RestoreAgentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetValidationResult gets agent validation result. Agent validation is performed during +// training time and is updated automatically when training is completed. +func (c *agentsRESTClient) GetValidationResult(ctx context.Context, req *dialogflowpb.GetValidationResultRequest, opts ...gax.CallOption) (*dialogflowpb.ValidationResult, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/agent/validationResult", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetLanguageCode() != "" { + params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetValidationResult[0:len((*c.CallOptions).GetValidationResult):len((*c.CallOptions).GetValidationResult)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dialogflowpb.ValidationResult{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetLocation gets information about a location. +func (c *agentsRESTClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *agentsRESTClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *agentsRESTClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *agentsRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *agentsRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// ExportAgentOperation manages a long-running operation from ExportAgent. +type ExportAgentOperation struct { + lro *longrunning.Operation + pollPath string +} + +// ExportAgentOperation returns a new ExportAgentOperation from a given name. +// The name must be that of a previously created ExportAgentOperation, possibly from a different process. +func (c *agentsGRPCClient) ExportAgentOperation(name string) *ExportAgentOperation { + return &ExportAgentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// ExportAgentOperation returns a new ExportAgentOperation from a given name. +// The name must be that of a previously created ExportAgentOperation, possibly from a different process. +func (c *agentsRESTClient) ExportAgentOperation(name string) *ExportAgentOperation { + override := fmt.Sprintf("/v2/%s", name) + return &ExportAgentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *ExportAgentOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*dialogflowpb.ExportAgentResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp dialogflowpb.ExportAgentResponse + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *ExportAgentOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*dialogflowpb.ExportAgentResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp dialogflowpb.ExportAgentResponse + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *ExportAgentOperation) Metadata() (*structpb.Struct, error) { + var meta structpb.Struct + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *ExportAgentOperation) Done() bool { + return op.lro.Done() +} + +// 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 *ExportAgentOperation) Name() string { + return op.lro.Name() +} + +// ImportAgentOperation manages a long-running operation from ImportAgent. +type ImportAgentOperation struct { + lro *longrunning.Operation + pollPath string +} + +// ImportAgentOperation returns a new ImportAgentOperation from a given name. +// The name must be that of a previously created ImportAgentOperation, possibly from a different process. +func (c *agentsGRPCClient) ImportAgentOperation(name string) *ImportAgentOperation { + return &ImportAgentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// ImportAgentOperation returns a new ImportAgentOperation from a given name. +// The name must be that of a previously created ImportAgentOperation, possibly from a different process. +func (c *agentsRESTClient) ImportAgentOperation(name string) *ImportAgentOperation { + override := fmt.Sprintf("/v2/%s", name) + return &ImportAgentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *ImportAgentOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. // // 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. @@ -987,6 +2213,7 @@ func (op *ImportAgentOperation) Wait(ctx context.Context, opts ...gax.CallOption // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *ImportAgentOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -1017,7 +2244,8 @@ func (op *ImportAgentOperation) Name() string { // RestoreAgentOperation manages a long-running operation from RestoreAgent. type RestoreAgentOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // RestoreAgentOperation returns a new RestoreAgentOperation from a given name. @@ -1028,10 +2256,21 @@ func (c *agentsGRPCClient) RestoreAgentOperation(name string) *RestoreAgentOpera } } +// RestoreAgentOperation returns a new RestoreAgentOperation from a given name. +// The name must be that of a previously created RestoreAgentOperation, possibly from a different process. +func (c *agentsRESTClient) RestoreAgentOperation(name string) *RestoreAgentOperation { + override := fmt.Sprintf("/v2/%s", name) + return &RestoreAgentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *RestoreAgentOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -1045,6 +2284,7 @@ func (op *RestoreAgentOperation) Wait(ctx context.Context, opts ...gax.CallOptio // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *RestoreAgentOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -1075,7 +2315,8 @@ func (op *RestoreAgentOperation) Name() string { // TrainAgentOperation manages a long-running operation from TrainAgent. type TrainAgentOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // TrainAgentOperation returns a new TrainAgentOperation from a given name. @@ -1086,10 +2327,21 @@ func (c *agentsGRPCClient) TrainAgentOperation(name string) *TrainAgentOperation } } +// TrainAgentOperation returns a new TrainAgentOperation from a given name. +// The name must be that of a previously created TrainAgentOperation, possibly from a different process. +func (c *agentsRESTClient) TrainAgentOperation(name string) *TrainAgentOperation { + override := fmt.Sprintf("/v2/%s", name) + return &TrainAgentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *TrainAgentOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -1103,6 +2355,7 @@ func (op *TrainAgentOperation) Wait(ctx context.Context, opts ...gax.CallOption) // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *TrainAgentOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } diff --git a/dialogflow/apiv2/agents_client_example_test.go b/dialogflow/apiv2/agents_client_example_test.go index 1775cd6b6248..5abea2da1b6d 100644 --- a/dialogflow/apiv2/agents_client_example_test.go +++ b/dialogflow/apiv2/agents_client_example_test.go @@ -43,6 +43,23 @@ func ExampleNewAgentsClient() { _ = c } +func ExampleNewAgentsRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := dialogflow.NewAgentsRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleAgentsClient_GetAgent() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/dialogflow/apiv2/answer_records_client.go b/dialogflow/apiv2/answer_records_client.go index 3430fae62024..d59cfc13ec5d 100644 --- a/dialogflow/apiv2/answer_records_client.go +++ b/dialogflow/apiv2/answer_records_client.go @@ -17,23 +17,29 @@ package dialogflow import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" dialogflowpb "cloud.google.com/go/dialogflow/apiv2/dialogflowpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -94,6 +100,36 @@ func defaultAnswerRecordsCallOptions() *AnswerRecordsCallOptions { } } +func defaultAnswerRecordsRESTCallOptions() *AnswerRecordsCallOptions { + return &AnswerRecordsCallOptions{ + ListAnswerRecords: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UpdateAnswerRecord: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + CancelOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalAnswerRecordsClient is an interface that defines the methods available from Dialogflow API. type internalAnswerRecordsClient interface { Close() error @@ -266,6 +302,74 @@ func (c *answerRecordsGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type answerRecordsRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing AnswerRecordsClient + CallOptions **AnswerRecordsCallOptions +} + +// NewAnswerRecordsRESTClient creates a new answer records rest client. +// +// Service for managing AnswerRecords. +func NewAnswerRecordsRESTClient(ctx context.Context, opts ...option.ClientOption) (*AnswerRecordsClient, error) { + clientOpts := append(defaultAnswerRecordsRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultAnswerRecordsRESTCallOptions() + c := &answerRecordsRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &AnswerRecordsClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultAnswerRecordsRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://dialogflow.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://dialogflow.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://dialogflow.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *answerRecordsRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *answerRecordsRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *answerRecordsRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *answerRecordsGRPCClient) ListAnswerRecords(ctx context.Context, req *dialogflowpb.ListAnswerRecordsRequest, opts ...gax.CallOption) *AnswerRecordIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -470,6 +574,508 @@ func (c *answerRecordsGRPCClient) ListOperations(ctx context.Context, req *longr return it } +// ListAnswerRecords returns the list of all answer records in the specified project in reverse +// chronological order. +func (c *answerRecordsRESTClient) ListAnswerRecords(ctx context.Context, req *dialogflowpb.ListAnswerRecordsRequest, opts ...gax.CallOption) *AnswerRecordIterator { + it := &AnswerRecordIterator{} + req = proto.Clone(req).(*dialogflowpb.ListAnswerRecordsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*dialogflowpb.AnswerRecord, string, error) { + resp := &dialogflowpb.ListAnswerRecordsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/answerRecords", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetAnswerRecords(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// UpdateAnswerRecord updates the specified answer record. +func (c *answerRecordsRESTClient) UpdateAnswerRecord(ctx context.Context, req *dialogflowpb.UpdateAnswerRecordRequest, opts ...gax.CallOption) (*dialogflowpb.AnswerRecord, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetAnswerRecord() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetAnswerRecord().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "answer_record.name", url.QueryEscape(req.GetAnswerRecord().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateAnswerRecord[0:len((*c.CallOptions).UpdateAnswerRecord):len((*c.CallOptions).UpdateAnswerRecord)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dialogflowpb.AnswerRecord{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetLocation gets information about a location. +func (c *answerRecordsRESTClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *answerRecordsRESTClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *answerRecordsRESTClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *answerRecordsRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *answerRecordsRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + // AnswerRecordIterator manages a stream of *dialogflowpb.AnswerRecord. type AnswerRecordIterator struct { items []*dialogflowpb.AnswerRecord diff --git a/dialogflow/apiv2/answer_records_client_example_test.go b/dialogflow/apiv2/answer_records_client_example_test.go index 7dccb1f672d1..9b6ad4108906 100644 --- a/dialogflow/apiv2/answer_records_client_example_test.go +++ b/dialogflow/apiv2/answer_records_client_example_test.go @@ -43,6 +43,23 @@ func ExampleNewAnswerRecordsClient() { _ = c } +func ExampleNewAnswerRecordsRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := dialogflow.NewAnswerRecordsRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleAnswerRecordsClient_ListAnswerRecords() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/dialogflow/apiv2/contexts_client.go b/dialogflow/apiv2/contexts_client.go index d68ac78d850a..0b957936c4ad 100644 --- a/dialogflow/apiv2/contexts_client.go +++ b/dialogflow/apiv2/contexts_client.go @@ -17,23 +17,29 @@ package dialogflow import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" dialogflowpb "cloud.google.com/go/dialogflow/apiv2/dialogflowpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -142,6 +148,76 @@ func defaultContextsCallOptions() *ContextsCallOptions { } } +func defaultContextsRESTCallOptions() *ContextsCallOptions { + return &ContextsCallOptions{ + ListContexts: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetContext: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateContext: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UpdateContext: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeleteContext: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeleteAllContexts: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + CancelOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalContextsClient is an interface that defines the methods available from Dialogflow API. type internalContextsClient interface { Close() error @@ -339,6 +415,74 @@ func (c *contextsGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type contextsRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing ContextsClient + CallOptions **ContextsCallOptions +} + +// NewContextsRESTClient creates a new contexts rest client. +// +// Service for managing Contexts. +func NewContextsRESTClient(ctx context.Context, opts ...option.ClientOption) (*ContextsClient, error) { + clientOpts := append(defaultContextsRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultContextsRESTCallOptions() + c := &contextsRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &ContextsClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultContextsRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://dialogflow.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://dialogflow.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://dialogflow.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *contextsRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *contextsRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *contextsRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *contextsGRPCClient) ListContexts(ctx context.Context, req *dialogflowpb.ListContextsRequest, opts ...gax.CallOption) *ContextIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -623,6 +767,709 @@ func (c *contextsGRPCClient) ListOperations(ctx context.Context, req *longrunnin return it } +// ListContexts returns the list of all contexts in the specified session. +func (c *contextsRESTClient) ListContexts(ctx context.Context, req *dialogflowpb.ListContextsRequest, opts ...gax.CallOption) *ContextIterator { + it := &ContextIterator{} + req = proto.Clone(req).(*dialogflowpb.ListContextsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*dialogflowpb.Context, string, error) { + resp := &dialogflowpb.ListContextsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/contexts", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetContexts(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetContext retrieves the specified context. +func (c *contextsRESTClient) GetContext(ctx context.Context, req *dialogflowpb.GetContextRequest, opts ...gax.CallOption) (*dialogflowpb.Context, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetContext[0:len((*c.CallOptions).GetContext):len((*c.CallOptions).GetContext)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dialogflowpb.Context{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateContext creates a context. +// +// If the specified context already exists, overrides the context. +func (c *contextsRESTClient) CreateContext(ctx context.Context, req *dialogflowpb.CreateContextRequest, opts ...gax.CallOption) (*dialogflowpb.Context, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetContext() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/contexts", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateContext[0:len((*c.CallOptions).CreateContext):len((*c.CallOptions).CreateContext)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dialogflowpb.Context{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateContext updates the specified context. +func (c *contextsRESTClient) UpdateContext(ctx context.Context, req *dialogflowpb.UpdateContextRequest, opts ...gax.CallOption) (*dialogflowpb.Context, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetContext() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetContext().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "context.name", url.QueryEscape(req.GetContext().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateContext[0:len((*c.CallOptions).UpdateContext):len((*c.CallOptions).UpdateContext)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dialogflowpb.Context{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteContext deletes the specified context. +func (c *contextsRESTClient) DeleteContext(ctx context.Context, req *dialogflowpb.DeleteContextRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// DeleteAllContexts deletes all active contexts in the specified session. +func (c *contextsRESTClient) DeleteAllContexts(ctx context.Context, req *dialogflowpb.DeleteAllContextsRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/contexts", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetLocation gets information about a location. +func (c *contextsRESTClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *contextsRESTClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *contextsRESTClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *contextsRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *contextsRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + // ContextIterator manages a stream of *dialogflowpb.Context. type ContextIterator struct { items []*dialogflowpb.Context diff --git a/dialogflow/apiv2/contexts_client_example_test.go b/dialogflow/apiv2/contexts_client_example_test.go index 90176288c839..c179d0fd5914 100644 --- a/dialogflow/apiv2/contexts_client_example_test.go +++ b/dialogflow/apiv2/contexts_client_example_test.go @@ -43,6 +43,23 @@ func ExampleNewContextsClient() { _ = c } +func ExampleNewContextsRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := dialogflow.NewContextsRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleContextsClient_ListContexts() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/dialogflow/apiv2/conversation_datasets_client.go b/dialogflow/apiv2/conversation_datasets_client.go index 63d0746d9b1f..c41e08e4a346 100644 --- a/dialogflow/apiv2/conversation_datasets_client.go +++ b/dialogflow/apiv2/conversation_datasets_client.go @@ -17,9 +17,12 @@ package dialogflow import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,15 +30,18 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -132,6 +138,66 @@ func defaultConversationDatasetsCallOptions() *ConversationDatasetsCallOptions { } } +func defaultConversationDatasetsRESTCallOptions() *ConversationDatasetsCallOptions { + return &ConversationDatasetsCallOptions{ + CreateConversationDataset: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetConversationDataset: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListConversationDatasets: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeleteConversationDataset: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ImportConversationData: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + CancelOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalConversationDatasetsClient is an interface that defines the methods available from Dialogflow API. type internalConversationDatasetsClient interface { Close() error @@ -397,6 +463,92 @@ func (c *conversationDatasetsGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type conversationDatasetsRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing ConversationDatasetsClient + CallOptions **ConversationDatasetsCallOptions +} + +// NewConversationDatasetsRESTClient creates a new conversation datasets rest client. +// +// Conversation datasets. +// +// Conversation datasets contain raw conversation files and their +// customizable metadata that can be used for model training. +func NewConversationDatasetsRESTClient(ctx context.Context, opts ...option.ClientOption) (*ConversationDatasetsClient, error) { + clientOpts := append(defaultConversationDatasetsRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultConversationDatasetsRESTCallOptions() + c := &conversationDatasetsRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &ConversationDatasetsClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultConversationDatasetsRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://dialogflow.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://dialogflow.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://dialogflow.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *conversationDatasetsRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *conversationDatasetsRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *conversationDatasetsRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *conversationDatasetsGRPCClient) CreateConversationDataset(ctx context.Context, req *dialogflowpb.CreateConversationDatasetRequest, opts ...gax.CallOption) (*CreateConversationDatasetOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) @@ -673,9 +825,721 @@ func (c *conversationDatasetsGRPCClient) ListOperations(ctx context.Context, req return it } +// CreateConversationDataset creates a new conversation dataset. +// +// This method is a long-running +// operation (at https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). +// The returned Operation type has the following method-specific fields: +// +// metadata: CreateConversationDatasetOperationMetadata +// +// response: ConversationDataset +func (c *conversationDatasetsRESTClient) CreateConversationDataset(ctx context.Context, req *dialogflowpb.CreateConversationDatasetRequest, opts ...gax.CallOption) (*CreateConversationDatasetOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetConversationDataset() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/conversationDatasets", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &CreateConversationDatasetOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetConversationDataset retrieves the specified conversation dataset. +func (c *conversationDatasetsRESTClient) GetConversationDataset(ctx context.Context, req *dialogflowpb.GetConversationDatasetRequest, opts ...gax.CallOption) (*dialogflowpb.ConversationDataset, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetConversationDataset[0:len((*c.CallOptions).GetConversationDataset):len((*c.CallOptions).GetConversationDataset)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dialogflowpb.ConversationDataset{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListConversationDatasets returns the list of all conversation datasets in the specified +// project and location. +func (c *conversationDatasetsRESTClient) ListConversationDatasets(ctx context.Context, req *dialogflowpb.ListConversationDatasetsRequest, opts ...gax.CallOption) *ConversationDatasetIterator { + it := &ConversationDatasetIterator{} + req = proto.Clone(req).(*dialogflowpb.ListConversationDatasetsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*dialogflowpb.ConversationDataset, string, error) { + resp := &dialogflowpb.ListConversationDatasetsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/conversationDatasets", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetConversationDatasets(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// DeleteConversationDataset deletes the specified conversation dataset. +// +// This method is a long-running +// operation (at https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). +// The returned Operation type has the following method-specific fields: +// +// metadata: DeleteConversationDatasetOperationMetadata +// +// response: An Empty +// message (at https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) +func (c *conversationDatasetsRESTClient) DeleteConversationDataset(ctx context.Context, req *dialogflowpb.DeleteConversationDatasetRequest, opts ...gax.CallOption) (*DeleteConversationDatasetOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &DeleteConversationDatasetOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ImportConversationData import data into the specified conversation dataset. Note that it +// is not allowed to import data to a conversation dataset that +// already has data in it. +// +// This method is a long-running +// operation (at https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). +// The returned Operation type has the following method-specific fields: +// +// metadata: ImportConversationDataOperationMetadata +// +// response: ImportConversationDataOperationResponse +func (c *conversationDatasetsRESTClient) ImportConversationData(ctx context.Context, req *dialogflowpb.ImportConversationDataRequest, opts ...gax.CallOption) (*ImportConversationDataOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:importConversationData", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &ImportConversationDataOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetLocation gets information about a location. +func (c *conversationDatasetsRESTClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *conversationDatasetsRESTClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *conversationDatasetsRESTClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *conversationDatasetsRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *conversationDatasetsRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + // CreateConversationDatasetOperation manages a long-running operation from CreateConversationDataset. type CreateConversationDatasetOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateConversationDatasetOperation returns a new CreateConversationDatasetOperation from a given name. @@ -686,10 +1550,21 @@ func (c *conversationDatasetsGRPCClient) CreateConversationDatasetOperation(name } } +// CreateConversationDatasetOperation returns a new CreateConversationDatasetOperation from a given name. +// The name must be that of a previously created CreateConversationDatasetOperation, possibly from a different process. +func (c *conversationDatasetsRESTClient) CreateConversationDatasetOperation(name string) *CreateConversationDatasetOperation { + override := fmt.Sprintf("/v2/%s", name) + return &CreateConversationDatasetOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateConversationDatasetOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*dialogflowpb.ConversationDataset, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp dialogflowpb.ConversationDataset if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -707,6 +1582,7 @@ func (op *CreateConversationDatasetOperation) Wait(ctx context.Context, opts ... // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateConversationDatasetOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*dialogflowpb.ConversationDataset, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp dialogflowpb.ConversationDataset if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -744,7 +1620,8 @@ func (op *CreateConversationDatasetOperation) Name() string { // DeleteConversationDatasetOperation manages a long-running operation from DeleteConversationDataset. type DeleteConversationDatasetOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteConversationDatasetOperation returns a new DeleteConversationDatasetOperation from a given name. @@ -755,10 +1632,21 @@ func (c *conversationDatasetsGRPCClient) DeleteConversationDatasetOperation(name } } +// DeleteConversationDatasetOperation returns a new DeleteConversationDatasetOperation from a given name. +// The name must be that of a previously created DeleteConversationDatasetOperation, possibly from a different process. +func (c *conversationDatasetsRESTClient) DeleteConversationDatasetOperation(name string) *DeleteConversationDatasetOperation { + override := fmt.Sprintf("/v2/%s", name) + return &DeleteConversationDatasetOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteConversationDatasetOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -772,6 +1660,7 @@ func (op *DeleteConversationDatasetOperation) Wait(ctx context.Context, opts ... // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteConversationDatasetOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -802,7 +1691,8 @@ func (op *DeleteConversationDatasetOperation) Name() string { // ImportConversationDataOperation manages a long-running operation from ImportConversationData. type ImportConversationDataOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // ImportConversationDataOperation returns a new ImportConversationDataOperation from a given name. @@ -813,10 +1703,21 @@ func (c *conversationDatasetsGRPCClient) ImportConversationDataOperation(name st } } +// ImportConversationDataOperation returns a new ImportConversationDataOperation from a given name. +// The name must be that of a previously created ImportConversationDataOperation, possibly from a different process. +func (c *conversationDatasetsRESTClient) ImportConversationDataOperation(name string) *ImportConversationDataOperation { + override := fmt.Sprintf("/v2/%s", name) + return &ImportConversationDataOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *ImportConversationDataOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*dialogflowpb.ImportConversationDataOperationResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp dialogflowpb.ImportConversationDataOperationResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -834,6 +1735,7 @@ func (op *ImportConversationDataOperation) Wait(ctx context.Context, opts ...gax // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *ImportConversationDataOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*dialogflowpb.ImportConversationDataOperationResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp dialogflowpb.ImportConversationDataOperationResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/dialogflow/apiv2/conversation_datasets_client_example_test.go b/dialogflow/apiv2/conversation_datasets_client_example_test.go index 4e989da290ee..f911b417d5d8 100644 --- a/dialogflow/apiv2/conversation_datasets_client_example_test.go +++ b/dialogflow/apiv2/conversation_datasets_client_example_test.go @@ -43,6 +43,23 @@ func ExampleNewConversationDatasetsClient() { _ = c } +func ExampleNewConversationDatasetsRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := dialogflow.NewConversationDatasetsRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleConversationDatasetsClient_CreateConversationDataset() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/dialogflow/apiv2/conversation_models_client.go b/dialogflow/apiv2/conversation_models_client.go index 3a955e0a5129..ad1b155f0b20 100644 --- a/dialogflow/apiv2/conversation_models_client.go +++ b/dialogflow/apiv2/conversation_models_client.go @@ -17,9 +17,12 @@ package dialogflow import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,15 +30,18 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -180,6 +186,106 @@ func defaultConversationModelsCallOptions() *ConversationModelsCallOptions { } } +func defaultConversationModelsRESTCallOptions() *ConversationModelsCallOptions { + return &ConversationModelsCallOptions{ + CreateConversationModel: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetConversationModel: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListConversationModels: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeleteConversationModel: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeployConversationModel: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UndeployConversationModel: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetConversationModelEvaluation: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListConversationModelEvaluations: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateConversationModelEvaluation: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + CancelOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalConversationModelsClient is an interface that defines the methods available from Dialogflow API. type internalConversationModelsClient interface { Close() error @@ -491,6 +597,89 @@ func (c *conversationModelsGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type conversationModelsRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing ConversationModelsClient + CallOptions **ConversationModelsCallOptions +} + +// NewConversationModelsRESTClient creates a new conversation models rest client. +// +// Manages a collection of models for human agent assistant. +func NewConversationModelsRESTClient(ctx context.Context, opts ...option.ClientOption) (*ConversationModelsClient, error) { + clientOpts := append(defaultConversationModelsRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultConversationModelsRESTCallOptions() + c := &conversationModelsRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &ConversationModelsClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultConversationModelsRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://dialogflow.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://dialogflow.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://dialogflow.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *conversationModelsRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *conversationModelsRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *conversationModelsRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *conversationModelsGRPCClient) CreateConversationModel(ctx context.Context, req *dialogflowpb.CreateConversationModelRequest, opts ...gax.CallOption) (*CreateConversationModelOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) @@ -882,128 +1071,1161 @@ func (c *conversationModelsGRPCClient) ListOperations(ctx context.Context, req * return it } -// CreateConversationModelOperation manages a long-running operation from CreateConversationModel. -type CreateConversationModelOperation struct { - lro *longrunning.Operation -} - -// CreateConversationModelOperation returns a new CreateConversationModelOperation from a given name. -// The name must be that of a previously created CreateConversationModelOperation, possibly from a different process. -func (c *conversationModelsGRPCClient) CreateConversationModelOperation(name string) *CreateConversationModelOperation { - return &CreateConversationModelOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} - -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// CreateConversationModel creates a model. // -// See documentation of Poll for error-handling information. -func (op *CreateConversationModelOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*dialogflowpb.ConversationModel, error) { - var resp dialogflowpb.ConversationModel - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { - return nil, err - } - return &resp, nil -} - -// Poll fetches the latest state of the long-running operation. +// This method is a long-running +// operation (at https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). +// The returned Operation type has the following method-specific fields: // -// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// metadata: CreateConversationModelOperationMetadata // -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *CreateConversationModelOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*dialogflowpb.ConversationModel, error) { - var resp dialogflowpb.ConversationModel - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { +// response: ConversationModel +func (c *conversationModelsRESTClient) CreateConversationModel(ctx context.Context, req *dialogflowpb.CreateConversationModelRequest, opts ...gax.CallOption) (*CreateConversationModelOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetConversationModel() + jsonReq, err := m.Marshal(body) + if err != nil { return nil, err } - if !op.Done() { - return nil, nil - } - return &resp, nil -} -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *CreateConversationModelOperation) Metadata() (*dialogflowpb.CreateConversationModelOperationMetadata, error) { - var meta dialogflowpb.CreateConversationModelOperationMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - return &meta, nil -} + baseUrl.Path += fmt.Sprintf("/v2/%v/conversationModels", req.GetParent()) -// Done reports whether the long-running operation has completed. -func (op *CreateConversationModelOperation) Done() bool { - return op.lro.Done() -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") -// 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 *CreateConversationModelOperation) Name() string { - return op.lro.Name() -} + baseUrl.RawQuery = params.Encode() -// CreateConversationModelEvaluationOperation manages a long-running operation from CreateConversationModelEvaluation. -type CreateConversationModelEvaluationOperation struct { - lro *longrunning.Operation -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) -// CreateConversationModelEvaluationOperation returns a new CreateConversationModelEvaluationOperation from a given name. -// The name must be that of a previously created CreateConversationModelEvaluationOperation, possibly from a different process. -func (c *conversationModelsGRPCClient) CreateConversationModelEvaluationOperation(name string) *CreateConversationModelEvaluationOperation { - return &CreateConversationModelEvaluationOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *CreateConversationModelEvaluationOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*dialogflowpb.ConversationModelEvaluation, error) { - var resp dialogflowpb.ConversationModelEvaluation - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { - return nil, err + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e } - return &resp, nil + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &CreateConversationModelOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil } -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *CreateConversationModelEvaluationOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*dialogflowpb.ConversationModelEvaluation, error) { - var resp dialogflowpb.ConversationModelEvaluation - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { +// GetConversationModel gets conversation model. +func (c *conversationModelsRESTClient) GetConversationModel(ctx context.Context, req *dialogflowpb.GetConversationModelRequest, opts ...gax.CallOption) (*dialogflowpb.ConversationModel, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - if !op.Done() { - return nil, nil - } - return &resp, nil -} + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *CreateConversationModelEvaluationOperation) Metadata() (*dialogflowpb.CreateConversationModelEvaluationOperationMetadata, error) { - var meta dialogflowpb.CreateConversationModelEvaluationOperationMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetConversationModel[0:len((*c.CallOptions).GetConversationModel):len((*c.CallOptions).GetConversationModel)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dialogflowpb.ConversationModel{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListConversationModels lists conversation models. +func (c *conversationModelsRESTClient) ListConversationModels(ctx context.Context, req *dialogflowpb.ListConversationModelsRequest, opts ...gax.CallOption) *ConversationModelIterator { + it := &ConversationModelIterator{} + req = proto.Clone(req).(*dialogflowpb.ListConversationModelsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*dialogflowpb.ConversationModel, string, error) { + resp := &dialogflowpb.ListConversationModelsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/conversationModels", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetConversationModels(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// DeleteConversationModel deletes a model. +// +// This method is a long-running +// operation (at https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). +// The returned Operation type has the following method-specific fields: +// +// metadata: DeleteConversationModelOperationMetadata +// +// response: An Empty +// message (at https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) +func (c *conversationModelsRESTClient) DeleteConversationModel(ctx context.Context, req *dialogflowpb.DeleteConversationModelRequest, opts ...gax.CallOption) (*DeleteConversationModelOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &DeleteConversationModelOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeployConversationModel deploys a model. If a model is already deployed, deploying it +// has no effect. A model can only serve prediction requests after it gets +// deployed. For article suggestion, custom model will not be used unless +// it is deployed. +// +// This method is a long-running +// operation (at https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). +// The returned Operation type has the following method-specific fields: +// +// metadata: DeployConversationModelOperationMetadata +// +// response: An Empty +// message (at https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) +func (c *conversationModelsRESTClient) DeployConversationModel(ctx context.Context, req *dialogflowpb.DeployConversationModelRequest, opts ...gax.CallOption) (*DeployConversationModelOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:deploy", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &DeployConversationModelOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UndeployConversationModel undeploys a model. If the model is not deployed this method has no effect. +// If the model is currently being used: +// +// For article suggestion, article suggestion will fallback to the default +// model if model is undeployed. +// +// This method is a long-running +// operation (at https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). +// The returned Operation type has the following method-specific fields: +// +// metadata: UndeployConversationModelOperationMetadata +// +// response: An Empty +// message (at https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) +func (c *conversationModelsRESTClient) UndeployConversationModel(ctx context.Context, req *dialogflowpb.UndeployConversationModelRequest, opts ...gax.CallOption) (*UndeployConversationModelOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:undeploy", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &UndeployConversationModelOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetConversationModelEvaluation gets an evaluation of conversation model. +func (c *conversationModelsRESTClient) GetConversationModelEvaluation(ctx context.Context, req *dialogflowpb.GetConversationModelEvaluationRequest, opts ...gax.CallOption) (*dialogflowpb.ConversationModelEvaluation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetConversationModelEvaluation[0:len((*c.CallOptions).GetConversationModelEvaluation):len((*c.CallOptions).GetConversationModelEvaluation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dialogflowpb.ConversationModelEvaluation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListConversationModelEvaluations lists evaluations of a conversation model. +func (c *conversationModelsRESTClient) ListConversationModelEvaluations(ctx context.Context, req *dialogflowpb.ListConversationModelEvaluationsRequest, opts ...gax.CallOption) *ConversationModelEvaluationIterator { + it := &ConversationModelEvaluationIterator{} + req = proto.Clone(req).(*dialogflowpb.ListConversationModelEvaluationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*dialogflowpb.ConversationModelEvaluation, string, error) { + resp := &dialogflowpb.ListConversationModelEvaluationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/evaluations", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetConversationModelEvaluations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CreateConversationModelEvaluation creates evaluation of a conversation model. +func (c *conversationModelsRESTClient) CreateConversationModelEvaluation(ctx context.Context, req *dialogflowpb.CreateConversationModelEvaluationRequest, opts ...gax.CallOption) (*CreateConversationModelEvaluationOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/evaluations", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &CreateConversationModelEvaluationOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetLocation gets information about a location. +func (c *conversationModelsRESTClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *conversationModelsRESTClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *conversationModelsRESTClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *conversationModelsRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *conversationModelsRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CreateConversationModelOperation manages a long-running operation from CreateConversationModel. +type CreateConversationModelOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateConversationModelOperation returns a new CreateConversationModelOperation from a given name. +// The name must be that of a previously created CreateConversationModelOperation, possibly from a different process. +func (c *conversationModelsGRPCClient) CreateConversationModelOperation(name string) *CreateConversationModelOperation { + return &CreateConversationModelOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateConversationModelOperation returns a new CreateConversationModelOperation from a given name. +// The name must be that of a previously created CreateConversationModelOperation, possibly from a different process. +func (c *conversationModelsRESTClient) CreateConversationModelOperation(name string) *CreateConversationModelOperation { + override := fmt.Sprintf("/v2/%s", name) + return &CreateConversationModelOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CreateConversationModelOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*dialogflowpb.ConversationModel, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp dialogflowpb.ConversationModel + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *CreateConversationModelOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*dialogflowpb.ConversationModel, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp dialogflowpb.ConversationModel + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *CreateConversationModelOperation) Metadata() (*dialogflowpb.CreateConversationModelOperationMetadata, error) { + var meta dialogflowpb.CreateConversationModelOperationMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *CreateConversationModelOperation) Done() bool { + return op.lro.Done() +} + +// 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 *CreateConversationModelOperation) Name() string { + return op.lro.Name() +} + +// CreateConversationModelEvaluationOperation manages a long-running operation from CreateConversationModelEvaluation. +type CreateConversationModelEvaluationOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateConversationModelEvaluationOperation returns a new CreateConversationModelEvaluationOperation from a given name. +// The name must be that of a previously created CreateConversationModelEvaluationOperation, possibly from a different process. +func (c *conversationModelsGRPCClient) CreateConversationModelEvaluationOperation(name string) *CreateConversationModelEvaluationOperation { + return &CreateConversationModelEvaluationOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateConversationModelEvaluationOperation returns a new CreateConversationModelEvaluationOperation from a given name. +// The name must be that of a previously created CreateConversationModelEvaluationOperation, possibly from a different process. +func (c *conversationModelsRESTClient) CreateConversationModelEvaluationOperation(name string) *CreateConversationModelEvaluationOperation { + override := fmt.Sprintf("/v2/%s", name) + return &CreateConversationModelEvaluationOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CreateConversationModelEvaluationOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*dialogflowpb.ConversationModelEvaluation, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp dialogflowpb.ConversationModelEvaluation + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *CreateConversationModelEvaluationOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*dialogflowpb.ConversationModelEvaluation, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp dialogflowpb.ConversationModelEvaluation + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *CreateConversationModelEvaluationOperation) Metadata() (*dialogflowpb.CreateConversationModelEvaluationOperationMetadata, error) { + var meta dialogflowpb.CreateConversationModelEvaluationOperationMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { return nil, err } return &meta, nil @@ -1022,7 +2244,8 @@ func (op *CreateConversationModelEvaluationOperation) Name() string { // DeleteConversationModelOperation manages a long-running operation from DeleteConversationModel. type DeleteConversationModelOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteConversationModelOperation returns a new DeleteConversationModelOperation from a given name. @@ -1033,10 +2256,21 @@ func (c *conversationModelsGRPCClient) DeleteConversationModelOperation(name str } } +// DeleteConversationModelOperation returns a new DeleteConversationModelOperation from a given name. +// The name must be that of a previously created DeleteConversationModelOperation, possibly from a different process. +func (c *conversationModelsRESTClient) DeleteConversationModelOperation(name string) *DeleteConversationModelOperation { + override := fmt.Sprintf("/v2/%s", name) + return &DeleteConversationModelOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteConversationModelOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -1050,6 +2284,7 @@ func (op *DeleteConversationModelOperation) Wait(ctx context.Context, opts ...ga // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteConversationModelOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -1080,7 +2315,8 @@ func (op *DeleteConversationModelOperation) Name() string { // DeployConversationModelOperation manages a long-running operation from DeployConversationModel. type DeployConversationModelOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeployConversationModelOperation returns a new DeployConversationModelOperation from a given name. @@ -1091,10 +2327,21 @@ func (c *conversationModelsGRPCClient) DeployConversationModelOperation(name str } } +// DeployConversationModelOperation returns a new DeployConversationModelOperation from a given name. +// The name must be that of a previously created DeployConversationModelOperation, possibly from a different process. +func (c *conversationModelsRESTClient) DeployConversationModelOperation(name string) *DeployConversationModelOperation { + override := fmt.Sprintf("/v2/%s", name) + return &DeployConversationModelOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeployConversationModelOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -1108,6 +2355,7 @@ func (op *DeployConversationModelOperation) Wait(ctx context.Context, opts ...ga // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeployConversationModelOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -1138,7 +2386,8 @@ func (op *DeployConversationModelOperation) Name() string { // UndeployConversationModelOperation manages a long-running operation from UndeployConversationModel. type UndeployConversationModelOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UndeployConversationModelOperation returns a new UndeployConversationModelOperation from a given name. @@ -1149,10 +2398,21 @@ func (c *conversationModelsGRPCClient) UndeployConversationModelOperation(name s } } +// UndeployConversationModelOperation returns a new UndeployConversationModelOperation from a given name. +// The name must be that of a previously created UndeployConversationModelOperation, possibly from a different process. +func (c *conversationModelsRESTClient) UndeployConversationModelOperation(name string) *UndeployConversationModelOperation { + override := fmt.Sprintf("/v2/%s", name) + return &UndeployConversationModelOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UndeployConversationModelOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -1166,6 +2426,7 @@ func (op *UndeployConversationModelOperation) Wait(ctx context.Context, opts ... // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UndeployConversationModelOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } diff --git a/dialogflow/apiv2/conversation_models_client_example_test.go b/dialogflow/apiv2/conversation_models_client_example_test.go index ca8d7096c392..672a4c99e1c6 100644 --- a/dialogflow/apiv2/conversation_models_client_example_test.go +++ b/dialogflow/apiv2/conversation_models_client_example_test.go @@ -43,6 +43,23 @@ func ExampleNewConversationModelsClient() { _ = c } +func ExampleNewConversationModelsRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := dialogflow.NewConversationModelsRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleConversationModelsClient_CreateConversationModel() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/dialogflow/apiv2/conversation_profiles_client.go b/dialogflow/apiv2/conversation_profiles_client.go index f957c146ff76..e5f7d488b286 100644 --- a/dialogflow/apiv2/conversation_profiles_client.go +++ b/dialogflow/apiv2/conversation_profiles_client.go @@ -17,9 +17,12 @@ package dialogflow import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,15 +30,18 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -156,6 +162,86 @@ func defaultConversationProfilesCallOptions() *ConversationProfilesCallOptions { } } +func defaultConversationProfilesRESTCallOptions() *ConversationProfilesCallOptions { + return &ConversationProfilesCallOptions{ + ListConversationProfiles: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetConversationProfile: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateConversationProfile: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UpdateConversationProfile: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeleteConversationProfile: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + SetSuggestionFeatureConfig: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ClearSuggestionFeatureConfig: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + CancelOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalConversationProfilesClient is an interface that defines the methods available from Dialogflow API. type internalConversationProfilesClient interface { Close() error @@ -425,6 +511,89 @@ func (c *conversationProfilesGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type conversationProfilesRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing ConversationProfilesClient + CallOptions **ConversationProfilesCallOptions +} + +// NewConversationProfilesRESTClient creates a new conversation profiles rest client. +// +// Service for managing ConversationProfiles. +func NewConversationProfilesRESTClient(ctx context.Context, opts ...option.ClientOption) (*ConversationProfilesClient, error) { + clientOpts := append(defaultConversationProfilesRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultConversationProfilesRESTCallOptions() + c := &conversationProfilesRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &ConversationProfilesClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultConversationProfilesRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://dialogflow.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://dialogflow.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://dialogflow.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *conversationProfilesRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *conversationProfilesRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *conversationProfilesRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *conversationProfilesGRPCClient) ListConversationProfiles(ctx context.Context, req *dialogflowpb.ListConversationProfilesRequest, opts ...gax.CallOption) *ConversationProfileIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -739,85 +908,939 @@ func (c *conversationProfilesGRPCClient) ListOperations(ctx context.Context, req return it } -// ClearSuggestionFeatureConfigOperation manages a long-running operation from ClearSuggestionFeatureConfig. -type ClearSuggestionFeatureConfigOperation struct { - lro *longrunning.Operation -} +// ListConversationProfiles returns the list of all conversation profiles in the specified project. +func (c *conversationProfilesRESTClient) ListConversationProfiles(ctx context.Context, req *dialogflowpb.ListConversationProfilesRequest, opts ...gax.CallOption) *ConversationProfileIterator { + it := &ConversationProfileIterator{} + req = proto.Clone(req).(*dialogflowpb.ListConversationProfilesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*dialogflowpb.ConversationProfile, string, error) { + resp := &dialogflowpb.ListConversationProfilesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/conversationProfiles", req.GetParent()) -// ClearSuggestionFeatureConfigOperation returns a new ClearSuggestionFeatureConfigOperation from a given name. -// The name must be that of a previously created ClearSuggestionFeatureConfigOperation, possibly from a different process. -func (c *conversationProfilesGRPCClient) ClearSuggestionFeatureConfigOperation(name string) *ClearSuggestionFeatureConfigOperation { - return &ClearSuggestionFeatureConfigOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetConversationProfiles(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it } -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *ClearSuggestionFeatureConfigOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*dialogflowpb.ConversationProfile, error) { - var resp dialogflowpb.ConversationProfile - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { +// GetConversationProfile retrieves the specified conversation profile. +func (c *conversationProfilesRESTClient) GetConversationProfile(ctx context.Context, req *dialogflowpb.GetConversationProfileRequest, opts ...gax.CallOption) (*dialogflowpb.ConversationProfile, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - return &resp, nil + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetConversationProfile[0:len((*c.CallOptions).GetConversationProfile):len((*c.CallOptions).GetConversationProfile)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dialogflowpb.ConversationProfile{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil } -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// CreateConversationProfile creates a conversation profile in the specified project. // -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *ClearSuggestionFeatureConfigOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*dialogflowpb.ConversationProfile, error) { - var resp dialogflowpb.ConversationProfile - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { +// ConversationProfile.CreateTime and ConversationProfile.UpdateTime +// aren’t populated in the response. You can retrieve them via +// GetConversationProfile API. +func (c *conversationProfilesRESTClient) CreateConversationProfile(ctx context.Context, req *dialogflowpb.CreateConversationProfileRequest, opts ...gax.CallOption) (*dialogflowpb.ConversationProfile, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetConversationProfile() + jsonReq, err := m.Marshal(body) + if err != nil { return nil, err } - if !op.Done() { - return nil, nil - } - return &resp, nil -} -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *ClearSuggestionFeatureConfigOperation) Metadata() (*dialogflowpb.ClearSuggestionFeatureConfigOperationMetadata, error) { - var meta dialogflowpb.ClearSuggestionFeatureConfigOperationMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - return &meta, nil -} + baseUrl.Path += fmt.Sprintf("/v2/%v/conversationProfiles", req.GetParent()) -// Done reports whether the long-running operation has completed. -func (op *ClearSuggestionFeatureConfigOperation) Done() bool { - return op.lro.Done() -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") -// 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 *ClearSuggestionFeatureConfigOperation) Name() string { - return op.lro.Name() -} + baseUrl.RawQuery = params.Encode() -// SetSuggestionFeatureConfigOperation manages a long-running operation from SetSuggestionFeatureConfig. -type SetSuggestionFeatureConfigOperation struct { - lro *longrunning.Operation -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) -// SetSuggestionFeatureConfigOperation returns a new SetSuggestionFeatureConfigOperation from a given name. -// The name must be that of a previously created SetSuggestionFeatureConfigOperation, possibly from a different process. -func (c *conversationProfilesGRPCClient) SetSuggestionFeatureConfigOperation(name string) *SetSuggestionFeatureConfigOperation { - return &SetSuggestionFeatureConfigOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateConversationProfile[0:len((*c.CallOptions).CreateConversationProfile):len((*c.CallOptions).CreateConversationProfile)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dialogflowpb.ConversationProfile{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateConversationProfile updates the specified conversation profile. +// +// ConversationProfile.CreateTime and ConversationProfile.UpdateTime +// aren’t populated in the response. You can retrieve them via +// GetConversationProfile API. +func (c *conversationProfilesRESTClient) UpdateConversationProfile(ctx context.Context, req *dialogflowpb.UpdateConversationProfileRequest, opts ...gax.CallOption) (*dialogflowpb.ConversationProfile, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetConversationProfile() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetConversationProfile().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "conversation_profile.name", url.QueryEscape(req.GetConversationProfile().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateConversationProfile[0:len((*c.CallOptions).UpdateConversationProfile):len((*c.CallOptions).UpdateConversationProfile)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dialogflowpb.ConversationProfile{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteConversationProfile deletes the specified conversation profile. +func (c *conversationProfilesRESTClient) DeleteConversationProfile(ctx context.Context, req *dialogflowpb.DeleteConversationProfileRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// SetSuggestionFeatureConfig adds or updates a suggestion feature in a conversation profile. +// If the conversation profile contains the type of suggestion feature for +// the participant role, it will update it. Otherwise it will insert the +// suggestion feature. +// +// This method is a long-running +// operation (at https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). +// The returned Operation type has the following method-specific fields: +// +// metadata: SetSuggestionFeatureConfigOperationMetadata +// +// response: ConversationProfile +// +// If a long running operation to add or update suggestion feature +// config for the same conversation profile, participant role and suggestion +// feature type exists, please cancel the existing long running operation +// before sending such request, otherwise the request will be rejected. +func (c *conversationProfilesRESTClient) SetSuggestionFeatureConfig(ctx context.Context, req *dialogflowpb.SetSuggestionFeatureConfigRequest, opts ...gax.CallOption) (*SetSuggestionFeatureConfigOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:setSuggestionFeatureConfig", req.GetConversationProfile()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "conversation_profile", url.QueryEscape(req.GetConversationProfile()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &SetSuggestionFeatureConfigOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ClearSuggestionFeatureConfig clears a suggestion feature from a conversation profile for the given +// participant role. +// +// This method is a long-running +// operation (at https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). +// The returned Operation type has the following method-specific fields: +// +// metadata: ClearSuggestionFeatureConfigOperationMetadata +// +// response: ConversationProfile +func (c *conversationProfilesRESTClient) ClearSuggestionFeatureConfig(ctx context.Context, req *dialogflowpb.ClearSuggestionFeatureConfigRequest, opts ...gax.CallOption) (*ClearSuggestionFeatureConfigOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:clearSuggestionFeatureConfig", req.GetConversationProfile()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "conversation_profile", url.QueryEscape(req.GetConversationProfile()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &ClearSuggestionFeatureConfigOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetLocation gets information about a location. +func (c *conversationProfilesRESTClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *conversationProfilesRESTClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *conversationProfilesRESTClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *conversationProfilesRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *conversationProfilesRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// ClearSuggestionFeatureConfigOperation manages a long-running operation from ClearSuggestionFeatureConfig. +type ClearSuggestionFeatureConfigOperation struct { + lro *longrunning.Operation + pollPath string +} + +// ClearSuggestionFeatureConfigOperation returns a new ClearSuggestionFeatureConfigOperation from a given name. +// The name must be that of a previously created ClearSuggestionFeatureConfigOperation, possibly from a different process. +func (c *conversationProfilesGRPCClient) ClearSuggestionFeatureConfigOperation(name string) *ClearSuggestionFeatureConfigOperation { + return &ClearSuggestionFeatureConfigOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// ClearSuggestionFeatureConfigOperation returns a new ClearSuggestionFeatureConfigOperation from a given name. +// The name must be that of a previously created ClearSuggestionFeatureConfigOperation, possibly from a different process. +func (c *conversationProfilesRESTClient) ClearSuggestionFeatureConfigOperation(name string) *ClearSuggestionFeatureConfigOperation { + override := fmt.Sprintf("/v2/%s", name) + return &ClearSuggestionFeatureConfigOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *ClearSuggestionFeatureConfigOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*dialogflowpb.ConversationProfile, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp dialogflowpb.ConversationProfile + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *ClearSuggestionFeatureConfigOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*dialogflowpb.ConversationProfile, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp dialogflowpb.ConversationProfile + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *ClearSuggestionFeatureConfigOperation) Metadata() (*dialogflowpb.ClearSuggestionFeatureConfigOperationMetadata, error) { + var meta dialogflowpb.ClearSuggestionFeatureConfigOperationMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *ClearSuggestionFeatureConfigOperation) Done() bool { + return op.lro.Done() +} + +// 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 *ClearSuggestionFeatureConfigOperation) Name() string { + return op.lro.Name() +} + +// SetSuggestionFeatureConfigOperation manages a long-running operation from SetSuggestionFeatureConfig. +type SetSuggestionFeatureConfigOperation struct { + lro *longrunning.Operation + pollPath string +} + +// SetSuggestionFeatureConfigOperation returns a new SetSuggestionFeatureConfigOperation from a given name. +// The name must be that of a previously created SetSuggestionFeatureConfigOperation, possibly from a different process. +func (c *conversationProfilesGRPCClient) SetSuggestionFeatureConfigOperation(name string) *SetSuggestionFeatureConfigOperation { + return &SetSuggestionFeatureConfigOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// SetSuggestionFeatureConfigOperation returns a new SetSuggestionFeatureConfigOperation from a given name. +// The name must be that of a previously created SetSuggestionFeatureConfigOperation, possibly from a different process. +func (c *conversationProfilesRESTClient) SetSuggestionFeatureConfigOperation(name string) *SetSuggestionFeatureConfigOperation { + override := fmt.Sprintf("/v2/%s", name) + return &SetSuggestionFeatureConfigOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, } } @@ -825,6 +1848,7 @@ func (c *conversationProfilesGRPCClient) SetSuggestionFeatureConfigOperation(nam // // See documentation of Poll for error-handling information. func (op *SetSuggestionFeatureConfigOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*dialogflowpb.ConversationProfile, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp dialogflowpb.ConversationProfile if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -842,6 +1866,7 @@ func (op *SetSuggestionFeatureConfigOperation) Wait(ctx context.Context, opts .. // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *SetSuggestionFeatureConfigOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*dialogflowpb.ConversationProfile, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp dialogflowpb.ConversationProfile if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/dialogflow/apiv2/conversation_profiles_client_example_test.go b/dialogflow/apiv2/conversation_profiles_client_example_test.go index 55194c235255..ac0015349ddf 100644 --- a/dialogflow/apiv2/conversation_profiles_client_example_test.go +++ b/dialogflow/apiv2/conversation_profiles_client_example_test.go @@ -43,6 +43,23 @@ func ExampleNewConversationProfilesClient() { _ = c } +func ExampleNewConversationProfilesRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := dialogflow.NewConversationProfilesRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleConversationProfilesClient_ListConversationProfiles() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/dialogflow/apiv2/conversations_client.go b/dialogflow/apiv2/conversations_client.go index ac2e960ec245..f1526a44cd49 100644 --- a/dialogflow/apiv2/conversations_client.go +++ b/dialogflow/apiv2/conversations_client.go @@ -17,23 +17,29 @@ package dialogflow import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" dialogflowpb "cloud.google.com/go/dialogflow/apiv2/dialogflowpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -130,6 +136,66 @@ func defaultConversationsCallOptions() *ConversationsCallOptions { } } +func defaultConversationsRESTCallOptions() *ConversationsCallOptions { + return &ConversationsCallOptions{ + CreateConversation: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListConversations: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetConversation: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CompleteConversation: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListMessages: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + CancelOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalConversationsClient is an interface that defines the methods available from Dialogflow API. type internalConversationsClient interface { Close() error @@ -340,6 +406,74 @@ func (c *conversationsGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type conversationsRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing ConversationsClient + CallOptions **ConversationsCallOptions +} + +// NewConversationsRESTClient creates a new conversations rest client. +// +// Service for managing Conversations. +func NewConversationsRESTClient(ctx context.Context, opts ...option.ClientOption) (*ConversationsClient, error) { + clientOpts := append(defaultConversationsRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultConversationsRESTCallOptions() + c := &conversationsRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &ConversationsClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultConversationsRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://dialogflow.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://dialogflow.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://dialogflow.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *conversationsRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *conversationsRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *conversationsRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *conversationsGRPCClient) CreateConversation(ctx context.Context, req *dialogflowpb.CreateConversationRequest, opts ...gax.CallOption) (*dialogflowpb.Conversation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) @@ -633,6 +767,737 @@ func (c *conversationsGRPCClient) ListOperations(ctx context.Context, req *longr return it } +// CreateConversation creates a new conversation. Conversations are auto-completed after 24 +// hours. +// +// Conversation Lifecycle: +// There are two stages during a conversation: Automated Agent Stage and +// Assist Stage. +// +// For Automated Agent Stage, there will be a dialogflow agent responding to +// user queries. +// +// For Assist Stage, there’s no dialogflow agent responding to user queries. +// But we will provide suggestions which are generated from conversation. +// +// If Conversation.conversation_profile is configured for a dialogflow +// agent, conversation will start from Automated Agent Stage, otherwise, it +// will start from Assist Stage. And during Automated Agent Stage, once an +// Intent with Intent.live_agent_handoff is triggered, conversation +// will transfer to Assist Stage. +func (c *conversationsRESTClient) CreateConversation(ctx context.Context, req *dialogflowpb.CreateConversationRequest, opts ...gax.CallOption) (*dialogflowpb.Conversation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetConversation() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/conversations", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetConversationId() != "" { + params.Add("conversationId", fmt.Sprintf("%v", req.GetConversationId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateConversation[0:len((*c.CallOptions).CreateConversation):len((*c.CallOptions).CreateConversation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dialogflowpb.Conversation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListConversations returns the list of all conversations in the specified project. +func (c *conversationsRESTClient) ListConversations(ctx context.Context, req *dialogflowpb.ListConversationsRequest, opts ...gax.CallOption) *ConversationIterator { + it := &ConversationIterator{} + req = proto.Clone(req).(*dialogflowpb.ListConversationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*dialogflowpb.Conversation, string, error) { + resp := &dialogflowpb.ListConversationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/conversations", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetConversations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetConversation retrieves the specific conversation. +func (c *conversationsRESTClient) GetConversation(ctx context.Context, req *dialogflowpb.GetConversationRequest, opts ...gax.CallOption) (*dialogflowpb.Conversation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetConversation[0:len((*c.CallOptions).GetConversation):len((*c.CallOptions).GetConversation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dialogflowpb.Conversation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CompleteConversation completes the specified conversation. Finished conversations are purged +// from the database after 30 days. +func (c *conversationsRESTClient) CompleteConversation(ctx context.Context, req *dialogflowpb.CompleteConversationRequest, opts ...gax.CallOption) (*dialogflowpb.Conversation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:complete", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CompleteConversation[0:len((*c.CallOptions).CompleteConversation):len((*c.CallOptions).CompleteConversation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dialogflowpb.Conversation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListMessages lists messages that belong to a given conversation. +// messages are ordered by create_time in descending order. To fetch +// updates without duplication, send request with filter +// create_time_epoch_microseconds > [first item's create_time of previous request] and empty page_token. +func (c *conversationsRESTClient) ListMessages(ctx context.Context, req *dialogflowpb.ListMessagesRequest, opts ...gax.CallOption) *MessageIterator { + it := &MessageIterator{} + req = proto.Clone(req).(*dialogflowpb.ListMessagesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*dialogflowpb.Message, string, error) { + resp := &dialogflowpb.ListMessagesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/messages", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetMessages(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetLocation gets information about a location. +func (c *conversationsRESTClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *conversationsRESTClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *conversationsRESTClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *conversationsRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *conversationsRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + // ConversationIterator manages a stream of *dialogflowpb.Conversation. type ConversationIterator struct { items []*dialogflowpb.Conversation diff --git a/dialogflow/apiv2/conversations_client_example_test.go b/dialogflow/apiv2/conversations_client_example_test.go index 38c40a577eb5..c0fdcc531ca1 100644 --- a/dialogflow/apiv2/conversations_client_example_test.go +++ b/dialogflow/apiv2/conversations_client_example_test.go @@ -43,6 +43,23 @@ func ExampleNewConversationsClient() { _ = c } +func ExampleNewConversationsRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := dialogflow.NewConversationsRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleConversationsClient_CreateConversation() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/dialogflow/apiv2/dialogflowpb/agent.pb.go b/dialogflow/apiv2/dialogflowpb/agent.pb.go index 5bf0444268d3..a9334cf0bc3e 100644 --- a/dialogflow/apiv2/dialogflowpb/agent.pb.go +++ b/dialogflow/apiv2/dialogflowpb/agent.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dialogflow/v2/agent.proto package dialogflowpb @@ -810,7 +810,6 @@ type ExportAgentResponse struct { // The exported agent. // // Types that are assignable to Agent: - // // *ExportAgentResponse_AgentUri // *ExportAgentResponse_AgentContent Agent isExportAgentResponse_Agent `protobuf_oneof:"agent"` @@ -900,7 +899,6 @@ type ImportAgentRequest struct { // Required. The agent to import. // // Types that are assignable to Agent: - // // *ImportAgentRequest_AgentUri // *ImportAgentRequest_AgentContent Agent isImportAgentRequest_Agent `protobuf_oneof:"agent"` @@ -1003,7 +1001,6 @@ type RestoreAgentRequest struct { // Required. The agent to restore. // // Types that are assignable to Agent: - // // *RestoreAgentRequest_AgentUri // *RestoreAgentRequest_AgentContent Agent isRestoreAgentRequest_Agent `protobuf_oneof:"agent"` @@ -1776,10 +1773,10 @@ type AgentsClient interface { // operation](https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: An empty [Struct - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) - // - `response`: An [Empty - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) + // - `metadata`: An empty [Struct + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) + // - `response`: An [Empty + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) // // Note: You should always train an agent prior to sending it queries. See the // [training @@ -1791,9 +1788,9 @@ type AgentsClient interface { // operation](https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: An empty [Struct - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) - // - `response`: [ExportAgentResponse][google.cloud.dialogflow.v2.ExportAgentResponse] + // - `metadata`: An empty [Struct + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) + // - `response`: [ExportAgentResponse][google.cloud.dialogflow.v2.ExportAgentResponse] ExportAgent(ctx context.Context, in *ExportAgentRequest, opts ...grpc.CallOption) (*longrunning.Operation, error) // Imports the specified agent from a ZIP file. // @@ -1809,10 +1806,10 @@ type AgentsClient interface { // operation](https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: An empty [Struct - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) - // - `response`: An [Empty - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) + // - `metadata`: An empty [Struct + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) + // - `response`: An [Empty + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) // // The operation only tracks when importing is complete, not when it is done // training. @@ -1834,10 +1831,10 @@ type AgentsClient interface { // operation](https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: An empty [Struct - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) - // - `response`: An [Empty - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) + // - `metadata`: An empty [Struct + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) + // - `response`: An [Empty + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) // // The operation only tracks when restoring is complete, not when it is done // training. @@ -1966,10 +1963,10 @@ type AgentsServer interface { // operation](https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: An empty [Struct - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) - // - `response`: An [Empty - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) + // - `metadata`: An empty [Struct + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) + // - `response`: An [Empty + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) // // Note: You should always train an agent prior to sending it queries. See the // [training @@ -1981,9 +1978,9 @@ type AgentsServer interface { // operation](https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: An empty [Struct - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) - // - `response`: [ExportAgentResponse][google.cloud.dialogflow.v2.ExportAgentResponse] + // - `metadata`: An empty [Struct + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) + // - `response`: [ExportAgentResponse][google.cloud.dialogflow.v2.ExportAgentResponse] ExportAgent(context.Context, *ExportAgentRequest) (*longrunning.Operation, error) // Imports the specified agent from a ZIP file. // @@ -1999,10 +1996,10 @@ type AgentsServer interface { // operation](https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: An empty [Struct - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) - // - `response`: An [Empty - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) + // - `metadata`: An empty [Struct + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) + // - `response`: An [Empty + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) // // The operation only tracks when importing is complete, not when it is done // training. @@ -2024,10 +2021,10 @@ type AgentsServer interface { // operation](https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: An empty [Struct - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) - // - `response`: An [Empty - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) + // - `metadata`: An empty [Struct + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) + // - `response`: An [Empty + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) // // The operation only tracks when restoring is complete, not when it is done // training. diff --git a/dialogflow/apiv2/dialogflowpb/answer_record.pb.go b/dialogflow/apiv2/dialogflowpb/answer_record.pb.go index eabadf167889..b8502029fa88 100644 --- a/dialogflow/apiv2/dialogflowpb/answer_record.pb.go +++ b/dialogflow/apiv2/dialogflowpb/answer_record.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dialogflow/v2/answer_record.proto package dialogflowpb @@ -300,7 +300,6 @@ type AnswerRecord struct { // The record for this answer. // // Types that are assignable to Record: - // // *AnswerRecord_AgentAssistantRecord Record isAnswerRecord_Record `protobuf_oneof:"record"` } @@ -600,7 +599,6 @@ type AnswerFeedback struct { // Normally, detail feedback is provided when answer is not fully correct. // // Types that are assignable to DetailFeedback: - // // *AnswerFeedback_AgentAssistantDetailFeedback DetailFeedback isAnswerFeedback_DetailFeedback `protobuf_oneof:"detail_feedback"` // Indicates whether the answer/item was clicked by the human agent @@ -717,20 +715,20 @@ type AgentAssistantFeedback struct { // // For example: // - // - Query: "Can I change my mailing address?" - // - Suggested document says: "Items must be returned/exchanged within 60 - // days of the purchase date." - // - [answer_relevance][google.cloud.dialogflow.v2.AgentAssistantFeedback.answer_relevance]: [AnswerRelevance.IRRELEVANT][google.cloud.dialogflow.v2.AgentAssistantFeedback.AnswerRelevance.IRRELEVANT] + // * Query: "Can I change my mailing address?" + // * Suggested document says: "Items must be returned/exchanged within 60 + // days of the purchase date." + // * [answer_relevance][google.cloud.dialogflow.v2.AgentAssistantFeedback.answer_relevance]: [AnswerRelevance.IRRELEVANT][google.cloud.dialogflow.v2.AgentAssistantFeedback.AnswerRelevance.IRRELEVANT] AnswerRelevance AgentAssistantFeedback_AnswerRelevance `protobuf:"varint,1,opt,name=answer_relevance,json=answerRelevance,proto3,enum=google.cloud.dialogflow.v2.AgentAssistantFeedback_AnswerRelevance" json:"answer_relevance,omitempty"` // Optional. Whether or not the information in the document is correct. // // For example: // - // - Query: "Can I return the package in 2 days once received?" - // - Suggested document says: "Items must be returned/exchanged within 60 - // days of the purchase date." - // - Ground truth: "No return or exchange is allowed." - // - [document_correctness]: INCORRECT + // * Query: "Can I return the package in 2 days once received?" + // * Suggested document says: "Items must be returned/exchanged within 60 + // days of the purchase date." + // * Ground truth: "No return or exchange is allowed." + // * [document_correctness]: INCORRECT DocumentCorrectness AgentAssistantFeedback_DocumentCorrectness `protobuf:"varint,2,opt,name=document_correctness,json=documentCorrectness,proto3,enum=google.cloud.dialogflow.v2.AgentAssistantFeedback_DocumentCorrectness" json:"document_correctness,omitempty"` // Optional. Whether or not the suggested document is efficient. For example, // if the document is poorly written, hard to understand, hard to use or @@ -801,7 +799,6 @@ type AgentAssistantRecord struct { // Output only. The agent assist answer. // // Types that are assignable to Answer: - // // *AgentAssistantRecord_ArticleSuggestionAnswer // *AgentAssistantRecord_FaqAnswer Answer isAgentAssistantRecord_Answer `protobuf_oneof:"answer"` diff --git a/dialogflow/apiv2/dialogflowpb/audio_config.pb.go b/dialogflow/apiv2/dialogflowpb/audio_config.pb.go index 3c188cbd6489..88a4b9320fa0 100644 --- a/dialogflow/apiv2/dialogflowpb/audio_config.pb.go +++ b/dialogflow/apiv2/dialogflowpb/audio_config.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dialogflow/v2/audio_config.proto package dialogflowpb @@ -159,18 +159,18 @@ const ( SpeechModelVariant_USE_STANDARD SpeechModelVariant = 2 // Use an enhanced model variant: // - // - If an enhanced variant does not exist for the given - // [model][google.cloud.dialogflow.v2.InputAudioConfig.model] and request language, Dialogflow falls - // back to the standard variant. + // * If an enhanced variant does not exist for the given + // [model][google.cloud.dialogflow.v2.InputAudioConfig.model] and request language, Dialogflow falls + // back to the standard variant. // - // The [Cloud Speech - // documentation](https://cloud.google.com/speech-to-text/docs/enhanced-models) - // describes which models have enhanced variants. + // The [Cloud Speech + // documentation](https://cloud.google.com/speech-to-text/docs/enhanced-models) + // describes which models have enhanced variants. // - // - If the API caller isn't eligible for enhanced models, Dialogflow returns - // an error. Please see the [Dialogflow - // docs](https://cloud.google.com/dialogflow/docs/data-logging) - // for how to make your project eligible. + // * If the API caller isn't eligible for enhanced models, Dialogflow returns + // an error. Please see the [Dialogflow + // docs](https://cloud.google.com/dialogflow/docs/data-logging) + // for how to make your project eligible. SpeechModelVariant_USE_ENHANCED SpeechModelVariant = 3 ) @@ -467,10 +467,10 @@ type SpeechContext struct { // // This list can be used to: // - // - improve accuracy for words and phrases you expect the user to say, - // e.g. typical commands for your Dialogflow agent - // - add additional words to the speech recognizer vocabulary - // - ... + // * improve accuracy for words and phrases you expect the user to say, + // e.g. typical commands for your Dialogflow agent + // * add additional words to the speech recognizer vocabulary + // * ... // // See the [Cloud Speech // documentation](https://cloud.google.com/speech-to-text/quotas) for usage @@ -478,10 +478,10 @@ type SpeechContext struct { Phrases []string `protobuf:"bytes,1,rep,name=phrases,proto3" json:"phrases,omitempty"` // Optional. Boost for this context compared to other contexts: // - // - If the boost is positive, Dialogflow will increase the probability that - // the phrases in this context are recognized over similar sounding phrases. - // - If the boost is unspecified or non-positive, Dialogflow will not apply - // any boost. + // * If the boost is positive, Dialogflow will increase the probability that + // the phrases in this context are recognized over similar sounding phrases. + // * If the boost is unspecified or non-positive, Dialogflow will not apply + // any boost. // // Dialogflow recommends that you use boosts in the range (0, 20] and that you // find a value that fits your use case with binary search. diff --git a/dialogflow/apiv2/dialogflowpb/context.pb.go b/dialogflow/apiv2/dialogflowpb/context.pb.go index 261dacf70f26..ed0850c63628 100644 --- a/dialogflow/apiv2/dialogflowpb/context.pb.go +++ b/dialogflow/apiv2/dialogflowpb/context.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dialogflow/v2/context.proto package dialogflowpb @@ -95,14 +95,13 @@ type Context struct { // - MapKey type: string // - MapKey value: parameter name // - MapValue type: - // - If parameter's entity type is a composite entity: map - // - Else: depending on parameter value type, could be one of string, - // number, boolean, null, list or map - // + // - If parameter's entity type is a composite entity: map + // - Else: depending on parameter value type, could be one of string, + // number, boolean, null, list or map // - MapValue value: - // - If parameter's entity type is a composite entity: - // map from composite entity property names to property values - // - Else: parameter value + // - If parameter's entity type is a composite entity: + // map from composite entity property names to property values + // - Else: parameter value Parameters *structpb.Struct `protobuf:"bytes,3,opt,name=parameters,proto3" json:"parameters,omitempty"` } diff --git a/dialogflow/apiv2/dialogflowpb/conversation.pb.go b/dialogflow/apiv2/dialogflowpb/conversation.pb.go index 3176dad4393c..63219964040c 100644 --- a/dialogflow/apiv2/dialogflowpb/conversation.pb.go +++ b/dialogflow/apiv2/dialogflowpb/conversation.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dialogflow/v2/conversation.proto package dialogflowpb @@ -371,13 +371,11 @@ type ListConversationsRequest struct { // general, the expression must specify the field name, a comparison operator, // and the value to use for filtering: //

    - // - //
  • The value must be a string, a number, or a boolean.
  • - //
  • The comparison operator must be either `=`,`!=`, `>`, or `<`.
  • - //
  • To filter on multiple expressions, separate the - // expressions with `AND` or `OR` (omitting both implies `AND`).
  • - //
  • For clarity, expressions can be enclosed in parentheses.
  • - // + //
  • The value must be a string, a number, or a boolean.
  • + //
  • The comparison operator must be either `=`,`!=`, `>`, or `<`.
  • + //
  • To filter on multiple expressions, separate the + // expressions with `AND` or `OR` (omitting both implies `AND`).
  • + //
  • For clarity, expressions can be enclosed in parentheses.
  • //
// Only `lifecycle_state` can be filtered on in this way. For example, // the following expression only returns `COMPLETED` conversations: diff --git a/dialogflow/apiv2/dialogflowpb/conversation_dataset.pb.go b/dialogflow/apiv2/dialogflowpb/conversation_dataset.pb.go index 0406a0223ae5..b54ed527464c 100644 --- a/dialogflow/apiv2/dialogflowpb/conversation_dataset.pb.go +++ b/dialogflow/apiv2/dialogflowpb/conversation_dataset.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dialogflow/v2/conversation_dataset.proto package dialogflowpb @@ -104,7 +104,6 @@ type InputConfig struct { // Required. Where the data is from. // // Types that are assignable to Source: - // // *InputConfig_GcsSource Source isInputConfig_Source `protobuf_oneof:"source"` } @@ -1414,9 +1413,9 @@ type ConversationDatasetsClient interface { // operation](https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: [DeleteConversationDatasetOperationMetadata][google.cloud.dialogflow.v2.DeleteConversationDatasetOperationMetadata] - // - `response`: An [Empty - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) + // - `metadata`: [DeleteConversationDatasetOperationMetadata][google.cloud.dialogflow.v2.DeleteConversationDatasetOperationMetadata] + // - `response`: An [Empty + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) DeleteConversationDataset(ctx context.Context, in *DeleteConversationDatasetRequest, opts ...grpc.CallOption) (*longrunning.Operation, error) // Import data into the specified conversation dataset. Note that it // is not allowed to import data to a conversation dataset that @@ -1506,9 +1505,9 @@ type ConversationDatasetsServer interface { // operation](https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: [DeleteConversationDatasetOperationMetadata][google.cloud.dialogflow.v2.DeleteConversationDatasetOperationMetadata] - // - `response`: An [Empty - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) + // - `metadata`: [DeleteConversationDatasetOperationMetadata][google.cloud.dialogflow.v2.DeleteConversationDatasetOperationMetadata] + // - `response`: An [Empty + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) DeleteConversationDataset(context.Context, *DeleteConversationDatasetRequest) (*longrunning.Operation, error) // Import data into the specified conversation dataset. Note that it // is not allowed to import data to a conversation dataset that diff --git a/dialogflow/apiv2/dialogflowpb/conversation_event.pb.go b/dialogflow/apiv2/dialogflowpb/conversation_event.pb.go index 1630e5399de2..9ae72c91ad66 100644 --- a/dialogflow/apiv2/dialogflowpb/conversation_event.pb.go +++ b/dialogflow/apiv2/dialogflowpb/conversation_event.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dialogflow/v2/conversation_event.proto package dialogflowpb @@ -134,7 +134,6 @@ type ConversationEvent struct { // Payload of conversation event. // // Types that are assignable to Payload: - // // *ConversationEvent_NewMessagePayload Payload isConversationEvent_Payload `protobuf_oneof:"payload"` } diff --git a/dialogflow/apiv2/dialogflowpb/conversation_model.pb.go b/dialogflow/apiv2/dialogflowpb/conversation_model.pb.go index bb44c1b58faf..1c88d43c933f 100644 --- a/dialogflow/apiv2/dialogflowpb/conversation_model.pb.go +++ b/dialogflow/apiv2/dialogflowpb/conversation_model.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dialogflow/v2/conversation_model.proto package dialogflowpb @@ -339,7 +339,6 @@ type ConversationModel struct { // Must match the metadata type of the dataset used to train the model. // // Types that are assignable to ModelMetadata: - // // *ConversationModel_ArticleSuggestionModelMetadata // *ConversationModel_SmartReplyModelMetadata ModelMetadata isConversationModel_ModelMetadata `protobuf_oneof:"model_metadata"` @@ -477,7 +476,6 @@ type ConversationModelEvaluation struct { // Metrics details. // // Types that are assignable to Metrics: - // // *ConversationModelEvaluation_SmartReplyMetrics Metrics isConversationModelEvaluation_Metrics `protobuf_oneof:"metrics"` } @@ -578,7 +576,6 @@ type EvaluationConfig struct { // Specific configurations for different models in order to do evaluation. // // Types that are assignable to ModelSpecificConfig: - // // *EvaluationConfig_SmartReplyConfig_ // *EvaluationConfig_SmartComposeConfig_ ModelSpecificConfig isEvaluationConfig_ModelSpecificConfig `protobuf_oneof:"model_specific_config"` @@ -3090,9 +3087,9 @@ type ConversationModelsClient interface { // operation](https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: [DeleteConversationModelOperationMetadata][google.cloud.dialogflow.v2.DeleteConversationModelOperationMetadata] - // - `response`: An [Empty - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) + // - `metadata`: [DeleteConversationModelOperationMetadata][google.cloud.dialogflow.v2.DeleteConversationModelOperationMetadata] + // - `response`: An [Empty + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) DeleteConversationModel(ctx context.Context, in *DeleteConversationModelRequest, opts ...grpc.CallOption) (*longrunning.Operation, error) // Deploys a model. If a model is already deployed, deploying it // has no effect. A model can only serve prediction requests after it gets @@ -3103,9 +3100,9 @@ type ConversationModelsClient interface { // operation](https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: [DeployConversationModelOperationMetadata][google.cloud.dialogflow.v2.DeployConversationModelOperationMetadata] - // - `response`: An [Empty - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) + // - `metadata`: [DeployConversationModelOperationMetadata][google.cloud.dialogflow.v2.DeployConversationModelOperationMetadata] + // - `response`: An [Empty + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) DeployConversationModel(ctx context.Context, in *DeployConversationModelRequest, opts ...grpc.CallOption) (*longrunning.Operation, error) // Undeploys a model. If the model is not deployed this method has no effect. // If the model is currently being used: @@ -3116,9 +3113,9 @@ type ConversationModelsClient interface { // operation](https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: [UndeployConversationModelOperationMetadata][google.cloud.dialogflow.v2.UndeployConversationModelOperationMetadata] - // - `response`: An [Empty - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) + // - `metadata`: [UndeployConversationModelOperationMetadata][google.cloud.dialogflow.v2.UndeployConversationModelOperationMetadata] + // - `response`: An [Empty + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) UndeployConversationModel(ctx context.Context, in *UndeployConversationModelRequest, opts ...grpc.CallOption) (*longrunning.Operation, error) // Gets an evaluation of conversation model. GetConversationModelEvaluation(ctx context.Context, in *GetConversationModelEvaluationRequest, opts ...grpc.CallOption) (*ConversationModelEvaluation, error) @@ -3238,9 +3235,9 @@ type ConversationModelsServer interface { // operation](https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: [DeleteConversationModelOperationMetadata][google.cloud.dialogflow.v2.DeleteConversationModelOperationMetadata] - // - `response`: An [Empty - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) + // - `metadata`: [DeleteConversationModelOperationMetadata][google.cloud.dialogflow.v2.DeleteConversationModelOperationMetadata] + // - `response`: An [Empty + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) DeleteConversationModel(context.Context, *DeleteConversationModelRequest) (*longrunning.Operation, error) // Deploys a model. If a model is already deployed, deploying it // has no effect. A model can only serve prediction requests after it gets @@ -3251,9 +3248,9 @@ type ConversationModelsServer interface { // operation](https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: [DeployConversationModelOperationMetadata][google.cloud.dialogflow.v2.DeployConversationModelOperationMetadata] - // - `response`: An [Empty - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) + // - `metadata`: [DeployConversationModelOperationMetadata][google.cloud.dialogflow.v2.DeployConversationModelOperationMetadata] + // - `response`: An [Empty + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) DeployConversationModel(context.Context, *DeployConversationModelRequest) (*longrunning.Operation, error) // Undeploys a model. If the model is not deployed this method has no effect. // If the model is currently being used: @@ -3264,9 +3261,9 @@ type ConversationModelsServer interface { // operation](https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: [UndeployConversationModelOperationMetadata][google.cloud.dialogflow.v2.UndeployConversationModelOperationMetadata] - // - `response`: An [Empty - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) + // - `metadata`: [UndeployConversationModelOperationMetadata][google.cloud.dialogflow.v2.UndeployConversationModelOperationMetadata] + // - `response`: An [Empty + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) UndeployConversationModel(context.Context, *UndeployConversationModelRequest) (*longrunning.Operation, error) // Gets an evaluation of conversation model. GetConversationModelEvaluation(context.Context, *GetConversationModelEvaluationRequest) (*ConversationModelEvaluation, error) diff --git a/dialogflow/apiv2/dialogflowpb/conversation_profile.pb.go b/dialogflow/apiv2/dialogflowpb/conversation_profile.pb.go index 179f675ee0ef..450b46a89a8f 100644 --- a/dialogflow/apiv2/dialogflowpb/conversation_profile.pb.go +++ b/dialogflow/apiv2/dialogflowpb/conversation_profile.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dialogflow/v2/conversation_profile.proto package dialogflowpb @@ -842,7 +842,6 @@ type HumanAgentHandoffConfig struct { // Required. Specifies which agent service to connect for human agent handoff. // // Types that are assignable to AgentService: - // // *HumanAgentHandoffConfig_LivePersonConfig_ // *HumanAgentHandoffConfig_SalesforceLiveAgentConfig_ AgentService isHumanAgentHandoffConfig_AgentService `protobuf_oneof:"agent_service"` @@ -1630,7 +1629,6 @@ type HumanAgentAssistantConfig_SuggestionQueryConfig struct { // Source of query. // // Types that are assignable to QuerySource: - // // *HumanAgentAssistantConfig_SuggestionQueryConfig_KnowledgeBaseQuerySource_ // *HumanAgentAssistantConfig_SuggestionQueryConfig_DocumentQuerySource_ // *HumanAgentAssistantConfig_SuggestionQueryConfig_DialogflowQuerySource_ diff --git a/dialogflow/apiv2/dialogflowpb/document.pb.go b/dialogflow/apiv2/dialogflowpb/document.pb.go index 4b232d77e4ff..f84a593f283b 100644 --- a/dialogflow/apiv2/dialogflowpb/document.pb.go +++ b/dialogflow/apiv2/dialogflowpb/document.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dialogflow/v2/document.proto package dialogflowpb @@ -262,7 +262,6 @@ type Document struct { // Required. The source of this document. // // Types that are assignable to Source: - // // *Document_ContentUri // *Document_RawContent Source isDocument_Source `protobuf_oneof:"source"` @@ -501,7 +500,7 @@ type ListDocumentsRequest struct { // The filter expression used to filter documents returned by the list method. // The expression has the following syntax: // - // [AND ] ... + // [AND ] ... // // The following fields and operators are supported: // @@ -511,11 +510,11 @@ type ListDocumentsRequest struct { // // Examples: // - // - "knowledge_types:FAQ" matches documents with FAQ knowledge type. - // - "display_name:customer" matches documents whose display name contains - // "customer". - // - "state=ACTIVE" matches documents with ACTIVE state. - // - "knowledge_types:FAQ AND state=ACTIVE" matches all active FAQ documents. + // * "knowledge_types:FAQ" matches documents with FAQ knowledge type. + // * "display_name:customer" matches documents whose display name contains + // "customer". + // * "state=ACTIVE" matches documents with ACTIVE state. + // * "knowledge_types:FAQ AND state=ACTIVE" matches all active FAQ documents. // // For more information about filtering, see // [API Filtering](https://aip.dev/160). @@ -721,7 +720,6 @@ type ImportDocumentsRequest struct { // import more, Dialogflow will return an error. // // Types that are assignable to Source: - // // *ImportDocumentsRequest_GcsSource Source isImportDocumentsRequest_Source `protobuf_oneof:"source"` // Required. Document template used for importing all the documents. @@ -1059,7 +1057,6 @@ type ReloadDocumentRequest struct { // and update document in the knowledge base. // // Types that are assignable to Source: - // // *ReloadDocumentRequest_ContentUri Source isReloadDocumentRequest_Source `protobuf_oneof:"source"` // Optional. Whether to import custom metadata from Google Cloud Storage. @@ -1165,7 +1162,6 @@ type ExportDocumentRequest struct { // Required. The destination for the export. // // Types that are assignable to Destination: - // // *ExportDocumentRequest_GcsDestination Destination isExportDocumentRequest_Destination `protobuf_oneof:"destination"` // When enabled, export the full content of the document including empirical @@ -1316,7 +1312,6 @@ type KnowledgeOperationMetadata struct { // Additional metadata for the Knowledge operation. // // Types that are assignable to OperationMetadata: - // // *KnowledgeOperationMetadata_ExportOperationMetadata OperationMetadata isKnowledgeOperationMetadata_OperationMetadata `protobuf_oneof:"operation_metadata"` } @@ -2262,9 +2257,9 @@ type DocumentsClient interface { // operation](https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: [KnowledgeOperationMetadata][google.cloud.dialogflow.v2.KnowledgeOperationMetadata] - // - `response`: An [Empty - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) + // - `metadata`: [KnowledgeOperationMetadata][google.cloud.dialogflow.v2.KnowledgeOperationMetadata] + // - `response`: An [Empty + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) DeleteDocument(ctx context.Context, in *DeleteDocumentRequest, opts ...grpc.CallOption) (*longrunning.Operation, error) // Updates the specified document. // @@ -2414,9 +2409,9 @@ type DocumentsServer interface { // operation](https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: [KnowledgeOperationMetadata][google.cloud.dialogflow.v2.KnowledgeOperationMetadata] - // - `response`: An [Empty - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) + // - `metadata`: [KnowledgeOperationMetadata][google.cloud.dialogflow.v2.KnowledgeOperationMetadata] + // - `response`: An [Empty + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) DeleteDocument(context.Context, *DeleteDocumentRequest) (*longrunning.Operation, error) // Updates the specified document. // diff --git a/dialogflow/apiv2/dialogflowpb/entity_type.pb.go b/dialogflow/apiv2/dialogflowpb/entity_type.pb.go index 7afe85d264ba..3525607d716c 100644 --- a/dialogflow/apiv2/dialogflowpb/entity_type.pb.go +++ b/dialogflow/apiv2/dialogflowpb/entity_type.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dialogflow/v2/entity_type.proto package dialogflowpb @@ -680,7 +680,6 @@ type BatchUpdateEntityTypesRequest struct { // * If `name` is not specified, we create a new entity type. // // Types that are assignable to EntityTypeBatch: - // // *BatchUpdateEntityTypesRequest_EntityTypeBatchUri // *BatchUpdateEntityTypesRequest_EntityTypeBatchInline EntityTypeBatch isBatchUpdateEntityTypesRequest_EntityTypeBatch `protobuf_oneof:"entity_type_batch"` @@ -1192,7 +1191,7 @@ type EntityType_Entity struct { // // For `KIND_LIST` entity types: // - // - A string that can contain references to other entity types (with or + // * A string that can contain references to other entity types (with or // without aliases). Value string `protobuf:"bytes,1,opt,name=value,proto3" json:"value,omitempty"` // Required. A collection of value synonyms. For example, if the entity type @@ -2024,9 +2023,9 @@ type EntityTypesClient interface { // operation](https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: An empty [Struct - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) - // - `response`: [BatchUpdateEntityTypesResponse][google.cloud.dialogflow.v2.BatchUpdateEntityTypesResponse] + // - `metadata`: An empty [Struct + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) + // - `response`: [BatchUpdateEntityTypesResponse][google.cloud.dialogflow.v2.BatchUpdateEntityTypesResponse] // // Note: You should always train an agent prior to sending it queries. See the // [training @@ -2038,10 +2037,10 @@ type EntityTypesClient interface { // operation](https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: An empty [Struct - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) - // - `response`: An [Empty - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) + // - `metadata`: An empty [Struct + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) + // - `response`: An [Empty + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) // // Note: You should always train an agent prior to sending it queries. See the // [training @@ -2053,10 +2052,10 @@ type EntityTypesClient interface { // operation](https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: An empty [Struct - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) - // - `response`: An [Empty - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) + // - `metadata`: An empty [Struct + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) + // - `response`: An [Empty + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) // // Note: You should always train an agent prior to sending it queries. See the // [training @@ -2070,14 +2069,15 @@ type EntityTypesClient interface { // operation](https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: An empty [Struct - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) - // - `response`: An [Empty - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) + // - `metadata`: An empty [Struct + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) + // - `response`: An [Empty + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) // // Note: You should always train an agent prior to sending it queries. See the // [training // documentation](https://cloud.google.com/dialogflow/es/docs/training). + // BatchUpdateEntities(ctx context.Context, in *BatchUpdateEntitiesRequest, opts ...grpc.CallOption) (*longrunning.Operation, error) // Deletes entities in the specified entity type. // @@ -2085,10 +2085,10 @@ type EntityTypesClient interface { // operation](https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: An empty [Struct - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) - // - `response`: An [Empty - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) + // - `metadata`: An empty [Struct + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) + // - `response`: An [Empty + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) // // Note: You should always train an agent prior to sending it queries. See the // [training @@ -2224,9 +2224,9 @@ type EntityTypesServer interface { // operation](https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: An empty [Struct - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) - // - `response`: [BatchUpdateEntityTypesResponse][google.cloud.dialogflow.v2.BatchUpdateEntityTypesResponse] + // - `metadata`: An empty [Struct + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) + // - `response`: [BatchUpdateEntityTypesResponse][google.cloud.dialogflow.v2.BatchUpdateEntityTypesResponse] // // Note: You should always train an agent prior to sending it queries. See the // [training @@ -2238,10 +2238,10 @@ type EntityTypesServer interface { // operation](https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: An empty [Struct - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) - // - `response`: An [Empty - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) + // - `metadata`: An empty [Struct + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) + // - `response`: An [Empty + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) // // Note: You should always train an agent prior to sending it queries. See the // [training @@ -2253,10 +2253,10 @@ type EntityTypesServer interface { // operation](https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: An empty [Struct - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) - // - `response`: An [Empty - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) + // - `metadata`: An empty [Struct + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) + // - `response`: An [Empty + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) // // Note: You should always train an agent prior to sending it queries. See the // [training @@ -2270,14 +2270,15 @@ type EntityTypesServer interface { // operation](https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: An empty [Struct - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) - // - `response`: An [Empty - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) + // - `metadata`: An empty [Struct + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) + // - `response`: An [Empty + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) // // Note: You should always train an agent prior to sending it queries. See the // [training // documentation](https://cloud.google.com/dialogflow/es/docs/training). + // BatchUpdateEntities(context.Context, *BatchUpdateEntitiesRequest) (*longrunning.Operation, error) // Deletes entities in the specified entity type. // @@ -2285,10 +2286,10 @@ type EntityTypesServer interface { // operation](https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: An empty [Struct - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) - // - `response`: An [Empty - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) + // - `metadata`: An empty [Struct + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) + // - `response`: An [Empty + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) // // Note: You should always train an agent prior to sending it queries. See the // [training diff --git a/dialogflow/apiv2/dialogflowpb/environment.pb.go b/dialogflow/apiv2/dialogflowpb/environment.pb.go index c67eefe59257..80165e9d22cf 100644 --- a/dialogflow/apiv2/dialogflowpb/environment.pb.go +++ b/dialogflow/apiv2/dialogflowpb/environment.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dialogflow/v2/environment.proto package dialogflowpb @@ -130,9 +130,9 @@ type Environment struct { // Output only. The unique identifier of this agent environment. // Supported formats: // - // - `projects//agent/environments/` - // - `projects//locations//agent/environments/` + // - `projects//agent/environments/` + // - `projects//locations//agent/environments/` // // The environment ID for the default environment is `-`. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` @@ -142,9 +142,9 @@ type Environment struct { // Optional. The agent version loaded into this environment. // Supported formats: // - // - `projects//agent/versions/` - // - `projects//locations//agent/versions/` + // - `projects//agent/versions/` + // - `projects//locations//agent/versions/` AgentVersion string `protobuf:"bytes,3,opt,name=agent_version,json=agentVersion,proto3" json:"agent_version,omitempty"` // Output only. The state of this environment. This field is read-only, i.e., it cannot be // set by create and update methods. @@ -463,9 +463,9 @@ type GetEnvironmentRequest struct { // Required. The name of the environment. // Supported formats: // - // - `projects//agent/environments/` - // - `projects//locations//agent/environments/` + // - `projects//agent/environments/` + // - `projects//locations//agent/environments/` // // The environment ID for the default environment is `-`. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` @@ -660,9 +660,9 @@ type DeleteEnvironmentRequest struct { // Required. The name of the environment to delete. // / Format: // - // - `projects//agent/environments/` - // - `projects//locations//agent/environments/` + // - `projects//agent/environments/` + // - `projects//locations//agent/environments/` // // The environment ID for the default environment is `-`. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` @@ -716,9 +716,9 @@ type GetEnvironmentHistoryRequest struct { // Required. The name of the environment to retrieve history for. // Supported formats: // - // - `projects//agent/environments/` - // - `projects//locations//agent/environments/` + // - `projects//agent/environments/` + // - `projects//locations//agent/environments/` // // The environment ID for the default environment is `-`. Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` @@ -791,9 +791,9 @@ type EnvironmentHistory struct { // Output only. The name of the environment this history is for. // Supported formats: // - // - `projects//agent/environments/` - // - `projects//locations//agent/environments/` + // - `projects//agent/environments/` + // - `projects//locations//agent/environments/` // // The environment ID for the default environment is `-`. Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` diff --git a/dialogflow/apiv2/dialogflowpb/fulfillment.pb.go b/dialogflow/apiv2/dialogflowpb/fulfillment.pb.go index ca8ea30c5029..1917f53d37b2 100644 --- a/dialogflow/apiv2/dialogflowpb/fulfillment.pb.go +++ b/dialogflow/apiv2/dialogflowpb/fulfillment.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dialogflow/v2/fulfillment.proto package dialogflowpb @@ -120,7 +120,6 @@ type Fulfillment struct { // Required. The fulfillment configuration. // // Types that are assignable to Fulfillment: - // // *Fulfillment_GenericWebService_ Fulfillment isFulfillment_Fulfillment `protobuf_oneof:"fulfillment"` // Optional. Whether fulfillment is enabled. diff --git a/dialogflow/apiv2/dialogflowpb/gcs.pb.go b/dialogflow/apiv2/dialogflowpb/gcs.pb.go index 63eaaba2aee9..4e4c0111ce15 100644 --- a/dialogflow/apiv2/dialogflowpb/gcs.pb.go +++ b/dialogflow/apiv2/dialogflowpb/gcs.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dialogflow/v2/gcs.proto package dialogflowpb @@ -43,9 +43,7 @@ type GcsSources struct { unknownFields protoimpl.UnknownFields // Required. Google Cloud Storage URIs for the inputs. A URI is of the form: - // - // gs://bucket/object-prefix-or-name - // + // gs://bucket/object-prefix-or-name // Whether a prefix or name is used depends on the use case. Uris []string `protobuf:"bytes,2,rep,name=uris,proto3" json:"uris,omitempty"` } @@ -97,9 +95,7 @@ type GcsDestination struct { // The Google Cloud Storage URIs for the output. A URI is of the // form: - // - // gs://bucket/object-prefix-or-name - // + // gs://bucket/object-prefix-or-name // Whether a prefix or name is used depends on the use case. The requesting // user must have "write-permission" to the bucket. Uri string `protobuf:"bytes,1,opt,name=uri,proto3" json:"uri,omitempty"` diff --git a/dialogflow/apiv2/dialogflowpb/human_agent_assistant_event.pb.go b/dialogflow/apiv2/dialogflowpb/human_agent_assistant_event.pb.go index 10fdf244e045..d95a93a5223f 100644 --- a/dialogflow/apiv2/dialogflowpb/human_agent_assistant_event.pb.go +++ b/dialogflow/apiv2/dialogflowpb/human_agent_assistant_event.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dialogflow/v2/human_agent_assistant_event.proto package dialogflowpb diff --git a/dialogflow/apiv2/dialogflowpb/intent.pb.go b/dialogflow/apiv2/dialogflowpb/intent.pb.go index 06b90a395894..579bb4b0ff8b 100644 --- a/dialogflow/apiv2/dialogflowpb/intent.pb.go +++ b/dialogflow/apiv2/dialogflowpb/intent.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dialogflow/v2/intent.proto package dialogflowpb @@ -552,11 +552,11 @@ type Intent struct { // Optional. The priority of this intent. Higher numbers represent higher // priorities. // - // - If the supplied value is unspecified or 0, the service - // translates the value to 500,000, which corresponds to the - // `Normal` priority in the console. - // - If the supplied value is negative, the intent is ignored - // in runtime detect intent requests. + // - If the supplied value is unspecified or 0, the service + // translates the value to 500,000, which corresponds to the + // `Normal` priority in the console. + // - If the supplied value is negative, the intent is ignored + // in runtime detect intent requests. Priority int32 `protobuf:"varint,3,opt,name=priority,proto3" json:"priority,omitempty"` // Optional. Indicates whether this is a fallback intent. IsFallback bool `protobuf:"varint,4,opt,name=is_fallback,json=isFallback,proto3" json:"is_fallback,omitempty"` @@ -1253,7 +1253,6 @@ type BatchUpdateIntentsRequest struct { // The source of the intent batch. // // Types that are assignable to IntentBatch: - // // *BatchUpdateIntentsRequest_IntentBatchUri // *BatchUpdateIntentsRequest_IntentBatchInline IntentBatch isBatchUpdateIntentsRequest_IntentBatch `protobuf_oneof:"intent_batch"` @@ -1553,8 +1552,8 @@ type Intent_TrainingPhrase struct { // If you want to annotate the training phrase, you must create multiple // parts, where the fields of each part are populated in one of two ways: // - // - `Part.text` is set to a part of the phrase that has no parameters. - // - `Part.text` is set to a part of the phrase that you want to annotate, + // - `Part.text` is set to a part of the phrase that has no parameters. + // - `Part.text` is set to a part of the phrase that you want to annotate, // and the `entity_type`, `alias`, and `user_defined` fields are all // set. Parts []*Intent_TrainingPhrase_Part `protobuf:"bytes,3,rep,name=parts,proto3" json:"parts,omitempty"` @@ -1636,11 +1635,11 @@ type Intent_Parameter struct { DisplayName string `protobuf:"bytes,2,opt,name=display_name,json=displayName,proto3" json:"display_name,omitempty"` // Optional. The definition of the parameter value. It can be: // - // - a constant string, - // - a parameter value defined as `$parameter_name`, - // - an original parameter value defined as `$parameter_name.original`, - // - a parameter value from some context defined as - // `#context_name.parameter_name`. + // - a constant string, + // - a parameter value defined as `$parameter_name`, + // - an original parameter value defined as `$parameter_name.original`, + // - a parameter value from some context defined as + // `#context_name.parameter_name`. Value string `protobuf:"bytes,3,opt,name=value,proto3" json:"value,omitempty"` // Optional. The default value to use when the `value` yields an empty // result. @@ -1763,7 +1762,6 @@ type Intent_Message struct { // Required. The rich response message. // // Types that are assignable to Message: - // // *Intent_Message_Text_ // *Intent_Message_Image_ // *Intent_Message_QuickReplies_ @@ -3665,7 +3663,6 @@ type Intent_Message_MediaContent_ResponseMediaObject struct { // Image to show with the media card. // // Types that are assignable to Image: - // // *Intent_Message_MediaContent_ResponseMediaObject_LargeImage // *Intent_Message_MediaContent_ResponseMediaObject_Icon Image isIntent_Message_MediaContent_ResponseMediaObject_Image `protobuf_oneof:"image"` @@ -5523,9 +5520,9 @@ type IntentsClient interface { // operation](https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: An empty [Struct - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) - // - `response`: [BatchUpdateIntentsResponse][google.cloud.dialogflow.v2.BatchUpdateIntentsResponse] + // - `metadata`: An empty [Struct + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) + // - `response`: [BatchUpdateIntentsResponse][google.cloud.dialogflow.v2.BatchUpdateIntentsResponse] // // Note: You should always train an agent prior to sending it queries. See the // [training @@ -5537,10 +5534,10 @@ type IntentsClient interface { // operation](https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: An empty [Struct - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) - // - `response`: An [Empty - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) + // - `metadata`: An empty [Struct + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) + // - `response`: An [Empty + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) // // Note: You should always train an agent prior to sending it queries. See the // [training @@ -5649,9 +5646,9 @@ type IntentsServer interface { // operation](https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: An empty [Struct - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) - // - `response`: [BatchUpdateIntentsResponse][google.cloud.dialogflow.v2.BatchUpdateIntentsResponse] + // - `metadata`: An empty [Struct + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) + // - `response`: [BatchUpdateIntentsResponse][google.cloud.dialogflow.v2.BatchUpdateIntentsResponse] // // Note: You should always train an agent prior to sending it queries. See the // [training @@ -5663,10 +5660,10 @@ type IntentsServer interface { // operation](https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: An empty [Struct - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) - // - `response`: An [Empty - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) + // - `metadata`: An empty [Struct + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) + // - `response`: An [Empty + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) // // Note: You should always train an agent prior to sending it queries. See the // [training diff --git a/dialogflow/apiv2/dialogflowpb/knowledge_base.pb.go b/dialogflow/apiv2/dialogflowpb/knowledge_base.pb.go index e97c9c713dd4..1343d14e9877 100644 --- a/dialogflow/apiv2/dialogflowpb/knowledge_base.pb.go +++ b/dialogflow/apiv2/dialogflowpb/knowledge_base.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dialogflow/v2/knowledge_base.proto package dialogflowpb @@ -141,7 +141,7 @@ type ListKnowledgeBasesRequest struct { // The filter expression used to filter knowledge bases returned by the list // method. The expression has the following syntax: // - // [AND ] ... + // [AND ] ... // // The following fields and operators are supported: // @@ -150,14 +150,14 @@ type ListKnowledgeBasesRequest struct { // // Examples: // - // - 'language_code=en-us' matches knowledge bases with en-us language code. - // - 'display_name:articles' matches knowledge bases whose display name - // contains "articles". - // - 'display_name:"Best Articles"' matches knowledge bases whose display - // name contains "Best Articles". - // - 'language_code=en-gb AND display_name=articles' matches all knowledge - // bases whose display name contains "articles" and whose language code is - // "en-gb". + // * 'language_code=en-us' matches knowledge bases with en-us language code. + // * 'display_name:articles' matches knowledge bases whose display name + // contains "articles". + // * 'display_name:"Best Articles"' matches knowledge bases whose display + // name contains "Best Articles". + // * 'language_code=en-gb AND display_name=articles' matches all knowledge + // bases whose display name contains "articles" and whose language code is + // "en-gb". // // Note: An empty filter string (i.e. "") is a no-op and will result in no // filtering. diff --git a/dialogflow/apiv2/dialogflowpb/participant.pb.go b/dialogflow/apiv2/dialogflowpb/participant.pb.go index 1819576ec939..040a038ebaa3 100644 --- a/dialogflow/apiv2/dialogflowpb/participant.pb.go +++ b/dialogflow/apiv2/dialogflowpb/participant.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dialogflow/v2/participant.proto package dialogflowpb @@ -178,15 +178,15 @@ type Participant struct { // // You can specify a user id as follows: // - // 1. If you set this field in - // [CreateParticipantRequest][google.cloud.dialogflow.v2.CreateParticipantRequest.participant] or - // [UpdateParticipantRequest][google.cloud.dialogflow.v2.UpdateParticipantRequest.participant], - // Dialogflow adds the obfuscated user id with the participant. + // 1. If you set this field in + // [CreateParticipantRequest][google.cloud.dialogflow.v2.CreateParticipantRequest.participant] or + // [UpdateParticipantRequest][google.cloud.dialogflow.v2.UpdateParticipantRequest.participant], + // Dialogflow adds the obfuscated user id with the participant. // - // 2. If you set this field in - // [AnalyzeContent][google.cloud.dialogflow.v2.AnalyzeContentRequest.obfuscated_external_user_id] or - // [StreamingAnalyzeContent][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.obfuscated_external_user_id], - // Dialogflow will update [Participant.obfuscated_external_user_id][google.cloud.dialogflow.v2.Participant.obfuscated_external_user_id]. + // 2. If you set this field in + // [AnalyzeContent][google.cloud.dialogflow.v2.AnalyzeContentRequest.obfuscated_external_user_id] or + // [StreamingAnalyzeContent][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.obfuscated_external_user_id], + // Dialogflow will update [Participant.obfuscated_external_user_id][google.cloud.dialogflow.v2.Participant.obfuscated_external_user_id]. // // Dialogflow returns an error if you try to add a user id for a // non-[END_USER][google.cloud.dialogflow.v2.Participant.Role.END_USER] participant. @@ -197,11 +197,11 @@ type Participant struct { // // Note: // - // - Please never pass raw user ids to Dialogflow. Always obfuscate your user - // id first. - // - Dialogflow only accepts a UTF-8 encoded string, e.g., a hex digest of a - // hash function like SHA-512. - // - The length of the user id must be <= 256 characters. + // * Please never pass raw user ids to Dialogflow. Always obfuscate your user + // id first. + // * Dialogflow only accepts a UTF-8 encoded string, e.g., a hex digest of a + // hash function like SHA-512. + // * The length of the user id must be <= 256 characters. ObfuscatedExternalUserId string `protobuf:"bytes,7,opt,name=obfuscated_external_user_id,json=obfuscatedExternalUserId,proto3" json:"obfuscated_external_user_id,omitempty"` // Optional. Key-value filters on the metadata of documents returned by article // suggestion. If specified, article suggestion only returns suggested @@ -210,17 +210,14 @@ type Participant struct { // filters to match all documents that have 'US' or 'CA' in their market // metadata values and 'agent' in their user metadata values will be // ``` - // - // documents_metadata_filters { - // key: "market" - // value: "US,CA" - // } - // - // documents_metadata_filters { - // key: "user" - // value: "agent" - // } - // + // documents_metadata_filters { + // key: "market" + // value: "US,CA" + // } + // documents_metadata_filters { + // key: "user" + // value: "agent" + // } // ``` DocumentsMetadataFilters map[string]string `protobuf:"bytes,8,rep,name=documents_metadata_filters,json=documentsMetadataFilters,proto3" json:"documents_metadata_filters,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` } @@ -729,7 +726,6 @@ type AnalyzeContentRequest struct { // Required. The input content. // // Types that are assignable to Input: - // // *AnalyzeContentRequest_TextInput // *AnalyzeContentRequest_EventInput Input isAnalyzeContentRequest_Input `protobuf_oneof:"input"` @@ -931,10 +927,10 @@ type AnalyzeContentResponse struct { // The audio data bytes encoded as specified in the request. // This field is set if: // - // - `reply_audio_config` was specified in the request, or - // - The automated agent responded with audio to play to the user. In such - // case, `reply_audio.config` contains settings used to synthesize the - // speech. + // - `reply_audio_config` was specified in the request, or + // - The automated agent responded with audio to play to the user. In such + // case, `reply_audio.config` contains settings used to synthesize the + // speech. // // In some scenarios, multiple output audio fields may be present in the // response structure. In these cases, only the top-most-level audio output @@ -1093,7 +1089,6 @@ type StreamingAnalyzeContentRequest struct { // The input config. // // Types that are assignable to Config: - // // *StreamingAnalyzeContentRequest_AudioConfig // *StreamingAnalyzeContentRequest_TextConfig Config isStreamingAnalyzeContentRequest_Config `protobuf_oneof:"config"` @@ -1106,7 +1101,6 @@ type StreamingAnalyzeContentRequest struct { // The input. // // Types that are assignable to Input: - // // *StreamingAnalyzeContentRequest_InputAudio // *StreamingAnalyzeContentRequest_InputText // *StreamingAnalyzeContentRequest_InputDtmf @@ -1338,10 +1332,10 @@ type StreamingAnalyzeContentResponse struct { // The audio data bytes encoded as specified in the request. // This field is set if: // - // - The `reply_audio_config` field is specified in the request. - // - The automated agent, which this output comes from, responded with audio. - // In such case, the `reply_audio.config` field contains settings used to - // synthesize the speech. + // - The `reply_audio_config` field is specified in the request. + // - The automated agent, which this output comes from, responded with audio. + // In such case, the `reply_audio.config` field contains settings used to + // synthesize the speech. // // In some scenarios, multiple output audio fields may be present in the // response structure. In these cases, only the top-most-level audio output @@ -2359,7 +2353,6 @@ type SuggestionResult struct { // Different type of suggestion response. // // Types that are assignable to SuggestionResponse: - // // *SuggestionResult_Error // *SuggestionResult_SuggestArticlesResponse // *SuggestionResult_SuggestFaqAnswersResponse @@ -2537,12 +2530,10 @@ type AnnotatedMessagePart struct { // this message part. For example for a system entity of type // `@sys.unit-currency`, this may contain: //
-	//
-	//	{
-	//	  "amount": 5,
-	//	  "currency": "USD"
-	//	}
-	//
+	// {
+	//   "amount": 5,
+	//   "currency": "USD"
+	// }
 	// 
FormattedValue *structpb.Value `protobuf:"bytes,3,opt,name=formatted_value,json=formattedValue,proto3" json:"formatted_value,omitempty"` } @@ -2673,17 +2664,14 @@ type AssistQueryParameters struct { // filters to match all documents that have 'US' or 'CA' in their market // metadata values and 'agent' in their user metadata values will be // ``` - // - // documents_metadata_filters { - // key: "market" - // value: "US,CA" - // } - // - // documents_metadata_filters { - // key: "user" - // value: "agent" - // } - // + // documents_metadata_filters { + // key: "market" + // value: "US,CA" + // } + // documents_metadata_filters { + // key: "user" + // value: "agent" + // } // ``` DocumentsMetadataFilters map[string]string `protobuf:"bytes,1,rep,name=documents_metadata_filters,json=documentsMetadataFilters,proto3" json:"documents_metadata_filters,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` } diff --git a/dialogflow/apiv2/dialogflowpb/session.pb.go b/dialogflow/apiv2/dialogflowpb/session.pb.go index f17e9cf474aa..a907e65715e7 100644 --- a/dialogflow/apiv2/dialogflowpb/session.pb.go +++ b/dialogflow/apiv2/dialogflowpb/session.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dialogflow/v2/session.proto package dialogflowpb @@ -132,7 +132,7 @@ type DetectIntentRequest struct { QueryParams *QueryParameters `protobuf:"bytes,2,opt,name=query_params,json=queryParams,proto3" json:"query_params,omitempty"` // Required. The input specification. It can be set to: // - // 1. an audio config + // 1. an audio config // which instructs the speech recognizer how to process the speech audio, // // 2. a conversational query in the form of text, or @@ -474,7 +474,6 @@ type QueryInput struct { // Required. The input specification. // // Types that are assignable to Input: - // // *QueryInput_AudioConfig // *QueryInput_Text // *QueryInput_Event @@ -575,13 +574,13 @@ type QueryResult struct { // The original conversational query text: // - // - If natural language text was provided as input, `query_text` contains - // a copy of the input. - // - If natural language speech audio was provided as input, `query_text` - // contains the speech recognition result. If speech recognizer produced - // multiple alternatives, a particular one is picked. - // - If automatic spell correction is enabled, `query_text` will contain the - // corrected user input. + // - If natural language text was provided as input, `query_text` contains + // a copy of the input. + // - If natural language speech audio was provided as input, `query_text` + // contains the speech recognition result. If speech recognizer produced + // multiple alternatives, a particular one is picked. + // - If automatic spell correction is enabled, `query_text` will contain the + // corrected user input. QueryText string `protobuf:"bytes,1,opt,name=query_text,json=queryText,proto3" json:"query_text,omitempty"` // The language that was triggered during intent detection. // See [Language @@ -609,21 +608,20 @@ type QueryResult struct { // - MapKey type: string // - MapKey value: parameter name // - MapValue type: - // - If parameter's entity type is a composite entity: map - // - Else: depending on parameter value type, could be one of string, - // number, boolean, null, list or map - // + // - If parameter's entity type is a composite entity: map + // - Else: depending on parameter value type, could be one of string, + // number, boolean, null, list or map // - MapValue value: - // - If parameter's entity type is a composite entity: - // map from composite entity property names to property values - // - Else: parameter value + // - If parameter's entity type is a composite entity: + // map from composite entity property names to property values + // - Else: parameter value Parameters *structpb.Struct `protobuf:"bytes,4,opt,name=parameters,proto3" json:"parameters,omitempty"` // This field is set to: // - // - `false` if the matched intent has required parameters and not all of - // the required parameter values have been collected. - // - `true` if all required parameter values have been collected, or if the - // matched intent doesn't contain any required parameters. + // - `false` if the matched intent has required parameters and not all of + // the required parameter values have been collected. + // - `true` if all required parameter values have been collected, or if the + // matched intent doesn't contain any required parameters. AllRequiredParamsPresent bool `protobuf:"varint,5,opt,name=all_required_params_present,json=allRequiredParamsPresent,proto3" json:"all_required_params_present,omitempty"` // Indicates whether the conversational query triggers a cancellation for slot // filling. For more information, see the [cancel slot filling @@ -823,28 +821,28 @@ func (x *QueryResult) GetSentimentAnalysisResult() *SentimentAnalysisResult { // 1. The first message must contain // [session][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.session], // -// [query_input][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.query_input] plus optionally -// [query_params][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.query_params]. If the client -// wants to receive an audio response, it should also contain -// [output_audio_config][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.output_audio_config]. -// The message must not contain -// [input_audio][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.input_audio]. +// [query_input][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.query_input] plus optionally +// [query_params][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.query_params]. If the client +// wants to receive an audio response, it should also contain +// [output_audio_config][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.output_audio_config]. +// The message must not contain +// [input_audio][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.input_audio]. // -// 2. If [query_input][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.query_input] was set to -// [query_input.audio_config][google.cloud.dialogflow.v2.InputAudioConfig], all subsequent -// messages must contain -// [input_audio][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.input_audio] to continue with -// Speech recognition. -// If you decide to rather detect an intent from text input after you -// already started Speech recognition, please send a message with -// [query_input.text][google.cloud.dialogflow.v2.QueryInput.text]. +// 2. If [query_input][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.query_input] was set to +// [query_input.audio_config][google.cloud.dialogflow.v2.InputAudioConfig], all subsequent +// messages must contain +// [input_audio][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.input_audio] to continue with +// Speech recognition. +// If you decide to rather detect an intent from text input after you +// already started Speech recognition, please send a message with +// [query_input.text][google.cloud.dialogflow.v2.QueryInput.text]. // -// However, note that: +// However, note that: // -// * Dialogflow will bill you for the audio duration so far. -// * Dialogflow discards all Speech recognition results in favor of the -// input text. -// * Dialogflow will use the language code from the first message. +// * Dialogflow will bill you for the audio duration so far. +// * Dialogflow discards all Speech recognition results in favor of the +// input text. +// * Dialogflow will use the language code from the first message. // // After you sent all input, you must half-close or abort the request stream. type StreamingDetectIntentRequest struct { @@ -874,7 +872,7 @@ type StreamingDetectIntentRequest struct { QueryParams *QueryParameters `protobuf:"bytes,2,opt,name=query_params,json=queryParams,proto3" json:"query_params,omitempty"` // Required. The input specification. It can be set to: // - // 1. an audio config which instructs the speech recognizer how to process + // 1. an audio config which instructs the speech recognizer how to process // the speech audio, // // 2. a conversational query in the form of text, or @@ -1345,14 +1343,13 @@ type EventInput struct { // - MapKey type: string // - MapKey value: parameter name // - MapValue type: - // - If parameter's entity type is a composite entity: map - // - Else: depending on parameter value type, could be one of string, - // number, boolean, null, list or map - // + // - If parameter's entity type is a composite entity: map + // - Else: depending on parameter value type, could be one of string, + // number, boolean, null, list or map // - MapValue value: - // - If parameter's entity type is a composite entity: - // map from composite entity property names to property values - // - Else: parameter value + // - If parameter's entity type is a composite entity: + // map from composite entity property names to property values + // - Else: parameter value Parameters *structpb.Struct `protobuf:"bytes,2,opt,name=parameters,proto3" json:"parameters,omitempty"` // Required. The language of this query. See [Language // Support](https://cloud.google.com/dialogflow/docs/reference/language) diff --git a/dialogflow/apiv2/dialogflowpb/session_entity_type.pb.go b/dialogflow/apiv2/dialogflowpb/session_entity_type.pb.go index dcaf8308f8a8..5cbb88519763 100644 --- a/dialogflow/apiv2/dialogflowpb/session_entity_type.pb.go +++ b/dialogflow/apiv2/dialogflowpb/session_entity_type.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dialogflow/v2/session_entity_type.proto package dialogflowpb diff --git a/dialogflow/apiv2/dialogflowpb/validation_result.pb.go b/dialogflow/apiv2/dialogflowpb/validation_result.pb.go index 88f0b25b83bf..fa9601a32751 100644 --- a/dialogflow/apiv2/dialogflowpb/validation_result.pb.go +++ b/dialogflow/apiv2/dialogflowpb/validation_result.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dialogflow/v2/validation_result.proto package dialogflowpb diff --git a/dialogflow/apiv2/dialogflowpb/version.pb.go b/dialogflow/apiv2/dialogflowpb/version.pb.go index d0ad93c6ead7..00df73511810 100644 --- a/dialogflow/apiv2/dialogflowpb/version.pb.go +++ b/dialogflow/apiv2/dialogflowpb/version.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dialogflow/v2/version.proto package dialogflowpb @@ -126,9 +126,9 @@ type Version struct { // Output only. The unique identifier of this agent version. // Supported formats: // - // - `projects//agent/versions/` - // - `projects//locations//agent/versions/` + // - `projects//agent/versions/` + // - `projects//locations//agent/versions/` Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Optional. The developer-provided description of this version. Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` @@ -351,9 +351,9 @@ type GetVersionRequest struct { // Required. The name of the version. // Supported formats: // - // - `projects//agent/versions/` - // - `projects//locations//agent/versions/` + // - `projects//agent/versions/` + // - `projects//locations//agent/versions/` Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` } @@ -467,9 +467,9 @@ type UpdateVersionRequest struct { // Required. The version to update. // Supported formats: // - // - `projects//agent/versions/` - // - `projects//locations//agent/versions/` + // - `projects//agent/versions/` + // - `projects//locations//agent/versions/` Version *Version `protobuf:"bytes,1,opt,name=version,proto3" json:"version,omitempty"` // Required. The mask to control which fields get updated. UpdateMask *fieldmaskpb.FieldMask `protobuf:"bytes,2,opt,name=update_mask,json=updateMask,proto3" json:"update_mask,omitempty"` @@ -530,9 +530,9 @@ type DeleteVersionRequest struct { // Required. The name of the version to delete. // Supported formats: // - // - `projects//agent/versions/` - // - `projects//locations//agent/versions/` + // - `projects//agent/versions/` + // - `projects//locations//agent/versions/` Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` } diff --git a/dialogflow/apiv2/dialogflowpb/webhook.pb.go b/dialogflow/apiv2/dialogflowpb/webhook.pb.go index ffcc92808648..d948de542062 100644 --- a/dialogflow/apiv2/dialogflowpb/webhook.pb.go +++ b/dialogflow/apiv2/dialogflowpb/webhook.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dialogflow/v2/webhook.proto package dialogflowpb @@ -280,13 +280,11 @@ type OriginalDetectIntentRequest struct { // // In particular, for the Dialogflow Phone Gateway integration, this field has // the form: - // - //
{
-	//	 "telephony": {
-	//	   "caller_id": "+18558363987"
-	//	 }
-	//	}
- // + //
{
+	//  "telephony": {
+	//    "caller_id": "+18558363987"
+	//  }
+	// }
// Note: The caller ID field (`caller_id`) will be redacted for Trial // Edition agents and populated with the caller ID in [E.164 // format](https://en.wikipedia.org/wiki/E.164) for Essentials Edition agents. diff --git a/dialogflow/apiv2/doc.go b/dialogflow/apiv2/doc.go index 42b5c8e8016d..1bc410b5aa1c 100644 --- a/dialogflow/apiv2/doc.go +++ b/dialogflow/apiv2/doc.go @@ -81,6 +81,8 @@ package dialogflow // import "cloud.google.com/go/dialogflow/apiv2" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -170,3 +172,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/dialogflow/apiv2/documents_client.go b/dialogflow/apiv2/documents_client.go index aafc2dc0ffbd..ffe037d247f5 100644 --- a/dialogflow/apiv2/documents_client.go +++ b/dialogflow/apiv2/documents_client.go @@ -17,9 +17,12 @@ package dialogflow import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,15 +30,18 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -168,6 +174,96 @@ func defaultDocumentsCallOptions() *DocumentsCallOptions { } } +func defaultDocumentsRESTCallOptions() *DocumentsCallOptions { + return &DocumentsCallOptions{ + ListDocuments: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetDocument: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateDocument: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ImportDocuments: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeleteDocument: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UpdateDocument: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ReloadDocument: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ExportDocument: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + CancelOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalDocumentsClient is an interface that defines the methods available from Dialogflow API. type internalDocumentsClient interface { Close() error @@ -496,6 +592,89 @@ func (c *documentsGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type documentsRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing DocumentsClient + CallOptions **DocumentsCallOptions +} + +// NewDocumentsRESTClient creates a new documents rest client. +// +// Service for managing knowledge Documents. +func NewDocumentsRESTClient(ctx context.Context, opts ...option.ClientOption) (*DocumentsClient, error) { + clientOpts := append(defaultDocumentsRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultDocumentsRESTCallOptions() + c := &documentsRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &DocumentsClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultDocumentsRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://dialogflow.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://dialogflow.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://dialogflow.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *documentsRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *documentsRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *documentsRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *documentsGRPCClient) ListDocuments(ctx context.Context, req *dialogflowpb.ListDocumentsRequest, opts ...gax.CallOption) *DocumentIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -844,105 +1023,1087 @@ func (c *documentsGRPCClient) ListOperations(ctx context.Context, req *longrunni return it } -// CreateDocumentOperation manages a long-running operation from CreateDocument. -type CreateDocumentOperation struct { - lro *longrunning.Operation -} +// ListDocuments returns the list of all documents of the knowledge base. +func (c *documentsRESTClient) ListDocuments(ctx context.Context, req *dialogflowpb.ListDocumentsRequest, opts ...gax.CallOption) *DocumentIterator { + it := &DocumentIterator{} + req = proto.Clone(req).(*dialogflowpb.ListDocumentsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*dialogflowpb.Document, string, error) { + resp := &dialogflowpb.ListDocumentsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/documents", req.GetParent()) -// CreateDocumentOperation returns a new CreateDocumentOperation from a given name. -// The name must be that of a previously created CreateDocumentOperation, possibly from a different process. -func (c *documentsGRPCClient) CreateDocumentOperation(name string) *CreateDocumentOperation { - return &CreateDocumentOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *CreateDocumentOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*dialogflowpb.Document, error) { - var resp dialogflowpb.Document - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { - return nil, err + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetDocuments(), resp.GetNextPageToken(), nil } - return &resp, nil -} -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *CreateDocumentOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*dialogflowpb.Document, error) { - var resp dialogflowpb.Document - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { - return nil, err - } - if !op.Done() { - return nil, 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 } - return &resp, nil + + it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it } -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *CreateDocumentOperation) Metadata() (*dialogflowpb.KnowledgeOperationMetadata, error) { - var meta dialogflowpb.KnowledgeOperationMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { +// GetDocument retrieves the specified document. +func (c *documentsRESTClient) GetDocument(ctx context.Context, req *dialogflowpb.GetDocumentRequest, opts ...gax.CallOption) (*dialogflowpb.Document, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - return &meta, nil -} + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) -// Done reports whether the long-running operation has completed. -func (op *CreateDocumentOperation) Done() bool { - return op.lro.Done() -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") -// 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 *CreateDocumentOperation) Name() string { - return op.lro.Name() -} + baseUrl.RawQuery = params.Encode() -// DeleteDocumentOperation manages a long-running operation from DeleteDocument. -type DeleteDocumentOperation struct { - lro *longrunning.Operation -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) -// DeleteDocumentOperation returns a new DeleteDocumentOperation from a given name. -// The name must be that of a previously created DeleteDocumentOperation, possibly from a different process. -func (c *documentsGRPCClient) DeleteDocumentOperation(name string) *DeleteDocumentOperation { - return &DeleteDocumentOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetDocument[0:len((*c.CallOptions).GetDocument):len((*c.CallOptions).GetDocument)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dialogflowpb.Document{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e } + return resp, nil } -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// CreateDocument creates a new document. // -// See documentation of Poll for error-handling information. -func (op *DeleteDocumentOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { - return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) -} - -// Poll fetches the latest state of the long-running operation. +// This method is a long-running +// operation (at https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation). +// The returned Operation type has the following method-specific fields: // -// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// metadata: KnowledgeOperationMetadata // -// 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, +// response: Document +func (c *documentsRESTClient) CreateDocument(ctx context.Context, req *dialogflowpb.CreateDocumentRequest, opts ...gax.CallOption) (*CreateDocumentOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetDocument() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/documents", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &CreateDocumentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ImportDocuments creates documents by importing data from external sources. +// Dialogflow supports up to 350 documents in each request. If you try to +// import more, Dialogflow will return an error. +// +// This method is a long-running +// operation (at https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation). +// The returned Operation type has the following method-specific fields: +// +// metadata: KnowledgeOperationMetadata +// +// response: ImportDocumentsResponse +func (c *documentsRESTClient) ImportDocuments(ctx context.Context, req *dialogflowpb.ImportDocumentsRequest, opts ...gax.CallOption) (*ImportDocumentsOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/documents:import", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &ImportDocumentsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteDocument deletes the specified document. +// +// This method is a long-running +// operation (at https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation). +// The returned Operation type has the following method-specific fields: +// +// metadata: KnowledgeOperationMetadata +// +// response: An Empty +// message (at https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) +func (c *documentsRESTClient) DeleteDocument(ctx context.Context, req *dialogflowpb.DeleteDocumentRequest, opts ...gax.CallOption) (*DeleteDocumentOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &DeleteDocumentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateDocument updates the specified document. +// +// This method is a long-running +// operation (at https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation). +// The returned Operation type has the following method-specific fields: +// +// metadata: KnowledgeOperationMetadata +// +// response: Document +func (c *documentsRESTClient) UpdateDocument(ctx context.Context, req *dialogflowpb.UpdateDocumentRequest, opts ...gax.CallOption) (*UpdateDocumentOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetDocument() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetDocument().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "document.name", url.QueryEscape(req.GetDocument().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &UpdateDocumentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ReloadDocument reloads the specified document from its specified source, content_uri or +// content. The previously loaded content of the document will be deleted. +// Note: Even when the content of the document has not changed, there still +// may be side effects because of internal implementation changes. +// +// This method is a long-running +// operation (at https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation). +// The returned Operation type has the following method-specific fields: +// +// metadata: KnowledgeOperationMetadata +// +// response: Document +// +// Note: The projects.agent.knowledgeBases.documents resource is deprecated; +// only use projects.knowledgeBases.documents. +func (c *documentsRESTClient) ReloadDocument(ctx context.Context, req *dialogflowpb.ReloadDocumentRequest, opts ...gax.CallOption) (*ReloadDocumentOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:reload", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &ReloadDocumentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ExportDocument exports a smart messaging candidate document into the specified +// destination. +// +// This method is a long-running +// operation (at https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation). +// The returned Operation type has the following method-specific fields: +// +// metadata: KnowledgeOperationMetadata +// +// response: Document +func (c *documentsRESTClient) ExportDocument(ctx context.Context, req *dialogflowpb.ExportDocumentRequest, opts ...gax.CallOption) (*ExportDocumentOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:export", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &ExportDocumentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetLocation gets information about a location. +func (c *documentsRESTClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *documentsRESTClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *documentsRESTClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *documentsRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *documentsRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CreateDocumentOperation manages a long-running operation from CreateDocument. +type CreateDocumentOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateDocumentOperation returns a new CreateDocumentOperation from a given name. +// The name must be that of a previously created CreateDocumentOperation, possibly from a different process. +func (c *documentsGRPCClient) CreateDocumentOperation(name string) *CreateDocumentOperation { + return &CreateDocumentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateDocumentOperation returns a new CreateDocumentOperation from a given name. +// The name must be that of a previously created CreateDocumentOperation, possibly from a different process. +func (c *documentsRESTClient) CreateDocumentOperation(name string) *CreateDocumentOperation { + override := fmt.Sprintf("/v2/%s", name) + return &CreateDocumentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CreateDocumentOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*dialogflowpb.Document, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp dialogflowpb.Document + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *CreateDocumentOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*dialogflowpb.Document, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp dialogflowpb.Document + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *CreateDocumentOperation) Metadata() (*dialogflowpb.KnowledgeOperationMetadata, error) { + var meta dialogflowpb.KnowledgeOperationMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *CreateDocumentOperation) Done() bool { + return op.lro.Done() +} + +// 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 *CreateDocumentOperation) Name() string { + return op.lro.Name() +} + +// DeleteDocumentOperation manages a long-running operation from DeleteDocument. +type DeleteDocumentOperation struct { + lro *longrunning.Operation + pollPath string +} + +// DeleteDocumentOperation returns a new DeleteDocumentOperation from a given name. +// The name must be that of a previously created DeleteDocumentOperation, possibly from a different process. +func (c *documentsGRPCClient) DeleteDocumentOperation(name string) *DeleteDocumentOperation { + return &DeleteDocumentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// DeleteDocumentOperation returns a new DeleteDocumentOperation from a given name. +// The name must be that of a previously created DeleteDocumentOperation, possibly from a different process. +func (c *documentsRESTClient) DeleteDocumentOperation(name string) *DeleteDocumentOperation { + override := fmt.Sprintf("/v2/%s", name) + return &DeleteDocumentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *DeleteDocumentOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteDocumentOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -973,7 +2134,8 @@ func (op *DeleteDocumentOperation) Name() string { // ExportDocumentOperation manages a long-running operation from ExportDocument. type ExportDocumentOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // ExportDocumentOperation returns a new ExportDocumentOperation from a given name. @@ -984,10 +2146,21 @@ func (c *documentsGRPCClient) ExportDocumentOperation(name string) *ExportDocume } } +// ExportDocumentOperation returns a new ExportDocumentOperation from a given name. +// The name must be that of a previously created ExportDocumentOperation, possibly from a different process. +func (c *documentsRESTClient) ExportDocumentOperation(name string) *ExportDocumentOperation { + override := fmt.Sprintf("/v2/%s", name) + return &ExportDocumentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *ExportDocumentOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*dialogflowpb.Document, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp dialogflowpb.Document if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1005,6 +2178,7 @@ func (op *ExportDocumentOperation) Wait(ctx context.Context, opts ...gax.CallOpt // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *ExportDocumentOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*dialogflowpb.Document, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp dialogflowpb.Document if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1042,7 +2216,8 @@ func (op *ExportDocumentOperation) Name() string { // ImportDocumentsOperation manages a long-running operation from ImportDocuments. type ImportDocumentsOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // ImportDocumentsOperation returns a new ImportDocumentsOperation from a given name. @@ -1053,10 +2228,21 @@ func (c *documentsGRPCClient) ImportDocumentsOperation(name string) *ImportDocum } } +// ImportDocumentsOperation returns a new ImportDocumentsOperation from a given name. +// The name must be that of a previously created ImportDocumentsOperation, possibly from a different process. +func (c *documentsRESTClient) ImportDocumentsOperation(name string) *ImportDocumentsOperation { + override := fmt.Sprintf("/v2/%s", name) + return &ImportDocumentsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *ImportDocumentsOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*dialogflowpb.ImportDocumentsResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp dialogflowpb.ImportDocumentsResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1074,6 +2260,7 @@ func (op *ImportDocumentsOperation) Wait(ctx context.Context, opts ...gax.CallOp // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *ImportDocumentsOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*dialogflowpb.ImportDocumentsResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp dialogflowpb.ImportDocumentsResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1111,7 +2298,8 @@ func (op *ImportDocumentsOperation) Name() string { // ReloadDocumentOperation manages a long-running operation from ReloadDocument. type ReloadDocumentOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // ReloadDocumentOperation returns a new ReloadDocumentOperation from a given name. @@ -1122,10 +2310,21 @@ func (c *documentsGRPCClient) ReloadDocumentOperation(name string) *ReloadDocume } } +// ReloadDocumentOperation returns a new ReloadDocumentOperation from a given name. +// The name must be that of a previously created ReloadDocumentOperation, possibly from a different process. +func (c *documentsRESTClient) ReloadDocumentOperation(name string) *ReloadDocumentOperation { + override := fmt.Sprintf("/v2/%s", name) + return &ReloadDocumentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *ReloadDocumentOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*dialogflowpb.Document, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp dialogflowpb.Document if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1143,6 +2342,7 @@ func (op *ReloadDocumentOperation) Wait(ctx context.Context, opts ...gax.CallOpt // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *ReloadDocumentOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*dialogflowpb.Document, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp dialogflowpb.Document if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1180,7 +2380,8 @@ func (op *ReloadDocumentOperation) Name() string { // UpdateDocumentOperation manages a long-running operation from UpdateDocument. type UpdateDocumentOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateDocumentOperation returns a new UpdateDocumentOperation from a given name. @@ -1191,10 +2392,21 @@ func (c *documentsGRPCClient) UpdateDocumentOperation(name string) *UpdateDocume } } +// UpdateDocumentOperation returns a new UpdateDocumentOperation from a given name. +// The name must be that of a previously created UpdateDocumentOperation, possibly from a different process. +func (c *documentsRESTClient) UpdateDocumentOperation(name string) *UpdateDocumentOperation { + override := fmt.Sprintf("/v2/%s", name) + return &UpdateDocumentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateDocumentOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*dialogflowpb.Document, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp dialogflowpb.Document if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1212,6 +2424,7 @@ func (op *UpdateDocumentOperation) Wait(ctx context.Context, opts ...gax.CallOpt // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateDocumentOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*dialogflowpb.Document, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp dialogflowpb.Document if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/dialogflow/apiv2/documents_client_example_test.go b/dialogflow/apiv2/documents_client_example_test.go index 7d64b0b68b0d..d96d5495fd63 100644 --- a/dialogflow/apiv2/documents_client_example_test.go +++ b/dialogflow/apiv2/documents_client_example_test.go @@ -43,6 +43,23 @@ func ExampleNewDocumentsClient() { _ = c } +func ExampleNewDocumentsRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := dialogflow.NewDocumentsRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleDocumentsClient_ListDocuments() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/dialogflow/apiv2/entity_types_client.go b/dialogflow/apiv2/entity_types_client.go index 5484a307045a..b4457d6b3fd4 100644 --- a/dialogflow/apiv2/entity_types_client.go +++ b/dialogflow/apiv2/entity_types_client.go @@ -17,9 +17,12 @@ package dialogflow import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,15 +30,18 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" structpb "google.golang.org/protobuf/types/known/structpb" ) @@ -193,6 +199,116 @@ func defaultEntityTypesCallOptions() *EntityTypesCallOptions { } } +func defaultEntityTypesRESTCallOptions() *EntityTypesCallOptions { + return &EntityTypesCallOptions{ + ListEntityTypes: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetEntityType: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateEntityType: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UpdateEntityType: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeleteEntityType: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + BatchUpdateEntityTypes: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + BatchDeleteEntityTypes: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + BatchCreateEntities: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + BatchUpdateEntities: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + BatchDeleteEntities: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + CancelOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalEntityTypesClient is an interface that defines the methods available from Dialogflow API. type internalEntityTypesClient interface { Close() error @@ -551,6 +667,89 @@ func (c *entityTypesGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type entityTypesRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing EntityTypesClient + CallOptions **EntityTypesCallOptions +} + +// NewEntityTypesRESTClient creates a new entity types rest client. +// +// Service for managing EntityTypes. +func NewEntityTypesRESTClient(ctx context.Context, opts ...option.ClientOption) (*EntityTypesClient, error) { + clientOpts := append(defaultEntityTypesRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultEntityTypesRESTCallOptions() + c := &entityTypesRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &EntityTypesClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultEntityTypesRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://dialogflow.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://dialogflow.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://dialogflow.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *entityTypesRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *entityTypesRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *entityTypesRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *entityTypesGRPCClient) ListEntityTypes(ctx context.Context, req *dialogflowpb.ListEntityTypesRequest, opts ...gax.CallOption) *EntityTypeIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -937,87 +1136,1208 @@ func (c *entityTypesGRPCClient) ListOperations(ctx context.Context, req *longrun return it } -// BatchCreateEntitiesOperation manages a long-running operation from BatchCreateEntities. -type BatchCreateEntitiesOperation struct { - lro *longrunning.Operation -} +// ListEntityTypes returns the list of all entity types in the specified agent. +func (c *entityTypesRESTClient) ListEntityTypes(ctx context.Context, req *dialogflowpb.ListEntityTypesRequest, opts ...gax.CallOption) *EntityTypeIterator { + it := &EntityTypeIterator{} + req = proto.Clone(req).(*dialogflowpb.ListEntityTypesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*dialogflowpb.EntityType, string, error) { + resp := &dialogflowpb.ListEntityTypesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/entityTypes", req.GetParent()) -// BatchCreateEntitiesOperation returns a new BatchCreateEntitiesOperation from a given name. -// The name must be that of a previously created BatchCreateEntitiesOperation, possibly from a different process. -func (c *entityTypesGRPCClient) BatchCreateEntitiesOperation(name string) *BatchCreateEntitiesOperation { - return &BatchCreateEntitiesOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetLanguageCode() != "" { + params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetEntityTypes(), resp.GetNextPageToken(), nil } -} -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *BatchCreateEntitiesOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { - return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) -} + 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 + } -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *BatchCreateEntitiesOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { - return op.lro.Poll(ctx, nil, opts...) + it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it } -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *BatchCreateEntitiesOperation) Metadata() (*structpb.Struct, error) { - var meta structpb.Struct - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { +// GetEntityType retrieves the specified entity type. +func (c *entityTypesRESTClient) GetEntityType(ctx context.Context, req *dialogflowpb.GetEntityTypeRequest, opts ...gax.CallOption) (*dialogflowpb.EntityType, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - return &meta, nil -} + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) -// Done reports whether the long-running operation has completed. -func (op *BatchCreateEntitiesOperation) Done() bool { - return op.lro.Done() -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetLanguageCode() != "" { + params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) + } -// 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 *BatchCreateEntitiesOperation) Name() string { - return op.lro.Name() -} + baseUrl.RawQuery = params.Encode() -// BatchDeleteEntitiesOperation manages a long-running operation from BatchDeleteEntities. -type BatchDeleteEntitiesOperation struct { - lro *longrunning.Operation -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) -// BatchDeleteEntitiesOperation returns a new BatchDeleteEntitiesOperation from a given name. -// The name must be that of a previously created BatchDeleteEntitiesOperation, possibly from a different process. -func (c *entityTypesGRPCClient) BatchDeleteEntitiesOperation(name string) *BatchDeleteEntitiesOperation { - return &BatchDeleteEntitiesOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetEntityType[0:len((*c.CallOptions).GetEntityType):len((*c.CallOptions).GetEntityType)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dialogflowpb.EntityType{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *BatchDeleteEntitiesOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { - return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil } -// Poll fetches the latest state of the long-running operation. +// CreateEntityType creates an entity type in the specified agent. // -// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// Note: You should always train an agent prior to sending it queries. See the +// training +// documentation (at https://cloud.google.com/dialogflow/es/docs/training). +func (c *entityTypesRESTClient) CreateEntityType(ctx context.Context, req *dialogflowpb.CreateEntityTypeRequest, opts ...gax.CallOption) (*dialogflowpb.EntityType, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetEntityType() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/entityTypes", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetLanguageCode() != "" { + params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateEntityType[0:len((*c.CallOptions).CreateEntityType):len((*c.CallOptions).CreateEntityType)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dialogflowpb.EntityType{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateEntityType updates the specified entity type. +// +// Note: You should always train an agent prior to sending it queries. See the +// training +// documentation (at https://cloud.google.com/dialogflow/es/docs/training). +func (c *entityTypesRESTClient) UpdateEntityType(ctx context.Context, req *dialogflowpb.UpdateEntityTypeRequest, opts ...gax.CallOption) (*dialogflowpb.EntityType, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetEntityType() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetEntityType().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetLanguageCode() != "" { + params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) + } + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "entity_type.name", url.QueryEscape(req.GetEntityType().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateEntityType[0:len((*c.CallOptions).UpdateEntityType):len((*c.CallOptions).UpdateEntityType)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dialogflowpb.EntityType{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteEntityType deletes the specified entity type. +// +// Note: You should always train an agent prior to sending it queries. See the +// training +// documentation (at https://cloud.google.com/dialogflow/es/docs/training). +func (c *entityTypesRESTClient) DeleteEntityType(ctx context.Context, req *dialogflowpb.DeleteEntityTypeRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// BatchUpdateEntityTypes updates/Creates multiple entity types in the specified agent. +// +// This method is a long-running +// operation (at https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). +// The returned Operation type has the following method-specific fields: +// +// metadata: An empty Struct +// message (at https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) +// +// response: BatchUpdateEntityTypesResponse +// +// Note: You should always train an agent prior to sending it queries. See the +// training +// documentation (at https://cloud.google.com/dialogflow/es/docs/training). +func (c *entityTypesRESTClient) BatchUpdateEntityTypes(ctx context.Context, req *dialogflowpb.BatchUpdateEntityTypesRequest, opts ...gax.CallOption) (*BatchUpdateEntityTypesOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/entityTypes:batchUpdate", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &BatchUpdateEntityTypesOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// BatchDeleteEntityTypes deletes entity types in the specified agent. +// +// This method is a long-running +// operation (at https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). +// The returned Operation type has the following method-specific fields: +// +// metadata: An empty Struct +// message (at https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) +// +// response: An Empty +// message (at https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) +// +// Note: You should always train an agent prior to sending it queries. See the +// training +// documentation (at https://cloud.google.com/dialogflow/es/docs/training). +func (c *entityTypesRESTClient) BatchDeleteEntityTypes(ctx context.Context, req *dialogflowpb.BatchDeleteEntityTypesRequest, opts ...gax.CallOption) (*BatchDeleteEntityTypesOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/entityTypes:batchDelete", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &BatchDeleteEntityTypesOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// BatchCreateEntities creates multiple new entities in the specified entity type. +// +// This method is a long-running +// operation (at https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). +// The returned Operation type has the following method-specific fields: +// +// metadata: An empty Struct +// message (at https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) +// +// response: An Empty +// message (at https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) +// +// Note: You should always train an agent prior to sending it queries. See the +// training +// documentation (at https://cloud.google.com/dialogflow/es/docs/training). +func (c *entityTypesRESTClient) BatchCreateEntities(ctx context.Context, req *dialogflowpb.BatchCreateEntitiesRequest, opts ...gax.CallOption) (*BatchCreateEntitiesOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/entities:batchCreate", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &BatchCreateEntitiesOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// BatchUpdateEntities updates or creates multiple entities in the specified entity type. This +// method does not affect entities in the entity type that aren’t explicitly +// specified in the request. +// +// This method is a long-running +// operation (at https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). +// The returned Operation type has the following method-specific fields: +// +// metadata: An empty Struct +// message (at https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) +// +// response: An Empty +// message (at https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) +// +// Note: You should always train an agent prior to sending it queries. See the +// training +// documentation (at https://cloud.google.com/dialogflow/es/docs/training). +func (c *entityTypesRESTClient) BatchUpdateEntities(ctx context.Context, req *dialogflowpb.BatchUpdateEntitiesRequest, opts ...gax.CallOption) (*BatchUpdateEntitiesOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/entities:batchUpdate", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &BatchUpdateEntitiesOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// BatchDeleteEntities deletes entities in the specified entity type. +// +// This method is a long-running +// operation (at https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). +// The returned Operation type has the following method-specific fields: +// +// metadata: An empty Struct +// message (at https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) +// +// response: An Empty +// message (at https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) +// +// Note: You should always train an agent prior to sending it queries. See the +// training +// documentation (at https://cloud.google.com/dialogflow/es/docs/training). +func (c *entityTypesRESTClient) BatchDeleteEntities(ctx context.Context, req *dialogflowpb.BatchDeleteEntitiesRequest, opts ...gax.CallOption) (*BatchDeleteEntitiesOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/entities:batchDelete", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &BatchDeleteEntitiesOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetLocation gets information about a location. +func (c *entityTypesRESTClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *entityTypesRESTClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *entityTypesRESTClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *entityTypesRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *entityTypesRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// BatchCreateEntitiesOperation manages a long-running operation from BatchCreateEntities. +type BatchCreateEntitiesOperation struct { + lro *longrunning.Operation + pollPath string +} + +// BatchCreateEntitiesOperation returns a new BatchCreateEntitiesOperation from a given name. +// The name must be that of a previously created BatchCreateEntitiesOperation, possibly from a different process. +func (c *entityTypesGRPCClient) BatchCreateEntitiesOperation(name string) *BatchCreateEntitiesOperation { + return &BatchCreateEntitiesOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// BatchCreateEntitiesOperation returns a new BatchCreateEntitiesOperation from a given name. +// The name must be that of a previously created BatchCreateEntitiesOperation, possibly from a different process. +func (c *entityTypesRESTClient) BatchCreateEntitiesOperation(name string) *BatchCreateEntitiesOperation { + override := fmt.Sprintf("/v2/%s", name) + return &BatchCreateEntitiesOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *BatchCreateEntitiesOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *BatchCreateEntitiesOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + return op.lro.Poll(ctx, nil, opts...) +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *BatchCreateEntitiesOperation) Metadata() (*structpb.Struct, error) { + var meta structpb.Struct + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *BatchCreateEntitiesOperation) Done() bool { + return op.lro.Done() +} + +// 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 *BatchCreateEntitiesOperation) Name() string { + return op.lro.Name() +} + +// BatchDeleteEntitiesOperation manages a long-running operation from BatchDeleteEntities. +type BatchDeleteEntitiesOperation struct { + lro *longrunning.Operation + pollPath string +} + +// BatchDeleteEntitiesOperation returns a new BatchDeleteEntitiesOperation from a given name. +// The name must be that of a previously created BatchDeleteEntitiesOperation, possibly from a different process. +func (c *entityTypesGRPCClient) BatchDeleteEntitiesOperation(name string) *BatchDeleteEntitiesOperation { + return &BatchDeleteEntitiesOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// BatchDeleteEntitiesOperation returns a new BatchDeleteEntitiesOperation from a given name. +// The name must be that of a previously created BatchDeleteEntitiesOperation, possibly from a different process. +func (c *entityTypesRESTClient) BatchDeleteEntitiesOperation(name string) *BatchDeleteEntitiesOperation { + override := fmt.Sprintf("/v2/%s", name) + return &BatchDeleteEntitiesOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *BatchDeleteEntitiesOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. // // 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. @@ -1025,6 +2345,7 @@ func (op *BatchDeleteEntitiesOperation) Wait(ctx context.Context, opts ...gax.Ca // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *BatchDeleteEntitiesOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -1055,7 +2376,8 @@ func (op *BatchDeleteEntitiesOperation) Name() string { // BatchDeleteEntityTypesOperation manages a long-running operation from BatchDeleteEntityTypes. type BatchDeleteEntityTypesOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // BatchDeleteEntityTypesOperation returns a new BatchDeleteEntityTypesOperation from a given name. @@ -1066,10 +2388,21 @@ func (c *entityTypesGRPCClient) BatchDeleteEntityTypesOperation(name string) *Ba } } +// BatchDeleteEntityTypesOperation returns a new BatchDeleteEntityTypesOperation from a given name. +// The name must be that of a previously created BatchDeleteEntityTypesOperation, possibly from a different process. +func (c *entityTypesRESTClient) BatchDeleteEntityTypesOperation(name string) *BatchDeleteEntityTypesOperation { + override := fmt.Sprintf("/v2/%s", name) + return &BatchDeleteEntityTypesOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *BatchDeleteEntityTypesOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -1083,6 +2416,7 @@ func (op *BatchDeleteEntityTypesOperation) Wait(ctx context.Context, opts ...gax // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *BatchDeleteEntityTypesOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -1113,7 +2447,8 @@ func (op *BatchDeleteEntityTypesOperation) Name() string { // BatchUpdateEntitiesOperation manages a long-running operation from BatchUpdateEntities. type BatchUpdateEntitiesOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // BatchUpdateEntitiesOperation returns a new BatchUpdateEntitiesOperation from a given name. @@ -1124,10 +2459,21 @@ func (c *entityTypesGRPCClient) BatchUpdateEntitiesOperation(name string) *Batch } } +// BatchUpdateEntitiesOperation returns a new BatchUpdateEntitiesOperation from a given name. +// The name must be that of a previously created BatchUpdateEntitiesOperation, possibly from a different process. +func (c *entityTypesRESTClient) BatchUpdateEntitiesOperation(name string) *BatchUpdateEntitiesOperation { + override := fmt.Sprintf("/v2/%s", name) + return &BatchUpdateEntitiesOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *BatchUpdateEntitiesOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -1141,6 +2487,7 @@ func (op *BatchUpdateEntitiesOperation) Wait(ctx context.Context, opts ...gax.Ca // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *BatchUpdateEntitiesOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -1171,7 +2518,8 @@ func (op *BatchUpdateEntitiesOperation) Name() string { // BatchUpdateEntityTypesOperation manages a long-running operation from BatchUpdateEntityTypes. type BatchUpdateEntityTypesOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // BatchUpdateEntityTypesOperation returns a new BatchUpdateEntityTypesOperation from a given name. @@ -1182,10 +2530,21 @@ func (c *entityTypesGRPCClient) BatchUpdateEntityTypesOperation(name string) *Ba } } +// BatchUpdateEntityTypesOperation returns a new BatchUpdateEntityTypesOperation from a given name. +// The name must be that of a previously created BatchUpdateEntityTypesOperation, possibly from a different process. +func (c *entityTypesRESTClient) BatchUpdateEntityTypesOperation(name string) *BatchUpdateEntityTypesOperation { + override := fmt.Sprintf("/v2/%s", name) + return &BatchUpdateEntityTypesOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *BatchUpdateEntityTypesOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*dialogflowpb.BatchUpdateEntityTypesResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp dialogflowpb.BatchUpdateEntityTypesResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1203,6 +2562,7 @@ func (op *BatchUpdateEntityTypesOperation) Wait(ctx context.Context, opts ...gax // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *BatchUpdateEntityTypesOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*dialogflowpb.BatchUpdateEntityTypesResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp dialogflowpb.BatchUpdateEntityTypesResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/dialogflow/apiv2/entity_types_client_example_test.go b/dialogflow/apiv2/entity_types_client_example_test.go index 46f8a3f0ba76..203bbbe9aea4 100644 --- a/dialogflow/apiv2/entity_types_client_example_test.go +++ b/dialogflow/apiv2/entity_types_client_example_test.go @@ -43,6 +43,23 @@ func ExampleNewEntityTypesClient() { _ = c } +func ExampleNewEntityTypesRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := dialogflow.NewEntityTypesRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleEntityTypesClient_ListEntityTypes() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/dialogflow/apiv2/environments_client.go b/dialogflow/apiv2/environments_client.go index 1cd254cbf893..26bdef343527 100644 --- a/dialogflow/apiv2/environments_client.go +++ b/dialogflow/apiv2/environments_client.go @@ -17,23 +17,29 @@ package dialogflow import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" dialogflowpb "cloud.google.com/go/dialogflow/apiv2/dialogflowpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -142,6 +148,76 @@ func defaultEnvironmentsCallOptions() *EnvironmentsCallOptions { } } +func defaultEnvironmentsRESTCallOptions() *EnvironmentsCallOptions { + return &EnvironmentsCallOptions{ + ListEnvironments: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetEnvironment: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateEnvironment: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UpdateEnvironment: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeleteEnvironment: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetEnvironmentHistory: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + CancelOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalEnvironmentsClient is an interface that defines the methods available from Dialogflow API. type internalEnvironmentsClient interface { Close() error @@ -348,6 +424,74 @@ func (c *environmentsGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type environmentsRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing EnvironmentsClient + CallOptions **EnvironmentsCallOptions +} + +// NewEnvironmentsRESTClient creates a new environments rest client. +// +// Service for managing Environments. +func NewEnvironmentsRESTClient(ctx context.Context, opts ...option.ClientOption) (*EnvironmentsClient, error) { + clientOpts := append(defaultEnvironmentsRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultEnvironmentsRESTCallOptions() + c := &environmentsRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &EnvironmentsClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultEnvironmentsRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://dialogflow.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://dialogflow.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://dialogflow.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *environmentsRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *environmentsRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *environmentsRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *environmentsGRPCClient) ListEnvironments(ctx context.Context, req *dialogflowpb.ListEnvironmentsRequest, opts ...gax.CallOption) *EnvironmentIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -659,6 +803,770 @@ func (c *environmentsGRPCClient) ListOperations(ctx context.Context, req *longru return it } +// ListEnvironments returns the list of all non-default environments of the specified agent. +func (c *environmentsRESTClient) ListEnvironments(ctx context.Context, req *dialogflowpb.ListEnvironmentsRequest, opts ...gax.CallOption) *EnvironmentIterator { + it := &EnvironmentIterator{} + req = proto.Clone(req).(*dialogflowpb.ListEnvironmentsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*dialogflowpb.Environment, string, error) { + resp := &dialogflowpb.ListEnvironmentsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/environments", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetEnvironments(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetEnvironment retrieves the specified agent environment. +func (c *environmentsRESTClient) GetEnvironment(ctx context.Context, req *dialogflowpb.GetEnvironmentRequest, opts ...gax.CallOption) (*dialogflowpb.Environment, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetEnvironment[0:len((*c.CallOptions).GetEnvironment):len((*c.CallOptions).GetEnvironment)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dialogflowpb.Environment{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateEnvironment creates an agent environment. +func (c *environmentsRESTClient) CreateEnvironment(ctx context.Context, req *dialogflowpb.CreateEnvironmentRequest, opts ...gax.CallOption) (*dialogflowpb.Environment, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetEnvironment() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/environments", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("environmentId", fmt.Sprintf("%v", req.GetEnvironmentId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateEnvironment[0:len((*c.CallOptions).CreateEnvironment):len((*c.CallOptions).CreateEnvironment)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dialogflowpb.Environment{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateEnvironment updates the specified agent environment. +// +// This method allows you to deploy new agent versions into the environment. +// When an environment is pointed to a new agent version by setting +// environment.agent_version, the environment is temporarily set to the +// LOADING state. During that time, the environment continues serving the +// previous version of the agent. After the new agent version is done loading, +// the environment is set back to the RUNNING state. +// You can use “-” as Environment ID in environment name to update an agent +// version in the default environment. WARNING: this will negate all recent +// changes to the draft agent and can’t be undone. You may want to save the +// draft agent to a version before calling this method. +func (c *environmentsRESTClient) UpdateEnvironment(ctx context.Context, req *dialogflowpb.UpdateEnvironmentRequest, opts ...gax.CallOption) (*dialogflowpb.Environment, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetEnvironment() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetEnvironment().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetAllowLoadToDraftAndDiscardChanges() { + params.Add("allowLoadToDraftAndDiscardChanges", fmt.Sprintf("%v", req.GetAllowLoadToDraftAndDiscardChanges())) + } + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "environment.name", url.QueryEscape(req.GetEnvironment().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateEnvironment[0:len((*c.CallOptions).UpdateEnvironment):len((*c.CallOptions).UpdateEnvironment)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dialogflowpb.Environment{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteEnvironment deletes the specified agent environment. +func (c *environmentsRESTClient) DeleteEnvironment(ctx context.Context, req *dialogflowpb.DeleteEnvironmentRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetEnvironmentHistory gets the history of the specified environment. +func (c *environmentsRESTClient) GetEnvironmentHistory(ctx context.Context, req *dialogflowpb.GetEnvironmentHistoryRequest, opts ...gax.CallOption) *EnvironmentHistory_EntryIterator { + it := &EnvironmentHistory_EntryIterator{} + req = proto.Clone(req).(*dialogflowpb.GetEnvironmentHistoryRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*dialogflowpb.EnvironmentHistory_Entry, string, error) { + resp := &dialogflowpb.EnvironmentHistory{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/history", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetEntries(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetLocation gets information about a location. +func (c *environmentsRESTClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *environmentsRESTClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *environmentsRESTClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *environmentsRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *environmentsRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + // EnvironmentHistory_EntryIterator manages a stream of *dialogflowpb.EnvironmentHistory_Entry. type EnvironmentHistory_EntryIterator struct { items []*dialogflowpb.EnvironmentHistory_Entry diff --git a/dialogflow/apiv2/environments_client_example_test.go b/dialogflow/apiv2/environments_client_example_test.go index 8910a3ccc3c5..7f900e088845 100644 --- a/dialogflow/apiv2/environments_client_example_test.go +++ b/dialogflow/apiv2/environments_client_example_test.go @@ -43,6 +43,23 @@ func ExampleNewEnvironmentsClient() { _ = c } +func ExampleNewEnvironmentsRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := dialogflow.NewEnvironmentsRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleEnvironmentsClient_ListEnvironments() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/dialogflow/apiv2/fulfillments_client.go b/dialogflow/apiv2/fulfillments_client.go index d26c3ac62c90..39344ae3937f 100644 --- a/dialogflow/apiv2/fulfillments_client.go +++ b/dialogflow/apiv2/fulfillments_client.go @@ -17,23 +17,29 @@ package dialogflow import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" dialogflowpb "cloud.google.com/go/dialogflow/apiv2/dialogflowpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -94,6 +100,36 @@ func defaultFulfillmentsCallOptions() *FulfillmentsCallOptions { } } +func defaultFulfillmentsRESTCallOptions() *FulfillmentsCallOptions { + return &FulfillmentsCallOptions{ + GetFulfillment: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UpdateFulfillment: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + CancelOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalFulfillmentsClient is an interface that defines the methods available from Dialogflow API. type internalFulfillmentsClient interface { Close() error @@ -265,6 +301,74 @@ func (c *fulfillmentsGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type fulfillmentsRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing FulfillmentsClient + CallOptions **FulfillmentsCallOptions +} + +// NewFulfillmentsRESTClient creates a new fulfillments rest client. +// +// Service for managing Fulfillments. +func NewFulfillmentsRESTClient(ctx context.Context, opts ...option.ClientOption) (*FulfillmentsClient, error) { + clientOpts := append(defaultFulfillmentsRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultFulfillmentsRESTCallOptions() + c := &fulfillmentsRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &FulfillmentsClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultFulfillmentsRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://dialogflow.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://dialogflow.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://dialogflow.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *fulfillmentsRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *fulfillmentsRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *fulfillmentsRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *fulfillmentsGRPCClient) GetFulfillment(ctx context.Context, req *dialogflowpb.GetFulfillmentRequest, opts ...gax.CallOption) (*dialogflowpb.Fulfillment, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) @@ -445,3 +549,471 @@ func (c *fulfillmentsGRPCClient) ListOperations(ctx context.Context, req *longru return it } + +// GetFulfillment retrieves the fulfillment. +func (c *fulfillmentsRESTClient) GetFulfillment(ctx context.Context, req *dialogflowpb.GetFulfillmentRequest, opts ...gax.CallOption) (*dialogflowpb.Fulfillment, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetFulfillment[0:len((*c.CallOptions).GetFulfillment):len((*c.CallOptions).GetFulfillment)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dialogflowpb.Fulfillment{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateFulfillment updates the fulfillment. +func (c *fulfillmentsRESTClient) UpdateFulfillment(ctx context.Context, req *dialogflowpb.UpdateFulfillmentRequest, opts ...gax.CallOption) (*dialogflowpb.Fulfillment, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetFulfillment() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetFulfillment().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "fulfillment.name", url.QueryEscape(req.GetFulfillment().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateFulfillment[0:len((*c.CallOptions).UpdateFulfillment):len((*c.CallOptions).UpdateFulfillment)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dialogflowpb.Fulfillment{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetLocation gets information about a location. +func (c *fulfillmentsRESTClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *fulfillmentsRESTClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *fulfillmentsRESTClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *fulfillmentsRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *fulfillmentsRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} diff --git a/dialogflow/apiv2/fulfillments_client_example_test.go b/dialogflow/apiv2/fulfillments_client_example_test.go index 11917d5b6b1d..dc70ddce476d 100644 --- a/dialogflow/apiv2/fulfillments_client_example_test.go +++ b/dialogflow/apiv2/fulfillments_client_example_test.go @@ -43,6 +43,23 @@ func ExampleNewFulfillmentsClient() { _ = c } +func ExampleNewFulfillmentsRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := dialogflow.NewFulfillmentsRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleFulfillmentsClient_GetFulfillment() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/dialogflow/apiv2/gapic_metadata.json b/dialogflow/apiv2/gapic_metadata.json index 695beabb18bd..47aa6f6434be 100644 --- a/dialogflow/apiv2/gapic_metadata.json +++ b/dialogflow/apiv2/gapic_metadata.json @@ -81,6 +81,81 @@ ] } } + }, + "rest": { + "libraryClient": "AgentsClient", + "rpcs": { + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "DeleteAgent": { + "methods": [ + "DeleteAgent" + ] + }, + "ExportAgent": { + "methods": [ + "ExportAgent" + ] + }, + "GetAgent": { + "methods": [ + "GetAgent" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "GetValidationResult": { + "methods": [ + "GetValidationResult" + ] + }, + "ImportAgent": { + "methods": [ + "ImportAgent" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "RestoreAgent": { + "methods": [ + "RestoreAgent" + ] + }, + "SearchAgents": { + "methods": [ + "SearchAgents" + ] + }, + "SetAgent": { + "methods": [ + "SetAgent" + ] + }, + "TrainAgent": { + "methods": [ + "TrainAgent" + ] + } + } } } }, @@ -125,6 +200,46 @@ ] } } + }, + "rest": { + "libraryClient": "AnswerRecordsClient", + "rpcs": { + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ListAnswerRecords": { + "methods": [ + "ListAnswerRecords" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "UpdateAnswerRecord": { + "methods": [ + "UpdateAnswerRecord" + ] + } + } } } }, @@ -189,6 +304,66 @@ ] } } + }, + "rest": { + "libraryClient": "ContextsClient", + "rpcs": { + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "CreateContext": { + "methods": [ + "CreateContext" + ] + }, + "DeleteAllContexts": { + "methods": [ + "DeleteAllContexts" + ] + }, + "DeleteContext": { + "methods": [ + "DeleteContext" + ] + }, + "GetContext": { + "methods": [ + "GetContext" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ListContexts": { + "methods": [ + "ListContexts" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "UpdateContext": { + "methods": [ + "UpdateContext" + ] + } + } } } }, @@ -248,6 +423,61 @@ ] } } + }, + "rest": { + "libraryClient": "ConversationDatasetsClient", + "rpcs": { + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "CreateConversationDataset": { + "methods": [ + "CreateConversationDataset" + ] + }, + "DeleteConversationDataset": { + "methods": [ + "DeleteConversationDataset" + ] + }, + "GetConversationDataset": { + "methods": [ + "GetConversationDataset" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ImportConversationData": { + "methods": [ + "ImportConversationData" + ] + }, + "ListConversationDatasets": { + "methods": [ + "ListConversationDatasets" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + } + } } } }, @@ -273,22 +503,658 @@ }, "DeleteConversationModel": { "methods": [ - "DeleteConversationModel" + "DeleteConversationModel" + ] + }, + "DeployConversationModel": { + "methods": [ + "DeployConversationModel" + ] + }, + "GetConversationModel": { + "methods": [ + "GetConversationModel" + ] + }, + "GetConversationModelEvaluation": { + "methods": [ + "GetConversationModelEvaluation" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ListConversationModelEvaluations": { + "methods": [ + "ListConversationModelEvaluations" + ] + }, + "ListConversationModels": { + "methods": [ + "ListConversationModels" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "UndeployConversationModel": { + "methods": [ + "UndeployConversationModel" + ] + } + } + }, + "rest": { + "libraryClient": "ConversationModelsClient", + "rpcs": { + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "CreateConversationModel": { + "methods": [ + "CreateConversationModel" + ] + }, + "CreateConversationModelEvaluation": { + "methods": [ + "CreateConversationModelEvaluation" + ] + }, + "DeleteConversationModel": { + "methods": [ + "DeleteConversationModel" + ] + }, + "DeployConversationModel": { + "methods": [ + "DeployConversationModel" + ] + }, + "GetConversationModel": { + "methods": [ + "GetConversationModel" + ] + }, + "GetConversationModelEvaluation": { + "methods": [ + "GetConversationModelEvaluation" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ListConversationModelEvaluations": { + "methods": [ + "ListConversationModelEvaluations" + ] + }, + "ListConversationModels": { + "methods": [ + "ListConversationModels" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "UndeployConversationModel": { + "methods": [ + "UndeployConversationModel" + ] + } + } + } + } + }, + "ConversationProfiles": { + "clients": { + "grpc": { + "libraryClient": "ConversationProfilesClient", + "rpcs": { + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "ClearSuggestionFeatureConfig": { + "methods": [ + "ClearSuggestionFeatureConfig" + ] + }, + "CreateConversationProfile": { + "methods": [ + "CreateConversationProfile" + ] + }, + "DeleteConversationProfile": { + "methods": [ + "DeleteConversationProfile" + ] + }, + "GetConversationProfile": { + "methods": [ + "GetConversationProfile" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ListConversationProfiles": { + "methods": [ + "ListConversationProfiles" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "SetSuggestionFeatureConfig": { + "methods": [ + "SetSuggestionFeatureConfig" + ] + }, + "UpdateConversationProfile": { + "methods": [ + "UpdateConversationProfile" + ] + } + } + }, + "rest": { + "libraryClient": "ConversationProfilesClient", + "rpcs": { + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "ClearSuggestionFeatureConfig": { + "methods": [ + "ClearSuggestionFeatureConfig" + ] + }, + "CreateConversationProfile": { + "methods": [ + "CreateConversationProfile" + ] + }, + "DeleteConversationProfile": { + "methods": [ + "DeleteConversationProfile" + ] + }, + "GetConversationProfile": { + "methods": [ + "GetConversationProfile" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ListConversationProfiles": { + "methods": [ + "ListConversationProfiles" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "SetSuggestionFeatureConfig": { + "methods": [ + "SetSuggestionFeatureConfig" + ] + }, + "UpdateConversationProfile": { + "methods": [ + "UpdateConversationProfile" + ] + } + } + } + } + }, + "Conversations": { + "clients": { + "grpc": { + "libraryClient": "ConversationsClient", + "rpcs": { + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "CompleteConversation": { + "methods": [ + "CompleteConversation" + ] + }, + "CreateConversation": { + "methods": [ + "CreateConversation" + ] + }, + "GetConversation": { + "methods": [ + "GetConversation" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ListConversations": { + "methods": [ + "ListConversations" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListMessages": { + "methods": [ + "ListMessages" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + } + } + }, + "rest": { + "libraryClient": "ConversationsClient", + "rpcs": { + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "CompleteConversation": { + "methods": [ + "CompleteConversation" + ] + }, + "CreateConversation": { + "methods": [ + "CreateConversation" + ] + }, + "GetConversation": { + "methods": [ + "GetConversation" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ListConversations": { + "methods": [ + "ListConversations" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListMessages": { + "methods": [ + "ListMessages" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + } + } + } + } + }, + "Documents": { + "clients": { + "grpc": { + "libraryClient": "DocumentsClient", + "rpcs": { + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "CreateDocument": { + "methods": [ + "CreateDocument" + ] + }, + "DeleteDocument": { + "methods": [ + "DeleteDocument" + ] + }, + "ExportDocument": { + "methods": [ + "ExportDocument" + ] + }, + "GetDocument": { + "methods": [ + "GetDocument" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ImportDocuments": { + "methods": [ + "ImportDocuments" + ] + }, + "ListDocuments": { + "methods": [ + "ListDocuments" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "ReloadDocument": { + "methods": [ + "ReloadDocument" + ] + }, + "UpdateDocument": { + "methods": [ + "UpdateDocument" + ] + } + } + }, + "rest": { + "libraryClient": "DocumentsClient", + "rpcs": { + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "CreateDocument": { + "methods": [ + "CreateDocument" + ] + }, + "DeleteDocument": { + "methods": [ + "DeleteDocument" + ] + }, + "ExportDocument": { + "methods": [ + "ExportDocument" + ] + }, + "GetDocument": { + "methods": [ + "GetDocument" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ImportDocuments": { + "methods": [ + "ImportDocuments" + ] + }, + "ListDocuments": { + "methods": [ + "ListDocuments" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "ReloadDocument": { + "methods": [ + "ReloadDocument" + ] + }, + "UpdateDocument": { + "methods": [ + "UpdateDocument" + ] + } + } + } + } + }, + "EntityTypes": { + "clients": { + "grpc": { + "libraryClient": "EntityTypesClient", + "rpcs": { + "BatchCreateEntities": { + "methods": [ + "BatchCreateEntities" + ] + }, + "BatchDeleteEntities": { + "methods": [ + "BatchDeleteEntities" + ] + }, + "BatchDeleteEntityTypes": { + "methods": [ + "BatchDeleteEntityTypes" + ] + }, + "BatchUpdateEntities": { + "methods": [ + "BatchUpdateEntities" + ] + }, + "BatchUpdateEntityTypes": { + "methods": [ + "BatchUpdateEntityTypes" + ] + }, + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "CreateEntityType": { + "methods": [ + "CreateEntityType" + ] + }, + "DeleteEntityType": { + "methods": [ + "DeleteEntityType" + ] + }, + "GetEntityType": { + "methods": [ + "GetEntityType" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ListEntityTypes": { + "methods": [ + "ListEntityTypes" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "UpdateEntityType": { + "methods": [ + "UpdateEntityType" + ] + } + } + }, + "rest": { + "libraryClient": "EntityTypesClient", + "rpcs": { + "BatchCreateEntities": { + "methods": [ + "BatchCreateEntities" + ] + }, + "BatchDeleteEntities": { + "methods": [ + "BatchDeleteEntities" + ] + }, + "BatchDeleteEntityTypes": { + "methods": [ + "BatchDeleteEntityTypes" + ] + }, + "BatchUpdateEntities": { + "methods": [ + "BatchUpdateEntities" + ] + }, + "BatchUpdateEntityTypes": { + "methods": [ + "BatchUpdateEntityTypes" + ] + }, + "CancelOperation": { + "methods": [ + "CancelOperation" ] }, - "DeployConversationModel": { + "CreateEntityType": { "methods": [ - "DeployConversationModel" + "CreateEntityType" ] }, - "GetConversationModel": { + "DeleteEntityType": { "methods": [ - "GetConversationModel" + "DeleteEntityType" ] }, - "GetConversationModelEvaluation": { + "GetEntityType": { "methods": [ - "GetConversationModelEvaluation" + "GetEntityType" ] }, "GetLocation": { @@ -301,14 +1167,9 @@ "GetOperation" ] }, - "ListConversationModelEvaluations": { - "methods": [ - "ListConversationModelEvaluations" - ] - }, - "ListConversationModels": { + "ListEntityTypes": { "methods": [ - "ListConversationModels" + "ListEntityTypes" ] }, "ListLocations": { @@ -321,43 +1182,43 @@ "ListOperations" ] }, - "UndeployConversationModel": { + "UpdateEntityType": { "methods": [ - "UndeployConversationModel" + "UpdateEntityType" ] } } } } }, - "ConversationProfiles": { + "Environments": { "clients": { "grpc": { - "libraryClient": "ConversationProfilesClient", + "libraryClient": "EnvironmentsClient", "rpcs": { "CancelOperation": { "methods": [ "CancelOperation" ] }, - "ClearSuggestionFeatureConfig": { + "CreateEnvironment": { "methods": [ - "ClearSuggestionFeatureConfig" + "CreateEnvironment" ] }, - "CreateConversationProfile": { + "DeleteEnvironment": { "methods": [ - "CreateConversationProfile" + "DeleteEnvironment" ] }, - "DeleteConversationProfile": { + "GetEnvironment": { "methods": [ - "DeleteConversationProfile" + "GetEnvironment" ] }, - "GetConversationProfile": { + "GetEnvironmentHistory": { "methods": [ - "GetConversationProfile" + "GetEnvironmentHistory" ] }, "GetLocation": { @@ -370,9 +1231,9 @@ "GetOperation" ] }, - "ListConversationProfiles": { + "ListEnvironments": { "methods": [ - "ListConversationProfiles" + "ListEnvironments" ] }, "ListLocations": { @@ -385,43 +1246,39 @@ "ListOperations" ] }, - "SetSuggestionFeatureConfig": { - "methods": [ - "SetSuggestionFeatureConfig" - ] - }, - "UpdateConversationProfile": { + "UpdateEnvironment": { "methods": [ - "UpdateConversationProfile" + "UpdateEnvironment" ] } } - } - } - }, - "Conversations": { - "clients": { - "grpc": { - "libraryClient": "ConversationsClient", + }, + "rest": { + "libraryClient": "EnvironmentsClient", "rpcs": { "CancelOperation": { "methods": [ "CancelOperation" ] }, - "CompleteConversation": { + "CreateEnvironment": { "methods": [ - "CompleteConversation" + "CreateEnvironment" ] }, - "CreateConversation": { + "DeleteEnvironment": { "methods": [ - "CreateConversation" + "DeleteEnvironment" ] }, - "GetConversation": { + "GetEnvironment": { "methods": [ - "GetConversation" + "GetEnvironment" + ] + }, + "GetEnvironmentHistory": { + "methods": [ + "GetEnvironmentHistory" ] }, "GetLocation": { @@ -434,9 +1291,9 @@ "GetOperation" ] }, - "ListConversations": { + "ListEnvironments": { "methods": [ - "ListConversations" + "ListEnvironments" ] }, "ListLocations": { @@ -444,68 +1301,83 @@ "ListLocations" ] }, - "ListMessages": { + "ListOperations": { "methods": [ - "ListMessages" + "ListOperations" ] }, - "ListOperations": { + "UpdateEnvironment": { "methods": [ - "ListOperations" + "UpdateEnvironment" ] } } } } }, - "Documents": { + "Fulfillments": { "clients": { "grpc": { - "libraryClient": "DocumentsClient", + "libraryClient": "FulfillmentsClient", "rpcs": { "CancelOperation": { "methods": [ "CancelOperation" ] }, - "CreateDocument": { + "GetFulfillment": { "methods": [ - "CreateDocument" + "GetFulfillment" ] }, - "DeleteDocument": { + "GetLocation": { "methods": [ - "DeleteDocument" + "GetLocation" ] }, - "ExportDocument": { + "GetOperation": { "methods": [ - "ExportDocument" + "GetOperation" ] }, - "GetDocument": { + "ListLocations": { "methods": [ - "GetDocument" + "ListLocations" ] }, - "GetLocation": { + "ListOperations": { "methods": [ - "GetLocation" + "ListOperations" ] }, - "GetOperation": { + "UpdateFulfillment": { "methods": [ - "GetOperation" + "UpdateFulfillment" + ] + } + } + }, + "rest": { + "libraryClient": "FulfillmentsClient", + "rpcs": { + "CancelOperation": { + "methods": [ + "CancelOperation" ] }, - "ImportDocuments": { + "GetFulfillment": { "methods": [ - "ImportDocuments" + "GetFulfillment" ] }, - "ListDocuments": { + "GetLocation": { "methods": [ - "ListDocuments" + "GetLocation" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" ] }, "ListLocations": { @@ -518,48 +1390,28 @@ "ListOperations" ] }, - "ReloadDocument": { - "methods": [ - "ReloadDocument" - ] - }, - "UpdateDocument": { + "UpdateFulfillment": { "methods": [ - "UpdateDocument" + "UpdateFulfillment" ] } } } } }, - "EntityTypes": { + "Intents": { "clients": { "grpc": { - "libraryClient": "EntityTypesClient", + "libraryClient": "IntentsClient", "rpcs": { - "BatchCreateEntities": { - "methods": [ - "BatchCreateEntities" - ] - }, - "BatchDeleteEntities": { - "methods": [ - "BatchDeleteEntities" - ] - }, - "BatchDeleteEntityTypes": { - "methods": [ - "BatchDeleteEntityTypes" - ] - }, - "BatchUpdateEntities": { + "BatchDeleteIntents": { "methods": [ - "BatchUpdateEntities" + "BatchDeleteIntents" ] }, - "BatchUpdateEntityTypes": { + "BatchUpdateIntents": { "methods": [ - "BatchUpdateEntityTypes" + "BatchUpdateIntents" ] }, "CancelOperation": { @@ -567,19 +1419,19 @@ "CancelOperation" ] }, - "CreateEntityType": { + "CreateIntent": { "methods": [ - "CreateEntityType" + "CreateIntent" ] }, - "DeleteEntityType": { + "DeleteIntent": { "methods": [ - "DeleteEntityType" + "DeleteIntent" ] }, - "GetEntityType": { + "GetIntent": { "methods": [ - "GetEntityType" + "GetIntent" ] }, "GetLocation": { @@ -592,9 +1444,9 @@ "GetOperation" ] }, - "ListEntityTypes": { + "ListIntents": { "methods": [ - "ListEntityTypes" + "ListIntents" ] }, "ListLocations": { @@ -607,43 +1459,44 @@ "ListOperations" ] }, - "UpdateEntityType": { + "UpdateIntent": { "methods": [ - "UpdateEntityType" + "UpdateIntent" ] } } - } - } - }, - "Environments": { - "clients": { - "grpc": { - "libraryClient": "EnvironmentsClient", + }, + "rest": { + "libraryClient": "IntentsClient", "rpcs": { - "CancelOperation": { + "BatchDeleteIntents": { "methods": [ - "CancelOperation" + "BatchDeleteIntents" ] }, - "CreateEnvironment": { + "BatchUpdateIntents": { "methods": [ - "CreateEnvironment" + "BatchUpdateIntents" ] }, - "DeleteEnvironment": { + "CancelOperation": { "methods": [ - "DeleteEnvironment" + "CancelOperation" ] }, - "GetEnvironment": { + "CreateIntent": { "methods": [ - "GetEnvironment" + "CreateIntent" ] }, - "GetEnvironmentHistory": { + "DeleteIntent": { "methods": [ - "GetEnvironmentHistory" + "DeleteIntent" + ] + }, + "GetIntent": { + "methods": [ + "GetIntent" ] }, "GetLocation": { @@ -656,9 +1509,9 @@ "GetOperation" ] }, - "ListEnvironments": { + "ListIntents": { "methods": [ - "ListEnvironments" + "ListIntents" ] }, "ListLocations": { @@ -671,28 +1524,38 @@ "ListOperations" ] }, - "UpdateEnvironment": { + "UpdateIntent": { "methods": [ - "UpdateEnvironment" + "UpdateIntent" ] } } } } }, - "Fulfillments": { + "KnowledgeBases": { "clients": { "grpc": { - "libraryClient": "FulfillmentsClient", + "libraryClient": "KnowledgeBasesClient", "rpcs": { "CancelOperation": { "methods": [ "CancelOperation" ] }, - "GetFulfillment": { + "CreateKnowledgeBase": { + "methods": [ + "CreateKnowledgeBase" + ] + }, + "DeleteKnowledgeBase": { + "methods": [ + "DeleteKnowledgeBase" + ] + }, + "GetKnowledgeBase": { "methods": [ - "GetFulfillment" + "GetKnowledgeBase" ] }, "GetLocation": { @@ -705,6 +1568,11 @@ "GetOperation" ] }, + "ListKnowledgeBases": { + "methods": [ + "ListKnowledgeBases" + ] + }, "ListLocations": { "methods": [ "ListLocations" @@ -715,48 +1583,34 @@ "ListOperations" ] }, - "UpdateFulfillment": { + "UpdateKnowledgeBase": { "methods": [ - "UpdateFulfillment" + "UpdateKnowledgeBase" ] } } - } - } - }, - "Intents": { - "clients": { - "grpc": { - "libraryClient": "IntentsClient", + }, + "rest": { + "libraryClient": "KnowledgeBasesClient", "rpcs": { - "BatchDeleteIntents": { - "methods": [ - "BatchDeleteIntents" - ] - }, - "BatchUpdateIntents": { - "methods": [ - "BatchUpdateIntents" - ] - }, "CancelOperation": { "methods": [ "CancelOperation" ] }, - "CreateIntent": { + "CreateKnowledgeBase": { "methods": [ - "CreateIntent" + "CreateKnowledgeBase" ] }, - "DeleteIntent": { + "DeleteKnowledgeBase": { "methods": [ - "DeleteIntent" + "DeleteKnowledgeBase" ] }, - "GetIntent": { + "GetKnowledgeBase": { "methods": [ - "GetIntent" + "GetKnowledgeBase" ] }, "GetLocation": { @@ -769,9 +1623,9 @@ "GetOperation" ] }, - "ListIntents": { + "ListKnowledgeBases": { "methods": [ - "ListIntents" + "ListKnowledgeBases" ] }, "ListLocations": { @@ -784,38 +1638,33 @@ "ListOperations" ] }, - "UpdateIntent": { + "UpdateKnowledgeBase": { "methods": [ - "UpdateIntent" + "UpdateKnowledgeBase" ] } } } } }, - "KnowledgeBases": { + "Participants": { "clients": { "grpc": { - "libraryClient": "KnowledgeBasesClient", + "libraryClient": "ParticipantsClient", "rpcs": { - "CancelOperation": { - "methods": [ - "CancelOperation" - ] - }, - "CreateKnowledgeBase": { + "AnalyzeContent": { "methods": [ - "CreateKnowledgeBase" + "AnalyzeContent" ] }, - "DeleteKnowledgeBase": { + "CancelOperation": { "methods": [ - "DeleteKnowledgeBase" + "CancelOperation" ] }, - "GetKnowledgeBase": { + "CreateParticipant": { "methods": [ - "GetKnowledgeBase" + "CreateParticipant" ] }, "GetLocation": { @@ -828,9 +1677,9 @@ "GetOperation" ] }, - "ListKnowledgeBases": { + "GetParticipant": { "methods": [ - "ListKnowledgeBases" + "GetParticipant" ] }, "ListLocations": { @@ -843,18 +1692,39 @@ "ListOperations" ] }, - "UpdateKnowledgeBase": { + "ListParticipants": { "methods": [ - "UpdateKnowledgeBase" + "ListParticipants" + ] + }, + "StreamingAnalyzeContent": { + "methods": [ + "StreamingAnalyzeContent" + ] + }, + "SuggestArticles": { + "methods": [ + "SuggestArticles" + ] + }, + "SuggestFaqAnswers": { + "methods": [ + "SuggestFaqAnswers" + ] + }, + "SuggestSmartReplies": { + "methods": [ + "SuggestSmartReplies" + ] + }, + "UpdateParticipant": { + "methods": [ + "UpdateParticipant" ] } } - } - } - }, - "Participants": { - "clients": { - "grpc": { + }, + "rest": { "libraryClient": "ParticipantsClient", "rpcs": { "AnalyzeContent": { @@ -987,6 +1857,61 @@ ] } } + }, + "rest": { + "libraryClient": "SessionEntityTypesClient", + "rpcs": { + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "CreateSessionEntityType": { + "methods": [ + "CreateSessionEntityType" + ] + }, + "DeleteSessionEntityType": { + "methods": [ + "DeleteSessionEntityType" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "GetSessionEntityType": { + "methods": [ + "GetSessionEntityType" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "ListSessionEntityTypes": { + "methods": [ + "ListSessionEntityTypes" + ] + }, + "UpdateSessionEntityType": { + "methods": [ + "UpdateSessionEntityType" + ] + } + } } } }, @@ -1031,6 +1956,46 @@ ] } } + }, + "rest": { + "libraryClient": "SessionsClient", + "rpcs": { + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "DetectIntent": { + "methods": [ + "DetectIntent" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "StreamingDetectIntent": { + "methods": [ + "StreamingDetectIntent" + ] + } + } } } }, @@ -1090,6 +2055,61 @@ ] } } + }, + "rest": { + "libraryClient": "VersionsClient", + "rpcs": { + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "CreateVersion": { + "methods": [ + "CreateVersion" + ] + }, + "DeleteVersion": { + "methods": [ + "DeleteVersion" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "GetVersion": { + "methods": [ + "GetVersion" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "ListVersions": { + "methods": [ + "ListVersions" + ] + }, + "UpdateVersion": { + "methods": [ + "UpdateVersion" + ] + } + } } } } diff --git a/dialogflow/apiv2/intents_client.go b/dialogflow/apiv2/intents_client.go index 3982a6eb2538..d4e31f5a4ee0 100644 --- a/dialogflow/apiv2/intents_client.go +++ b/dialogflow/apiv2/intents_client.go @@ -17,9 +17,12 @@ package dialogflow import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,15 +30,18 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" structpb "google.golang.org/protobuf/types/known/structpb" ) @@ -157,6 +163,86 @@ func defaultIntentsCallOptions() *IntentsCallOptions { } } +func defaultIntentsRESTCallOptions() *IntentsCallOptions { + return &IntentsCallOptions{ + ListIntents: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetIntent: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateIntent: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UpdateIntent: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeleteIntent: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + BatchUpdateIntents: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + BatchDeleteIntents: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + CancelOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalIntentsClient is an interface that defines the methods available from Dialogflow API. type internalIntentsClient interface { Close() error @@ -432,6 +518,89 @@ func (c *intentsGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type intentsRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing IntentsClient + CallOptions **IntentsCallOptions +} + +// NewIntentsRESTClient creates a new intents rest client. +// +// Service for managing Intents. +func NewIntentsRESTClient(ctx context.Context, opts ...option.ClientOption) (*IntentsClient, error) { + clientOpts := append(defaultIntentsRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultIntentsRESTCallOptions() + c := &intentsRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &IntentsClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultIntentsRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://dialogflow.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://dialogflow.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://dialogflow.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *intentsRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *intentsRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *intentsRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *intentsGRPCClient) ListIntents(ctx context.Context, req *dialogflowpb.ListIntentsRequest, opts ...gax.CallOption) *IntentIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -746,74 +915,958 @@ func (c *intentsGRPCClient) ListOperations(ctx context.Context, req *longrunning return it } -// BatchDeleteIntentsOperation manages a long-running operation from BatchDeleteIntents. -type BatchDeleteIntentsOperation struct { - lro *longrunning.Operation -} +// ListIntents returns the list of all intents in the specified agent. +func (c *intentsRESTClient) ListIntents(ctx context.Context, req *dialogflowpb.ListIntentsRequest, opts ...gax.CallOption) *IntentIterator { + it := &IntentIterator{} + req = proto.Clone(req).(*dialogflowpb.ListIntentsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*dialogflowpb.Intent, string, error) { + resp := &dialogflowpb.ListIntentsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/intents", req.GetParent()) -// BatchDeleteIntentsOperation returns a new BatchDeleteIntentsOperation from a given name. -// The name must be that of a previously created BatchDeleteIntentsOperation, possibly from a different process. -func (c *intentsGRPCClient) BatchDeleteIntentsOperation(name string) *BatchDeleteIntentsOperation { - return &BatchDeleteIntentsOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetIntentView() != 0 { + params.Add("intentView", fmt.Sprintf("%v", req.GetIntentView())) + } + if req.GetLanguageCode() != "" { + params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetIntents(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it } -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *BatchDeleteIntentsOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { - return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) +// GetIntent retrieves the specified intent. +func (c *intentsRESTClient) GetIntent(ctx context.Context, req *dialogflowpb.GetIntentRequest, opts ...gax.CallOption) (*dialogflowpb.Intent, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetIntentView() != 0 { + params.Add("intentView", fmt.Sprintf("%v", req.GetIntentView())) + } + if req.GetLanguageCode() != "" { + params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetIntent[0:len((*c.CallOptions).GetIntent):len((*c.CallOptions).GetIntent)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dialogflowpb.Intent{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil } -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// CreateIntent creates an intent in the specified agent. // -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *BatchDeleteIntentsOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { - return op.lro.Poll(ctx, nil, opts...) -} +// Note: You should always train an agent prior to sending it queries. See the +// training +// documentation (at https://cloud.google.com/dialogflow/es/docs/training). +func (c *intentsRESTClient) CreateIntent(ctx context.Context, req *dialogflowpb.CreateIntentRequest, opts ...gax.CallOption) (*dialogflowpb.Intent, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetIntent() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *BatchDeleteIntentsOperation) Metadata() (*structpb.Struct, error) { - var meta structpb.Struct - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - return &meta, nil -} + baseUrl.Path += fmt.Sprintf("/v2/%v/intents", req.GetParent()) -// Done reports whether the long-running operation has completed. -func (op *BatchDeleteIntentsOperation) Done() bool { - return op.lro.Done() -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetIntentView() != 0 { + params.Add("intentView", fmt.Sprintf("%v", req.GetIntentView())) + } + if req.GetLanguageCode() != "" { + params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) + } -// 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 *BatchDeleteIntentsOperation) Name() string { - return op.lro.Name() -} + baseUrl.RawQuery = params.Encode() -// BatchUpdateIntentsOperation manages a long-running operation from BatchUpdateIntents. -type BatchUpdateIntentsOperation struct { - lro *longrunning.Operation -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) -// BatchUpdateIntentsOperation returns a new BatchUpdateIntentsOperation from a given name. -// The name must be that of a previously created BatchUpdateIntentsOperation, possibly from a different process. -func (c *intentsGRPCClient) BatchUpdateIntentsOperation(name string) *BatchUpdateIntentsOperation { - return &BatchUpdateIntentsOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateIntent[0:len((*c.CallOptions).CreateIntent):len((*c.CallOptions).CreateIntent)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dialogflowpb.Intent{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateIntent updates the specified intent. +// +// Note: You should always train an agent prior to sending it queries. See the +// training +// documentation (at https://cloud.google.com/dialogflow/es/docs/training). +func (c *intentsRESTClient) UpdateIntent(ctx context.Context, req *dialogflowpb.UpdateIntentRequest, opts ...gax.CallOption) (*dialogflowpb.Intent, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetIntent() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetIntent().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetIntentView() != 0 { + params.Add("intentView", fmt.Sprintf("%v", req.GetIntentView())) + } + if req.GetLanguageCode() != "" { + params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) + } + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "intent.name", url.QueryEscape(req.GetIntent().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateIntent[0:len((*c.CallOptions).UpdateIntent):len((*c.CallOptions).UpdateIntent)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dialogflowpb.Intent{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteIntent deletes the specified intent and its direct or indirect followup intents. +// +// Note: You should always train an agent prior to sending it queries. See the +// training +// documentation (at https://cloud.google.com/dialogflow/es/docs/training). +func (c *intentsRESTClient) DeleteIntent(ctx context.Context, req *dialogflowpb.DeleteIntentRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// BatchUpdateIntents updates/Creates multiple intents in the specified agent. +// +// This method is a long-running +// operation (at https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). +// The returned Operation type has the following method-specific fields: +// +// metadata: An empty Struct +// message (at https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) +// +// response: BatchUpdateIntentsResponse +// +// Note: You should always train an agent prior to sending it queries. See the +// training +// documentation (at https://cloud.google.com/dialogflow/es/docs/training). +func (c *intentsRESTClient) BatchUpdateIntents(ctx context.Context, req *dialogflowpb.BatchUpdateIntentsRequest, opts ...gax.CallOption) (*BatchUpdateIntentsOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/intents:batchUpdate", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &BatchUpdateIntentsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// BatchDeleteIntents deletes intents in the specified agent. +// +// This method is a long-running +// operation (at https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). +// The returned Operation type has the following method-specific fields: +// +// metadata: An empty Struct +// message (at https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) +// +// response: An Empty +// message (at https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) +// +// Note: You should always train an agent prior to sending it queries. See the +// training +// documentation (at https://cloud.google.com/dialogflow/es/docs/training). +func (c *intentsRESTClient) BatchDeleteIntents(ctx context.Context, req *dialogflowpb.BatchDeleteIntentsRequest, opts ...gax.CallOption) (*BatchDeleteIntentsOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/intents:batchDelete", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &BatchDeleteIntentsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetLocation gets information about a location. +func (c *intentsRESTClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *intentsRESTClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *intentsRESTClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *intentsRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *intentsRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// BatchDeleteIntentsOperation manages a long-running operation from BatchDeleteIntents. +type BatchDeleteIntentsOperation struct { + lro *longrunning.Operation + pollPath string +} + +// BatchDeleteIntentsOperation returns a new BatchDeleteIntentsOperation from a given name. +// The name must be that of a previously created BatchDeleteIntentsOperation, possibly from a different process. +func (c *intentsGRPCClient) BatchDeleteIntentsOperation(name string) *BatchDeleteIntentsOperation { + return &BatchDeleteIntentsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// BatchDeleteIntentsOperation returns a new BatchDeleteIntentsOperation from a given name. +// The name must be that of a previously created BatchDeleteIntentsOperation, possibly from a different process. +func (c *intentsRESTClient) BatchDeleteIntentsOperation(name string) *BatchDeleteIntentsOperation { + override := fmt.Sprintf("/v2/%s", name) + return &BatchDeleteIntentsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *BatchDeleteIntentsOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *BatchDeleteIntentsOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + return op.lro.Poll(ctx, nil, opts...) +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *BatchDeleteIntentsOperation) Metadata() (*structpb.Struct, error) { + var meta structpb.Struct + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *BatchDeleteIntentsOperation) Done() bool { + return op.lro.Done() +} + +// 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 *BatchDeleteIntentsOperation) Name() string { + return op.lro.Name() +} + +// BatchUpdateIntentsOperation manages a long-running operation from BatchUpdateIntents. +type BatchUpdateIntentsOperation struct { + lro *longrunning.Operation + pollPath string +} + +// BatchUpdateIntentsOperation returns a new BatchUpdateIntentsOperation from a given name. +// The name must be that of a previously created BatchUpdateIntentsOperation, possibly from a different process. +func (c *intentsGRPCClient) BatchUpdateIntentsOperation(name string) *BatchUpdateIntentsOperation { + return &BatchUpdateIntentsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// BatchUpdateIntentsOperation returns a new BatchUpdateIntentsOperation from a given name. +// The name must be that of a previously created BatchUpdateIntentsOperation, possibly from a different process. +func (c *intentsRESTClient) BatchUpdateIntentsOperation(name string) *BatchUpdateIntentsOperation { + override := fmt.Sprintf("/v2/%s", name) + return &BatchUpdateIntentsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, } } @@ -821,6 +1874,7 @@ func (c *intentsGRPCClient) BatchUpdateIntentsOperation(name string) *BatchUpdat // // See documentation of Poll for error-handling information. func (op *BatchUpdateIntentsOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*dialogflowpb.BatchUpdateIntentsResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp dialogflowpb.BatchUpdateIntentsResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -838,6 +1892,7 @@ func (op *BatchUpdateIntentsOperation) Wait(ctx context.Context, opts ...gax.Cal // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *BatchUpdateIntentsOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*dialogflowpb.BatchUpdateIntentsResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp dialogflowpb.BatchUpdateIntentsResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/dialogflow/apiv2/intents_client_example_test.go b/dialogflow/apiv2/intents_client_example_test.go index 4bcdc5782089..b4e13c35f2a9 100644 --- a/dialogflow/apiv2/intents_client_example_test.go +++ b/dialogflow/apiv2/intents_client_example_test.go @@ -43,6 +43,23 @@ func ExampleNewIntentsClient() { _ = c } +func ExampleNewIntentsRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := dialogflow.NewIntentsRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleIntentsClient_ListIntents() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/dialogflow/apiv2/knowledge_bases_client.go b/dialogflow/apiv2/knowledge_bases_client.go index 8fc9b7f1cf0a..94e768bd6c4e 100644 --- a/dialogflow/apiv2/knowledge_bases_client.go +++ b/dialogflow/apiv2/knowledge_bases_client.go @@ -17,23 +17,29 @@ package dialogflow import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" dialogflowpb "cloud.google.com/go/dialogflow/apiv2/dialogflowpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -130,6 +136,66 @@ func defaultKnowledgeBasesCallOptions() *KnowledgeBasesCallOptions { } } +func defaultKnowledgeBasesRESTCallOptions() *KnowledgeBasesCallOptions { + return &KnowledgeBasesCallOptions{ + ListKnowledgeBases: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetKnowledgeBase: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateKnowledgeBase: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeleteKnowledgeBase: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UpdateKnowledgeBase: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + CancelOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalKnowledgeBasesClient is an interface that defines the methods available from Dialogflow API. type internalKnowledgeBasesClient interface { Close() error @@ -319,6 +385,74 @@ func (c *knowledgeBasesGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type knowledgeBasesRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing KnowledgeBasesClient + CallOptions **KnowledgeBasesCallOptions +} + +// NewKnowledgeBasesRESTClient creates a new knowledge bases rest client. +// +// Service for managing KnowledgeBases. +func NewKnowledgeBasesRESTClient(ctx context.Context, opts ...option.ClientOption) (*KnowledgeBasesClient, error) { + clientOpts := append(defaultKnowledgeBasesRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultKnowledgeBasesRESTCallOptions() + c := &knowledgeBasesRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &KnowledgeBasesClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultKnowledgeBasesRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://dialogflow.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://dialogflow.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://dialogflow.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *knowledgeBasesRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *knowledgeBasesRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *knowledgeBasesRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *knowledgeBasesGRPCClient) ListKnowledgeBases(ctx context.Context, req *dialogflowpb.ListKnowledgeBasesRequest, opts ...gax.CallOption) *KnowledgeBaseIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -585,6 +719,673 @@ func (c *knowledgeBasesGRPCClient) ListOperations(ctx context.Context, req *long return it } +// ListKnowledgeBases returns the list of all knowledge bases of the specified agent. +func (c *knowledgeBasesRESTClient) ListKnowledgeBases(ctx context.Context, req *dialogflowpb.ListKnowledgeBasesRequest, opts ...gax.CallOption) *KnowledgeBaseIterator { + it := &KnowledgeBaseIterator{} + req = proto.Clone(req).(*dialogflowpb.ListKnowledgeBasesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*dialogflowpb.KnowledgeBase, string, error) { + resp := &dialogflowpb.ListKnowledgeBasesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/knowledgeBases", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetKnowledgeBases(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetKnowledgeBase retrieves the specified knowledge base. +func (c *knowledgeBasesRESTClient) GetKnowledgeBase(ctx context.Context, req *dialogflowpb.GetKnowledgeBaseRequest, opts ...gax.CallOption) (*dialogflowpb.KnowledgeBase, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetKnowledgeBase[0:len((*c.CallOptions).GetKnowledgeBase):len((*c.CallOptions).GetKnowledgeBase)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dialogflowpb.KnowledgeBase{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateKnowledgeBase creates a knowledge base. +func (c *knowledgeBasesRESTClient) CreateKnowledgeBase(ctx context.Context, req *dialogflowpb.CreateKnowledgeBaseRequest, opts ...gax.CallOption) (*dialogflowpb.KnowledgeBase, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetKnowledgeBase() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/knowledgeBases", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateKnowledgeBase[0:len((*c.CallOptions).CreateKnowledgeBase):len((*c.CallOptions).CreateKnowledgeBase)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dialogflowpb.KnowledgeBase{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteKnowledgeBase deletes the specified knowledge base. +func (c *knowledgeBasesRESTClient) DeleteKnowledgeBase(ctx context.Context, req *dialogflowpb.DeleteKnowledgeBaseRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetForce() { + params.Add("force", fmt.Sprintf("%v", req.GetForce())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// UpdateKnowledgeBase updates the specified knowledge base. +func (c *knowledgeBasesRESTClient) UpdateKnowledgeBase(ctx context.Context, req *dialogflowpb.UpdateKnowledgeBaseRequest, opts ...gax.CallOption) (*dialogflowpb.KnowledgeBase, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetKnowledgeBase() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetKnowledgeBase().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "knowledge_base.name", url.QueryEscape(req.GetKnowledgeBase().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateKnowledgeBase[0:len((*c.CallOptions).UpdateKnowledgeBase):len((*c.CallOptions).UpdateKnowledgeBase)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dialogflowpb.KnowledgeBase{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetLocation gets information about a location. +func (c *knowledgeBasesRESTClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *knowledgeBasesRESTClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *knowledgeBasesRESTClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *knowledgeBasesRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *knowledgeBasesRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + // KnowledgeBaseIterator manages a stream of *dialogflowpb.KnowledgeBase. type KnowledgeBaseIterator struct { items []*dialogflowpb.KnowledgeBase diff --git a/dialogflow/apiv2/knowledge_bases_client_example_test.go b/dialogflow/apiv2/knowledge_bases_client_example_test.go index 2c8a4c256776..a3e484af3cc0 100644 --- a/dialogflow/apiv2/knowledge_bases_client_example_test.go +++ b/dialogflow/apiv2/knowledge_bases_client_example_test.go @@ -43,6 +43,23 @@ func ExampleNewKnowledgeBasesClient() { _ = c } +func ExampleNewKnowledgeBasesRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := dialogflow.NewKnowledgeBasesRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleKnowledgeBasesClient_ListKnowledgeBases() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/dialogflow/apiv2/participants_client.go b/dialogflow/apiv2/participants_client.go index ae96e308137c..91cc6b596a61 100644 --- a/dialogflow/apiv2/participants_client.go +++ b/dialogflow/apiv2/participants_client.go @@ -17,23 +17,29 @@ package dialogflow import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" dialogflowpb "cloud.google.com/go/dialogflow/apiv2/dialogflowpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -168,6 +174,97 @@ func defaultParticipantsCallOptions() *ParticipantsCallOptions { } } +func defaultParticipantsRESTCallOptions() *ParticipantsCallOptions { + return &ParticipantsCallOptions{ + CreateParticipant: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetParticipant: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListParticipants: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UpdateParticipant: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + AnalyzeContent: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + StreamingAnalyzeContent: []gax.CallOption{}, + SuggestArticles: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + SuggestFaqAnswers: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + SuggestSmartReplies: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + CancelOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalParticipantsClient is an interface that defines the methods available from Dialogflow API. type internalParticipantsClient interface { Close() error @@ -269,6 +366,8 @@ func (c *ParticipantsClient) AnalyzeContent(ctx context.Context, req *dialogflow // Note: Always use agent versions for production traffic // sent to virtual agents. See Versions and // environments (at https://cloud.google.com/dialogflow/es/docs/agents-versions). +// +// This method is not supported for the REST transport. func (c *ParticipantsClient) StreamingAnalyzeContent(ctx context.Context, opts ...gax.CallOption) (dialogflowpb.Participants_StreamingAnalyzeContentClient, error) { return c.internalClient.StreamingAnalyzeContent(ctx, opts...) } @@ -403,6 +502,74 @@ func (c *participantsGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type participantsRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing ParticipantsClient + CallOptions **ParticipantsCallOptions +} + +// NewParticipantsRESTClient creates a new participants rest client. +// +// Service for managing Participants. +func NewParticipantsRESTClient(ctx context.Context, opts ...option.ClientOption) (*ParticipantsClient, error) { + clientOpts := append(defaultParticipantsRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultParticipantsRESTCallOptions() + c := &participantsRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &ParticipantsClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultParticipantsRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://dialogflow.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://dialogflow.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://dialogflow.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *participantsRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *participantsRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *participantsRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *participantsGRPCClient) CreateParticipant(ctx context.Context, req *dialogflowpb.CreateParticipantRequest, opts ...gax.CallOption) (*dialogflowpb.Participant, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) @@ -754,6 +921,912 @@ func (c *participantsGRPCClient) ListOperations(ctx context.Context, req *longru return it } +// CreateParticipant creates a new participant in a conversation. +func (c *participantsRESTClient) CreateParticipant(ctx context.Context, req *dialogflowpb.CreateParticipantRequest, opts ...gax.CallOption) (*dialogflowpb.Participant, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetParticipant() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/participants", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateParticipant[0:len((*c.CallOptions).CreateParticipant):len((*c.CallOptions).CreateParticipant)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dialogflowpb.Participant{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetParticipant retrieves a conversation participant. +func (c *participantsRESTClient) GetParticipant(ctx context.Context, req *dialogflowpb.GetParticipantRequest, opts ...gax.CallOption) (*dialogflowpb.Participant, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetParticipant[0:len((*c.CallOptions).GetParticipant):len((*c.CallOptions).GetParticipant)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dialogflowpb.Participant{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListParticipants returns the list of all participants in the specified conversation. +func (c *participantsRESTClient) ListParticipants(ctx context.Context, req *dialogflowpb.ListParticipantsRequest, opts ...gax.CallOption) *ParticipantIterator { + it := &ParticipantIterator{} + req = proto.Clone(req).(*dialogflowpb.ListParticipantsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*dialogflowpb.Participant, string, error) { + resp := &dialogflowpb.ListParticipantsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/participants", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetParticipants(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// UpdateParticipant updates the specified participant. +func (c *participantsRESTClient) UpdateParticipant(ctx context.Context, req *dialogflowpb.UpdateParticipantRequest, opts ...gax.CallOption) (*dialogflowpb.Participant, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetParticipant() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetParticipant().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "participant.name", url.QueryEscape(req.GetParticipant().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateParticipant[0:len((*c.CallOptions).UpdateParticipant):len((*c.CallOptions).UpdateParticipant)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dialogflowpb.Participant{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// AnalyzeContent adds a text (chat, for example), or audio (phone recording, for example) +// message from a participant into the conversation. +// +// Note: Always use agent versions for production traffic +// sent to virtual agents. See Versions and +// environments (at https://cloud.google.com/dialogflow/es/docs/agents-versions). +func (c *participantsRESTClient) AnalyzeContent(ctx context.Context, req *dialogflowpb.AnalyzeContentRequest, opts ...gax.CallOption) (*dialogflowpb.AnalyzeContentResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:analyzeContent", req.GetParticipant()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "participant", url.QueryEscape(req.GetParticipant()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).AnalyzeContent[0:len((*c.CallOptions).AnalyzeContent):len((*c.CallOptions).AnalyzeContent)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dialogflowpb.AnalyzeContentResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// StreamingAnalyzeContent adds a text (chat, for example), or audio (phone recording, for example) +// message from a participant into the conversation. +// Note: This method is only available through the gRPC API (not REST). +// +// The top-level message sent to the client by the server is +// StreamingAnalyzeContentResponse. Multiple response messages can be +// returned in order. The first one or more messages contain the +// recognition_result field. Each result represents a more complete +// transcript of what the user said. The next message contains the +// reply_text field and potentially the reply_audio field. The message can +// also contain the automated_agent_reply field. +// +// Note: Always use agent versions for production traffic +// sent to virtual agents. See Versions and +// environments (at https://cloud.google.com/dialogflow/es/docs/agents-versions). +// +// This method is not supported for the REST transport. +func (c *participantsRESTClient) StreamingAnalyzeContent(ctx context.Context, opts ...gax.CallOption) (dialogflowpb.Participants_StreamingAnalyzeContentClient, error) { + return nil, fmt.Errorf("StreamingAnalyzeContent not yet supported for REST clients") +} + +// SuggestArticles gets suggested articles for a participant based on specific historical +// messages. +func (c *participantsRESTClient) SuggestArticles(ctx context.Context, req *dialogflowpb.SuggestArticlesRequest, opts ...gax.CallOption) (*dialogflowpb.SuggestArticlesResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/suggestions:suggestArticles", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SuggestArticles[0:len((*c.CallOptions).SuggestArticles):len((*c.CallOptions).SuggestArticles)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dialogflowpb.SuggestArticlesResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SuggestFaqAnswers gets suggested faq answers for a participant based on specific historical +// messages. +func (c *participantsRESTClient) SuggestFaqAnswers(ctx context.Context, req *dialogflowpb.SuggestFaqAnswersRequest, opts ...gax.CallOption) (*dialogflowpb.SuggestFaqAnswersResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/suggestions:suggestFaqAnswers", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SuggestFaqAnswers[0:len((*c.CallOptions).SuggestFaqAnswers):len((*c.CallOptions).SuggestFaqAnswers)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dialogflowpb.SuggestFaqAnswersResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SuggestSmartReplies gets smart replies for a participant based on specific historical +// messages. +func (c *participantsRESTClient) SuggestSmartReplies(ctx context.Context, req *dialogflowpb.SuggestSmartRepliesRequest, opts ...gax.CallOption) (*dialogflowpb.SuggestSmartRepliesResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/suggestions:suggestSmartReplies", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SuggestSmartReplies[0:len((*c.CallOptions).SuggestSmartReplies):len((*c.CallOptions).SuggestSmartReplies)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dialogflowpb.SuggestSmartRepliesResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetLocation gets information about a location. +func (c *participantsRESTClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *participantsRESTClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *participantsRESTClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *participantsRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *participantsRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + // ParticipantIterator manages a stream of *dialogflowpb.Participant. type ParticipantIterator struct { items []*dialogflowpb.Participant diff --git a/dialogflow/apiv2/participants_client_example_test.go b/dialogflow/apiv2/participants_client_example_test.go index 8083e638a804..f3d6426dbb89 100644 --- a/dialogflow/apiv2/participants_client_example_test.go +++ b/dialogflow/apiv2/participants_client_example_test.go @@ -44,6 +44,23 @@ func ExampleNewParticipantsClient() { _ = c } +func ExampleNewParticipantsRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := dialogflow.NewParticipantsRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleParticipantsClient_CreateParticipant() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/dialogflow/apiv2/session_entity_types_client.go b/dialogflow/apiv2/session_entity_types_client.go index 7c7d40f69e56..d5644d2b2c3c 100644 --- a/dialogflow/apiv2/session_entity_types_client.go +++ b/dialogflow/apiv2/session_entity_types_client.go @@ -17,23 +17,29 @@ package dialogflow import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" dialogflowpb "cloud.google.com/go/dialogflow/apiv2/dialogflowpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -130,6 +136,66 @@ func defaultSessionEntityTypesCallOptions() *SessionEntityTypesCallOptions { } } +func defaultSessionEntityTypesRESTCallOptions() *SessionEntityTypesCallOptions { + return &SessionEntityTypesCallOptions{ + ListSessionEntityTypes: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetSessionEntityType: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateSessionEntityType: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UpdateSessionEntityType: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeleteSessionEntityType: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + CancelOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalSessionEntityTypesClient is an interface that defines the methods available from Dialogflow API. type internalSessionEntityTypesClient interface { Close() error @@ -342,6 +408,74 @@ func (c *sessionEntityTypesGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type sessionEntityTypesRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing SessionEntityTypesClient + CallOptions **SessionEntityTypesCallOptions +} + +// NewSessionEntityTypesRESTClient creates a new session entity types rest client. +// +// Service for managing SessionEntityTypes. +func NewSessionEntityTypesRESTClient(ctx context.Context, opts ...option.ClientOption) (*SessionEntityTypesClient, error) { + clientOpts := append(defaultSessionEntityTypesRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultSessionEntityTypesRESTCallOptions() + c := &sessionEntityTypesRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &SessionEntityTypesClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultSessionEntityTypesRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://dialogflow.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://dialogflow.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://dialogflow.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *sessionEntityTypesRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *sessionEntityTypesRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *sessionEntityTypesRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *sessionEntityTypesGRPCClient) ListSessionEntityTypes(ctx context.Context, req *dialogflowpb.ListSessionEntityTypesRequest, opts ...gax.CallOption) *SessionEntityTypeIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -608,6 +742,690 @@ func (c *sessionEntityTypesGRPCClient) ListOperations(ctx context.Context, req * return it } +// ListSessionEntityTypes returns the list of all session entity types in the specified session. +// +// This method doesn’t work with Google Assistant integration. +// Contact Dialogflow support if you need to use session entities +// with Google Assistant integration. +func (c *sessionEntityTypesRESTClient) ListSessionEntityTypes(ctx context.Context, req *dialogflowpb.ListSessionEntityTypesRequest, opts ...gax.CallOption) *SessionEntityTypeIterator { + it := &SessionEntityTypeIterator{} + req = proto.Clone(req).(*dialogflowpb.ListSessionEntityTypesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*dialogflowpb.SessionEntityType, string, error) { + resp := &dialogflowpb.ListSessionEntityTypesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/entityTypes", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetSessionEntityTypes(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetSessionEntityType retrieves the specified session entity type. +// +// This method doesn’t work with Google Assistant integration. +// Contact Dialogflow support if you need to use session entities +// with Google Assistant integration. +func (c *sessionEntityTypesRESTClient) GetSessionEntityType(ctx context.Context, req *dialogflowpb.GetSessionEntityTypeRequest, opts ...gax.CallOption) (*dialogflowpb.SessionEntityType, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetSessionEntityType[0:len((*c.CallOptions).GetSessionEntityType):len((*c.CallOptions).GetSessionEntityType)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dialogflowpb.SessionEntityType{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateSessionEntityType creates a session entity type. +// +// If the specified session entity type already exists, overrides the session +// entity type. +// +// This method doesn’t work with Google Assistant integration. +// Contact Dialogflow support if you need to use session entities +// with Google Assistant integration. +func (c *sessionEntityTypesRESTClient) CreateSessionEntityType(ctx context.Context, req *dialogflowpb.CreateSessionEntityTypeRequest, opts ...gax.CallOption) (*dialogflowpb.SessionEntityType, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetSessionEntityType() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/entityTypes", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateSessionEntityType[0:len((*c.CallOptions).CreateSessionEntityType):len((*c.CallOptions).CreateSessionEntityType)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dialogflowpb.SessionEntityType{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateSessionEntityType updates the specified session entity type. +// +// This method doesn’t work with Google Assistant integration. +// Contact Dialogflow support if you need to use session entities +// with Google Assistant integration. +func (c *sessionEntityTypesRESTClient) UpdateSessionEntityType(ctx context.Context, req *dialogflowpb.UpdateSessionEntityTypeRequest, opts ...gax.CallOption) (*dialogflowpb.SessionEntityType, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetSessionEntityType() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetSessionEntityType().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "session_entity_type.name", url.QueryEscape(req.GetSessionEntityType().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateSessionEntityType[0:len((*c.CallOptions).UpdateSessionEntityType):len((*c.CallOptions).UpdateSessionEntityType)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dialogflowpb.SessionEntityType{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteSessionEntityType deletes the specified session entity type. +// +// This method doesn’t work with Google Assistant integration. +// Contact Dialogflow support if you need to use session entities +// with Google Assistant integration. +func (c *sessionEntityTypesRESTClient) DeleteSessionEntityType(ctx context.Context, req *dialogflowpb.DeleteSessionEntityTypeRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetLocation gets information about a location. +func (c *sessionEntityTypesRESTClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *sessionEntityTypesRESTClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *sessionEntityTypesRESTClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *sessionEntityTypesRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *sessionEntityTypesRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + // SessionEntityTypeIterator manages a stream of *dialogflowpb.SessionEntityType. type SessionEntityTypeIterator struct { items []*dialogflowpb.SessionEntityType diff --git a/dialogflow/apiv2/session_entity_types_client_example_test.go b/dialogflow/apiv2/session_entity_types_client_example_test.go index af3894687539..21f63ac59fe6 100644 --- a/dialogflow/apiv2/session_entity_types_client_example_test.go +++ b/dialogflow/apiv2/session_entity_types_client_example_test.go @@ -43,6 +43,23 @@ func ExampleNewSessionEntityTypesClient() { _ = c } +func ExampleNewSessionEntityTypesRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := dialogflow.NewSessionEntityTypesRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleSessionEntityTypesClient_ListSessionEntityTypes() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/dialogflow/apiv2/sessions_client.go b/dialogflow/apiv2/sessions_client.go index 32fd691e6202..f06f6ca0adc4 100644 --- a/dialogflow/apiv2/sessions_client.go +++ b/dialogflow/apiv2/sessions_client.go @@ -17,23 +17,29 @@ package dialogflow import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" dialogflowpb "cloud.google.com/go/dialogflow/apiv2/dialogflowpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -84,6 +90,27 @@ func defaultSessionsCallOptions() *SessionsCallOptions { } } +func defaultSessionsRESTCallOptions() *SessionsCallOptions { + return &SessionsCallOptions{ + DetectIntent: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + StreamingDetectIntent: []gax.CallOption{}, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + CancelOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalSessionsClient is an interface that defines the methods available from Dialogflow API. type internalSessionsClient interface { Close() error @@ -169,6 +196,8 @@ func (c *SessionsClient) DetectIntent(ctx context.Context, req *dialogflowpb.Det // Note: Always use agent versions for production traffic. // See Versions and // environments (at https://cloud.google.com/dialogflow/es/docs/agents-versions). +// +// This method is not supported for the REST transport. func (c *SessionsClient) StreamingDetectIntent(ctx context.Context, opts ...gax.CallOption) (dialogflowpb.Sessions_StreamingDetectIntentClient, error) { return c.internalClient.StreamingDetectIntent(ctx, opts...) } @@ -288,6 +317,77 @@ func (c *sessionsGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type sessionsRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing SessionsClient + CallOptions **SessionsCallOptions +} + +// NewSessionsRESTClient creates a new sessions rest client. +// +// A service used for session interactions. +// +// For more information, see the API interactions +// guide (at https://cloud.google.com/dialogflow/docs/api-overview). +func NewSessionsRESTClient(ctx context.Context, opts ...option.ClientOption) (*SessionsClient, error) { + clientOpts := append(defaultSessionsRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultSessionsRESTCallOptions() + c := &sessionsRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &SessionsClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultSessionsRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://dialogflow.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://dialogflow.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://dialogflow.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *sessionsRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *sessionsRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *sessionsRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *sessionsGRPCClient) DetectIntent(ctx context.Context, req *dialogflowpb.DetectIntentRequest, opts ...gax.CallOption) (*dialogflowpb.DetectIntentResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 220000*time.Millisecond) @@ -461,3 +561,439 @@ func (c *sessionsGRPCClient) ListOperations(ctx context.Context, req *longrunnin return it } + +// DetectIntent processes a natural language query and returns structured, actionable data +// as a result. This method is not idempotent, because it may cause contexts +// and session entity types to be updated, which in turn might affect +// results of future queries. +// +// If you might use +// Agent Assist (at https://cloud.google.com/dialogflow/docs/#aa) +// or other CCAI products now or in the future, consider using +// AnalyzeContent +// instead of DetectIntent. AnalyzeContent has additional +// functionality for Agent Assist and other CCAI products. +// +// Note: Always use agent versions for production traffic. +// See Versions and +// environments (at https://cloud.google.com/dialogflow/es/docs/agents-versions). +func (c *sessionsRESTClient) DetectIntent(ctx context.Context, req *dialogflowpb.DetectIntentRequest, opts ...gax.CallOption) (*dialogflowpb.DetectIntentResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:detectIntent", req.GetSession()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "session", url.QueryEscape(req.GetSession()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).DetectIntent[0:len((*c.CallOptions).DetectIntent):len((*c.CallOptions).DetectIntent)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dialogflowpb.DetectIntentResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// StreamingDetectIntent processes a natural language query in audio format in a streaming fashion +// and returns structured, actionable data as a result. This method is only +// available via the gRPC API (not REST). +// +// If you might use +// Agent Assist (at https://cloud.google.com/dialogflow/docs/#aa) +// or other CCAI products now or in the future, consider using +// StreamingAnalyzeContent +// instead of StreamingDetectIntent. StreamingAnalyzeContent has +// additional functionality for Agent Assist and other CCAI products. +// +// Note: Always use agent versions for production traffic. +// See Versions and +// environments (at https://cloud.google.com/dialogflow/es/docs/agents-versions). +// +// This method is not supported for the REST transport. +func (c *sessionsRESTClient) StreamingDetectIntent(ctx context.Context, opts ...gax.CallOption) (dialogflowpb.Sessions_StreamingDetectIntentClient, error) { + return nil, fmt.Errorf("StreamingDetectIntent not yet supported for REST clients") +} + +// GetLocation gets information about a location. +func (c *sessionsRESTClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *sessionsRESTClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *sessionsRESTClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *sessionsRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *sessionsRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} diff --git a/dialogflow/apiv2/sessions_client_example_test.go b/dialogflow/apiv2/sessions_client_example_test.go index 9456253fe9f3..8559e7298c5f 100644 --- a/dialogflow/apiv2/sessions_client_example_test.go +++ b/dialogflow/apiv2/sessions_client_example_test.go @@ -44,6 +44,23 @@ func ExampleNewSessionsClient() { _ = c } +func ExampleNewSessionsRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := dialogflow.NewSessionsRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleSessionsClient_DetectIntent() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/dialogflow/apiv2/versions_client.go b/dialogflow/apiv2/versions_client.go index 54f9e7de37cf..a0ce80895aa7 100644 --- a/dialogflow/apiv2/versions_client.go +++ b/dialogflow/apiv2/versions_client.go @@ -17,23 +17,29 @@ package dialogflow import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" dialogflowpb "cloud.google.com/go/dialogflow/apiv2/dialogflowpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -130,6 +136,66 @@ func defaultVersionsCallOptions() *VersionsCallOptions { } } +func defaultVersionsRESTCallOptions() *VersionsCallOptions { + return &VersionsCallOptions{ + ListVersions: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetVersion: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateVersion: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UpdateVersion: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeleteVersion: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + CancelOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalVersionsClient is an interface that defines the methods available from Dialogflow API. type internalVersionsClient interface { Close() error @@ -325,6 +391,74 @@ func (c *versionsGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type versionsRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing VersionsClient + CallOptions **VersionsCallOptions +} + +// NewVersionsRESTClient creates a new versions rest client. +// +// Service for managing Versions. +func NewVersionsRESTClient(ctx context.Context, opts ...option.ClientOption) (*VersionsClient, error) { + clientOpts := append(defaultVersionsRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultVersionsRESTCallOptions() + c := &versionsRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &VersionsClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultVersionsRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://dialogflow.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://dialogflow.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://dialogflow.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *versionsRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *versionsRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *versionsRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *versionsGRPCClient) ListVersions(ctx context.Context, req *dialogflowpb.ListVersionsRequest, opts ...gax.CallOption) *VersionIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -591,6 +725,673 @@ func (c *versionsGRPCClient) ListOperations(ctx context.Context, req *longrunnin return it } +// ListVersions returns the list of all versions of the specified agent. +func (c *versionsRESTClient) ListVersions(ctx context.Context, req *dialogflowpb.ListVersionsRequest, opts ...gax.CallOption) *VersionIterator { + it := &VersionIterator{} + req = proto.Clone(req).(*dialogflowpb.ListVersionsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*dialogflowpb.Version, string, error) { + resp := &dialogflowpb.ListVersionsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/versions", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetVersions(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetVersion retrieves the specified agent version. +func (c *versionsRESTClient) GetVersion(ctx context.Context, req *dialogflowpb.GetVersionRequest, opts ...gax.CallOption) (*dialogflowpb.Version, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetVersion[0:len((*c.CallOptions).GetVersion):len((*c.CallOptions).GetVersion)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dialogflowpb.Version{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateVersion creates an agent version. +// +// The new version points to the agent instance in the “default” environment. +func (c *versionsRESTClient) CreateVersion(ctx context.Context, req *dialogflowpb.CreateVersionRequest, opts ...gax.CallOption) (*dialogflowpb.Version, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetVersion() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/versions", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateVersion[0:len((*c.CallOptions).CreateVersion):len((*c.CallOptions).CreateVersion)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dialogflowpb.Version{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateVersion updates the specified agent version. +// +// Note that this method does not allow you to update the state of the agent +// the given version points to. It allows you to update only mutable +// properties of the version resource. +func (c *versionsRESTClient) UpdateVersion(ctx context.Context, req *dialogflowpb.UpdateVersionRequest, opts ...gax.CallOption) (*dialogflowpb.Version, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetVersion() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetVersion().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "version.name", url.QueryEscape(req.GetVersion().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateVersion[0:len((*c.CallOptions).UpdateVersion):len((*c.CallOptions).UpdateVersion)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dialogflowpb.Version{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteVersion delete the specified agent version. +func (c *versionsRESTClient) DeleteVersion(ctx context.Context, req *dialogflowpb.DeleteVersionRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetLocation gets information about a location. +func (c *versionsRESTClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *versionsRESTClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *versionsRESTClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *versionsRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *versionsRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + // VersionIterator manages a stream of *dialogflowpb.Version. type VersionIterator struct { items []*dialogflowpb.Version diff --git a/dialogflow/apiv2/versions_client_example_test.go b/dialogflow/apiv2/versions_client_example_test.go index 8b8222c27729..4d97360c256d 100644 --- a/dialogflow/apiv2/versions_client_example_test.go +++ b/dialogflow/apiv2/versions_client_example_test.go @@ -43,6 +43,23 @@ func ExampleNewVersionsClient() { _ = c } +func ExampleNewVersionsRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := dialogflow.NewVersionsRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleVersionsClient_ListVersions() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/dialogflow/apiv2beta1/agents_client.go b/dialogflow/apiv2beta1/agents_client.go index c54e95dff3ee..5b191fd87727 100644 --- a/dialogflow/apiv2beta1/agents_client.go +++ b/dialogflow/apiv2beta1/agents_client.go @@ -1084,6 +1084,11 @@ func (c *agentsRESTClient) GetAgent(ctx context.Context, req *dialogflowpb.GetAg } baseUrl.Path += fmt.Sprintf("/v2beta1/%v/agent", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1149,6 +1154,7 @@ func (c *agentsRESTClient) SetAgent(ctx context.Context, req *dialogflowpb.SetAg baseUrl.Path += fmt.Sprintf("/v2beta1/%v/agent", req.GetAgent().GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -1212,6 +1218,11 @@ func (c *agentsRESTClient) DeleteAgent(ctx context.Context, req *dialogflowpb.De } baseUrl.Path += fmt.Sprintf("/v2beta1/%v/agent", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1266,6 +1277,7 @@ func (c *agentsRESTClient) SearchAgents(ctx context.Context, req *dialogflowpb.S baseUrl.Path += fmt.Sprintf("/v2beta1/%v/agent:search", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -1359,6 +1371,11 @@ func (c *agentsRESTClient) TrainAgent(ctx context.Context, req *dialogflowpb.Tra } baseUrl.Path += fmt.Sprintf("/v2beta1/%v/agent:train", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1431,6 +1448,11 @@ func (c *agentsRESTClient) ExportAgent(ctx context.Context, req *dialogflowpb.Ex } baseUrl.Path += fmt.Sprintf("/v2beta1/%v/agent:export", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1519,6 +1541,11 @@ func (c *agentsRESTClient) ImportAgent(ctx context.Context, req *dialogflowpb.Im } baseUrl.Path += fmt.Sprintf("/v2beta1/%v/agent:import", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1606,6 +1633,11 @@ func (c *agentsRESTClient) RestoreAgent(ctx context.Context, req *dialogflowpb.R } baseUrl.Path += fmt.Sprintf("/v2beta1/%v/agent:restore", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1665,6 +1697,7 @@ func (c *agentsRESTClient) GetValidationResult(ctx context.Context, req *dialogf baseUrl.Path += fmt.Sprintf("/v2beta1/%v/agent/validationResult", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetLanguageCode() != "" { params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) } @@ -1724,6 +1757,11 @@ func (c *agentsRESTClient) GetLocation(ctx context.Context, req *locationpb.GetL } baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1791,6 +1829,7 @@ func (c *agentsRESTClient) ListLocations(ctx context.Context, req *locationpb.Li baseUrl.Path += fmt.Sprintf("/v2beta1/%v/locations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1867,6 +1906,11 @@ func (c *agentsRESTClient) CancelOperation(ctx context.Context, req *longrunning } baseUrl.Path += fmt.Sprintf("/v2beta1/%v:cancel", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1902,6 +1946,11 @@ func (c *agentsRESTClient) GetOperation(ctx context.Context, req *longrunningpb. } baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1969,6 +2018,7 @@ func (c *agentsRESTClient) ListOperations(ctx context.Context, req *longrunningp baseUrl.Path += fmt.Sprintf("/v2beta1/%v/operations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/dialogflow/apiv2beta1/answer_records_client.go b/dialogflow/apiv2beta1/answer_records_client.go index 935e11a7bb98..0bafa0662020 100644 --- a/dialogflow/apiv2beta1/answer_records_client.go +++ b/dialogflow/apiv2beta1/answer_records_client.go @@ -638,6 +638,11 @@ func (c *answerRecordsRESTClient) GetAnswerRecord(ctx context.Context, req *dial } baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -706,6 +711,7 @@ func (c *answerRecordsRESTClient) ListAnswerRecords(ctx context.Context, req *di baseUrl.Path += fmt.Sprintf("/v2beta1/%v/answerRecords", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -790,6 +796,7 @@ func (c *answerRecordsRESTClient) UpdateAnswerRecord(ctx context.Context, req *d baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetAnswerRecord().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -853,6 +860,11 @@ func (c *answerRecordsRESTClient) GetLocation(ctx context.Context, req *location } baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -920,6 +932,7 @@ func (c *answerRecordsRESTClient) ListLocations(ctx context.Context, req *locati baseUrl.Path += fmt.Sprintf("/v2beta1/%v/locations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -996,6 +1009,11 @@ func (c *answerRecordsRESTClient) CancelOperation(ctx context.Context, req *long } baseUrl.Path += fmt.Sprintf("/v2beta1/%v:cancel", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1031,6 +1049,11 @@ func (c *answerRecordsRESTClient) GetOperation(ctx context.Context, req *longrun } baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1098,6 +1121,7 @@ func (c *answerRecordsRESTClient) ListOperations(ctx context.Context, req *longr baseUrl.Path += fmt.Sprintf("/v2beta1/%v/operations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/dialogflow/apiv2beta1/contexts_client.go b/dialogflow/apiv2beta1/contexts_client.go index f5e466062acf..989c41dfae01 100644 --- a/dialogflow/apiv2beta1/contexts_client.go +++ b/dialogflow/apiv2beta1/contexts_client.go @@ -789,6 +789,7 @@ func (c *contextsRESTClient) ListContexts(ctx context.Context, req *dialogflowpb baseUrl.Path += fmt.Sprintf("/v2beta1/%v/contexts", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -862,6 +863,11 @@ func (c *contextsRESTClient) GetContext(ctx context.Context, req *dialogflowpb.G } baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -924,6 +930,11 @@ func (c *contextsRESTClient) CreateContext(ctx context.Context, req *dialogflowp } baseUrl.Path += fmt.Sprintf("/v2beta1/%v/contexts", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -985,6 +996,7 @@ func (c *contextsRESTClient) UpdateContext(ctx context.Context, req *dialogflowp baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetContext().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -1048,6 +1060,11 @@ func (c *contextsRESTClient) DeleteContext(ctx context.Context, req *dialogflowp } baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1083,6 +1100,11 @@ func (c *contextsRESTClient) DeleteAllContexts(ctx context.Context, req *dialogf } baseUrl.Path += fmt.Sprintf("/v2beta1/%v/contexts", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1118,6 +1140,11 @@ func (c *contextsRESTClient) GetLocation(ctx context.Context, req *locationpb.Ge } baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1185,6 +1212,7 @@ func (c *contextsRESTClient) ListLocations(ctx context.Context, req *locationpb. baseUrl.Path += fmt.Sprintf("/v2beta1/%v/locations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1261,6 +1289,11 @@ func (c *contextsRESTClient) CancelOperation(ctx context.Context, req *longrunni } baseUrl.Path += fmt.Sprintf("/v2beta1/%v:cancel", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1296,6 +1329,11 @@ func (c *contextsRESTClient) GetOperation(ctx context.Context, req *longrunningp } baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1363,6 +1401,7 @@ func (c *contextsRESTClient) ListOperations(ctx context.Context, req *longrunnin baseUrl.Path += fmt.Sprintf("/v2beta1/%v/operations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/dialogflow/apiv2beta1/conversation_profiles_client.go b/dialogflow/apiv2beta1/conversation_profiles_client.go index c838bef80e04..df9daed2dcf9 100644 --- a/dialogflow/apiv2beta1/conversation_profiles_client.go +++ b/dialogflow/apiv2beta1/conversation_profiles_client.go @@ -930,6 +930,7 @@ func (c *conversationProfilesRESTClient) ListConversationProfiles(ctx context.Co baseUrl.Path += fmt.Sprintf("/v2beta1/%v/conversationProfiles", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -1003,6 +1004,11 @@ func (c *conversationProfilesRESTClient) GetConversationProfile(ctx context.Cont } baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1067,6 +1073,11 @@ func (c *conversationProfilesRESTClient) CreateConversationProfile(ctx context.C } baseUrl.Path += fmt.Sprintf("/v2beta1/%v/conversationProfiles", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1132,6 +1143,7 @@ func (c *conversationProfilesRESTClient) UpdateConversationProfile(ctx context.C baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetConversationProfile().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -1195,6 +1207,11 @@ func (c *conversationProfilesRESTClient) DeleteConversationProfile(ctx context.C } baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1252,6 +1269,11 @@ func (c *conversationProfilesRESTClient) SetSuggestionFeatureConfig(ctx context. } baseUrl.Path += fmt.Sprintf("/v2beta1/%v:setSuggestionFeatureConfig", req.GetConversationProfile()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "conversation_profile", url.QueryEscape(req.GetConversationProfile()))) @@ -1324,6 +1346,11 @@ func (c *conversationProfilesRESTClient) ClearSuggestionFeatureConfig(ctx contex } baseUrl.Path += fmt.Sprintf("/v2beta1/%v:clearSuggestionFeatureConfig", req.GetConversationProfile()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "conversation_profile", url.QueryEscape(req.GetConversationProfile()))) @@ -1381,6 +1408,11 @@ func (c *conversationProfilesRESTClient) GetLocation(ctx context.Context, req *l } baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1448,6 +1480,7 @@ func (c *conversationProfilesRESTClient) ListLocations(ctx context.Context, req baseUrl.Path += fmt.Sprintf("/v2beta1/%v/locations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1524,6 +1557,11 @@ func (c *conversationProfilesRESTClient) CancelOperation(ctx context.Context, re } baseUrl.Path += fmt.Sprintf("/v2beta1/%v:cancel", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1559,6 +1597,11 @@ func (c *conversationProfilesRESTClient) GetOperation(ctx context.Context, req * } baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1626,6 +1669,7 @@ func (c *conversationProfilesRESTClient) ListOperations(ctx context.Context, req baseUrl.Path += fmt.Sprintf("/v2beta1/%v/operations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/dialogflow/apiv2beta1/conversations_client.go b/dialogflow/apiv2beta1/conversations_client.go index dd553b9a7dde..3ccd6f2d495c 100644 --- a/dialogflow/apiv2beta1/conversations_client.go +++ b/dialogflow/apiv2beta1/conversations_client.go @@ -903,6 +903,7 @@ func (c *conversationsRESTClient) CreateConversation(ctx context.Context, req *d baseUrl.Path += fmt.Sprintf("/v2beta1/%v/conversations", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetConversationId() != "" { params.Add("conversationId", fmt.Sprintf("%v", req.GetConversationId())) } @@ -976,6 +977,7 @@ func (c *conversationsRESTClient) ListConversations(ctx context.Context, req *di baseUrl.Path += fmt.Sprintf("/v2beta1/%v/conversations", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1052,6 +1054,11 @@ func (c *conversationsRESTClient) GetConversation(ctx context.Context, req *dial } baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1112,6 +1119,11 @@ func (c *conversationsRESTClient) CompleteConversation(ctx context.Context, req } baseUrl.Path += fmt.Sprintf("/v2beta1/%v:complete", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1172,6 +1184,11 @@ func (c *conversationsRESTClient) BatchCreateMessages(ctx context.Context, req * } baseUrl.Path += fmt.Sprintf("/v2beta1/%v/messages:batchCreate", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1242,6 +1259,7 @@ func (c *conversationsRESTClient) ListMessages(ctx context.Context, req *dialogf baseUrl.Path += fmt.Sprintf("/v2beta1/%v/messages", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1326,6 +1344,11 @@ func (c *conversationsRESTClient) SuggestConversationSummary(ctx context.Context } baseUrl.Path += fmt.Sprintf("/v2beta1/%v/suggestions:suggestConversationSummary", req.GetConversation()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "conversation", url.QueryEscape(req.GetConversation()))) @@ -1379,6 +1402,11 @@ func (c *conversationsRESTClient) GetLocation(ctx context.Context, req *location } baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1446,6 +1474,7 @@ func (c *conversationsRESTClient) ListLocations(ctx context.Context, req *locati baseUrl.Path += fmt.Sprintf("/v2beta1/%v/locations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1522,6 +1551,11 @@ func (c *conversationsRESTClient) CancelOperation(ctx context.Context, req *long } baseUrl.Path += fmt.Sprintf("/v2beta1/%v:cancel", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1557,6 +1591,11 @@ func (c *conversationsRESTClient) GetOperation(ctx context.Context, req *longrun } baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1624,6 +1663,7 @@ func (c *conversationsRESTClient) ListOperations(ctx context.Context, req *longr baseUrl.Path += fmt.Sprintf("/v2beta1/%v/operations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/dialogflow/apiv2beta1/documents_client.go b/dialogflow/apiv2beta1/documents_client.go index 46315b0f0576..d31c21a67a3e 100644 --- a/dialogflow/apiv2beta1/documents_client.go +++ b/dialogflow/apiv2beta1/documents_client.go @@ -998,6 +998,7 @@ func (c *documentsRESTClient) ListDocuments(ctx context.Context, req *dialogflow baseUrl.Path += fmt.Sprintf("/v2beta1/%v/documents", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1077,6 +1078,11 @@ func (c *documentsRESTClient) GetDocument(ctx context.Context, req *dialogflowpb } baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1149,6 +1155,7 @@ func (c *documentsRESTClient) CreateDocument(ctx context.Context, req *dialogflo baseUrl.Path += fmt.Sprintf("/v2beta1/%v/documents", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetImportGcsCustomMetadata() { params.Add("importGcsCustomMetadata", fmt.Sprintf("%v", req.GetImportGcsCustomMetadata())) } @@ -1228,6 +1235,11 @@ func (c *documentsRESTClient) ImportDocuments(ctx context.Context, req *dialogfl } baseUrl.Path += fmt.Sprintf("/v2beta1/%v/documents:import", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1297,6 +1309,11 @@ func (c *documentsRESTClient) DeleteDocument(ctx context.Context, req *dialogflo } baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1373,6 +1390,7 @@ func (c *documentsRESTClient) UpdateDocument(ctx context.Context, req *dialogflo baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetDocument().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -1463,6 +1481,11 @@ func (c *documentsRESTClient) ReloadDocument(ctx context.Context, req *dialogflo } baseUrl.Path += fmt.Sprintf("/v2beta1/%v:reload", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1520,6 +1543,11 @@ func (c *documentsRESTClient) GetLocation(ctx context.Context, req *locationpb.G } baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1587,6 +1615,7 @@ func (c *documentsRESTClient) ListLocations(ctx context.Context, req *locationpb baseUrl.Path += fmt.Sprintf("/v2beta1/%v/locations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1663,6 +1692,11 @@ func (c *documentsRESTClient) CancelOperation(ctx context.Context, req *longrunn } baseUrl.Path += fmt.Sprintf("/v2beta1/%v:cancel", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1698,6 +1732,11 @@ func (c *documentsRESTClient) GetOperation(ctx context.Context, req *longrunning } baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1765,6 +1804,7 @@ func (c *documentsRESTClient) ListOperations(ctx context.Context, req *longrunni baseUrl.Path += fmt.Sprintf("/v2beta1/%v/operations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/dialogflow/apiv2beta1/entity_types_client.go b/dialogflow/apiv2beta1/entity_types_client.go index 0ce08ff4b8b5..59255bf301f1 100644 --- a/dialogflow/apiv2beta1/entity_types_client.go +++ b/dialogflow/apiv2beta1/entity_types_client.go @@ -1158,6 +1158,7 @@ func (c *entityTypesRESTClient) ListEntityTypes(ctx context.Context, req *dialog baseUrl.Path += fmt.Sprintf("/v2beta1/%v/entityTypes", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetLanguageCode() != "" { params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) } @@ -1235,6 +1236,7 @@ func (c *entityTypesRESTClient) GetEntityType(ctx context.Context, req *dialogfl baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetLanguageCode() != "" { params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) } @@ -1306,6 +1308,7 @@ func (c *entityTypesRESTClient) CreateEntityType(ctx context.Context, req *dialo baseUrl.Path += fmt.Sprintf("/v2beta1/%v/entityTypes", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetLanguageCode() != "" { params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) } @@ -1377,6 +1380,7 @@ func (c *entityTypesRESTClient) UpdateEntityType(ctx context.Context, req *dialo baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetEntityType().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetLanguageCode() != "" { params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) } @@ -1447,6 +1451,11 @@ func (c *entityTypesRESTClient) DeleteEntityType(ctx context.Context, req *dialo } baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1501,6 +1510,11 @@ func (c *entityTypesRESTClient) BatchUpdateEntityTypes(ctx context.Context, req } baseUrl.Path += fmt.Sprintf("/v2beta1/%v/entityTypes:batchUpdate", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1578,6 +1592,11 @@ func (c *entityTypesRESTClient) BatchDeleteEntityTypes(ctx context.Context, req } baseUrl.Path += fmt.Sprintf("/v2beta1/%v/entityTypes:batchDelete", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1655,6 +1674,11 @@ func (c *entityTypesRESTClient) BatchCreateEntities(ctx context.Context, req *di } baseUrl.Path += fmt.Sprintf("/v2beta1/%v/entities:batchCreate", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1734,6 +1758,11 @@ func (c *entityTypesRESTClient) BatchUpdateEntities(ctx context.Context, req *di } baseUrl.Path += fmt.Sprintf("/v2beta1/%v/entities:batchUpdate", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1811,6 +1840,11 @@ func (c *entityTypesRESTClient) BatchDeleteEntities(ctx context.Context, req *di } baseUrl.Path += fmt.Sprintf("/v2beta1/%v/entities:batchDelete", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1868,6 +1902,11 @@ func (c *entityTypesRESTClient) GetLocation(ctx context.Context, req *locationpb } baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1935,6 +1974,7 @@ func (c *entityTypesRESTClient) ListLocations(ctx context.Context, req *location baseUrl.Path += fmt.Sprintf("/v2beta1/%v/locations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -2011,6 +2051,11 @@ func (c *entityTypesRESTClient) CancelOperation(ctx context.Context, req *longru } baseUrl.Path += fmt.Sprintf("/v2beta1/%v:cancel", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2046,6 +2091,11 @@ func (c *entityTypesRESTClient) GetOperation(ctx context.Context, req *longrunni } baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2113,6 +2163,7 @@ func (c *entityTypesRESTClient) ListOperations(ctx context.Context, req *longrun baseUrl.Path += fmt.Sprintf("/v2beta1/%v/operations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/dialogflow/apiv2beta1/environments_client.go b/dialogflow/apiv2beta1/environments_client.go index d3fd9992e18a..1994531ac354 100644 --- a/dialogflow/apiv2beta1/environments_client.go +++ b/dialogflow/apiv2beta1/environments_client.go @@ -825,6 +825,7 @@ func (c *environmentsRESTClient) ListEnvironments(ctx context.Context, req *dial baseUrl.Path += fmt.Sprintf("/v2beta1/%v/environments", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -898,6 +899,11 @@ func (c *environmentsRESTClient) GetEnvironment(ctx context.Context, req *dialog } baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -959,6 +965,7 @@ func (c *environmentsRESTClient) CreateEnvironment(ctx context.Context, req *dia baseUrl.Path += fmt.Sprintf("/v2beta1/%v/environments", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("environmentId", fmt.Sprintf("%v", req.GetEnvironmentId())) baseUrl.RawQuery = params.Encode() @@ -1035,6 +1042,7 @@ func (c *environmentsRESTClient) UpdateEnvironment(ctx context.Context, req *dia baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetEnvironment().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetAllowLoadToDraftAndDiscardChanges() { params.Add("allowLoadToDraftAndDiscardChanges", fmt.Sprintf("%v", req.GetAllowLoadToDraftAndDiscardChanges())) } @@ -1101,6 +1109,11 @@ func (c *environmentsRESTClient) DeleteEnvironment(ctx context.Context, req *dia } baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1150,6 +1163,7 @@ func (c *environmentsRESTClient) GetEnvironmentHistory(ctx context.Context, req baseUrl.Path += fmt.Sprintf("/v2beta1/%v/history", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -1223,6 +1237,11 @@ func (c *environmentsRESTClient) GetLocation(ctx context.Context, req *locationp } baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1290,6 +1309,7 @@ func (c *environmentsRESTClient) ListLocations(ctx context.Context, req *locatio baseUrl.Path += fmt.Sprintf("/v2beta1/%v/locations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1366,6 +1386,11 @@ func (c *environmentsRESTClient) CancelOperation(ctx context.Context, req *longr } baseUrl.Path += fmt.Sprintf("/v2beta1/%v:cancel", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1401,6 +1426,11 @@ func (c *environmentsRESTClient) GetOperation(ctx context.Context, req *longrunn } baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1468,6 +1498,7 @@ func (c *environmentsRESTClient) ListOperations(ctx context.Context, req *longru baseUrl.Path += fmt.Sprintf("/v2beta1/%v/operations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/dialogflow/apiv2beta1/fulfillments_client.go b/dialogflow/apiv2beta1/fulfillments_client.go index df61dfe733af..3170492c3b77 100644 --- a/dialogflow/apiv2beta1/fulfillments_client.go +++ b/dialogflow/apiv2beta1/fulfillments_client.go @@ -558,6 +558,11 @@ func (c *fulfillmentsRESTClient) GetFulfillment(ctx context.Context, req *dialog } baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -619,6 +624,7 @@ func (c *fulfillmentsRESTClient) UpdateFulfillment(ctx context.Context, req *dia baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetFulfillment().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -682,6 +688,11 @@ func (c *fulfillmentsRESTClient) GetLocation(ctx context.Context, req *locationp } baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -749,6 +760,7 @@ func (c *fulfillmentsRESTClient) ListLocations(ctx context.Context, req *locatio baseUrl.Path += fmt.Sprintf("/v2beta1/%v/locations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -825,6 +837,11 @@ func (c *fulfillmentsRESTClient) CancelOperation(ctx context.Context, req *longr } baseUrl.Path += fmt.Sprintf("/v2beta1/%v:cancel", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -860,6 +877,11 @@ func (c *fulfillmentsRESTClient) GetOperation(ctx context.Context, req *longrunn } baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -927,6 +949,7 @@ func (c *fulfillmentsRESTClient) ListOperations(ctx context.Context, req *longru baseUrl.Path += fmt.Sprintf("/v2beta1/%v/operations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/dialogflow/apiv2beta1/intents_client.go b/dialogflow/apiv2beta1/intents_client.go index 2e804066d560..1094d9437047 100644 --- a/dialogflow/apiv2beta1/intents_client.go +++ b/dialogflow/apiv2beta1/intents_client.go @@ -937,6 +937,7 @@ func (c *intentsRESTClient) ListIntents(ctx context.Context, req *dialogflowpb.L baseUrl.Path += fmt.Sprintf("/v2beta1/%v/intents", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetIntentView() != 0 { params.Add("intentView", fmt.Sprintf("%v", req.GetIntentView())) } @@ -1017,6 +1018,7 @@ func (c *intentsRESTClient) GetIntent(ctx context.Context, req *dialogflowpb.Get baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetIntentView() != 0 { params.Add("intentView", fmt.Sprintf("%v", req.GetIntentView())) } @@ -1091,6 +1093,7 @@ func (c *intentsRESTClient) CreateIntent(ctx context.Context, req *dialogflowpb. baseUrl.Path += fmt.Sprintf("/v2beta1/%v/intents", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetIntentView() != 0 { params.Add("intentView", fmt.Sprintf("%v", req.GetIntentView())) } @@ -1165,6 +1168,7 @@ func (c *intentsRESTClient) UpdateIntent(ctx context.Context, req *dialogflowpb. baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetIntent().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetIntentView() != 0 { params.Add("intentView", fmt.Sprintf("%v", req.GetIntentView())) } @@ -1238,6 +1242,11 @@ func (c *intentsRESTClient) DeleteIntent(ctx context.Context, req *dialogflowpb. } baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1292,6 +1301,11 @@ func (c *intentsRESTClient) BatchUpdateIntents(ctx context.Context, req *dialogf } baseUrl.Path += fmt.Sprintf("/v2beta1/%v/intents:batchUpdate", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1369,6 +1383,11 @@ func (c *intentsRESTClient) BatchDeleteIntents(ctx context.Context, req *dialogf } baseUrl.Path += fmt.Sprintf("/v2beta1/%v/intents:batchDelete", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1426,6 +1445,11 @@ func (c *intentsRESTClient) GetLocation(ctx context.Context, req *locationpb.Get } baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1493,6 +1517,7 @@ func (c *intentsRESTClient) ListLocations(ctx context.Context, req *locationpb.L baseUrl.Path += fmt.Sprintf("/v2beta1/%v/locations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1569,6 +1594,11 @@ func (c *intentsRESTClient) CancelOperation(ctx context.Context, req *longrunnin } baseUrl.Path += fmt.Sprintf("/v2beta1/%v:cancel", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1604,6 +1634,11 @@ func (c *intentsRESTClient) GetOperation(ctx context.Context, req *longrunningpb } baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1671,6 +1706,7 @@ func (c *intentsRESTClient) ListOperations(ctx context.Context, req *longrunning baseUrl.Path += fmt.Sprintf("/v2beta1/%v/operations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/dialogflow/apiv2beta1/knowledge_bases_client.go b/dialogflow/apiv2beta1/knowledge_bases_client.go index 24b3812cc5d0..eaa6d99912aa 100644 --- a/dialogflow/apiv2beta1/knowledge_bases_client.go +++ b/dialogflow/apiv2beta1/knowledge_bases_client.go @@ -759,6 +759,7 @@ func (c *knowledgeBasesRESTClient) ListKnowledgeBases(ctx context.Context, req * baseUrl.Path += fmt.Sprintf("/v2beta1/%v/knowledgeBases", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -838,6 +839,11 @@ func (c *knowledgeBasesRESTClient) GetKnowledgeBase(ctx context.Context, req *di } baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -901,6 +907,11 @@ func (c *knowledgeBasesRESTClient) CreateKnowledgeBase(ctx context.Context, req } baseUrl.Path += fmt.Sprintf("/v2beta1/%v/knowledgeBases", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -958,6 +969,7 @@ func (c *knowledgeBasesRESTClient) DeleteKnowledgeBase(ctx context.Context, req baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetForce() { params.Add("force", fmt.Sprintf("%v", req.GetForce())) } @@ -1010,6 +1022,7 @@ func (c *knowledgeBasesRESTClient) UpdateKnowledgeBase(ctx context.Context, req baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetKnowledgeBase().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -1073,6 +1086,11 @@ func (c *knowledgeBasesRESTClient) GetLocation(ctx context.Context, req *locatio } baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1140,6 +1158,7 @@ func (c *knowledgeBasesRESTClient) ListLocations(ctx context.Context, req *locat baseUrl.Path += fmt.Sprintf("/v2beta1/%v/locations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1216,6 +1235,11 @@ func (c *knowledgeBasesRESTClient) CancelOperation(ctx context.Context, req *lon } baseUrl.Path += fmt.Sprintf("/v2beta1/%v:cancel", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1251,6 +1275,11 @@ func (c *knowledgeBasesRESTClient) GetOperation(ctx context.Context, req *longru } baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1318,6 +1347,7 @@ func (c *knowledgeBasesRESTClient) ListOperations(ctx context.Context, req *long baseUrl.Path += fmt.Sprintf("/v2beta1/%v/operations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/dialogflow/apiv2beta1/participants_client.go b/dialogflow/apiv2beta1/participants_client.go index 82f0bbf2b46a..e487ac5df7c8 100644 --- a/dialogflow/apiv2beta1/participants_client.go +++ b/dialogflow/apiv2beta1/participants_client.go @@ -412,6 +412,8 @@ func (c *ParticipantsClient) AnalyzeContent(ctx context.Context, req *dialogflow // Note: Always use agent versions for production traffic // sent to virtual agents. See Versions and // environments (at https://cloud.google.com/dialogflow/es/docs/agents-versions). +// +// This method is not supported for the REST transport. func (c *ParticipantsClient) StreamingAnalyzeContent(ctx context.Context, opts ...gax.CallOption) (dialogflowpb.Participants_StreamingAnalyzeContentClient, error) { return c.internalClient.StreamingAnalyzeContent(ctx, opts...) } @@ -1090,6 +1092,11 @@ func (c *participantsRESTClient) CreateParticipant(ctx context.Context, req *dia } baseUrl.Path += fmt.Sprintf("/v2beta1/%v/participants", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1143,6 +1150,11 @@ func (c *participantsRESTClient) GetParticipant(ctx context.Context, req *dialog } baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1210,6 +1222,7 @@ func (c *participantsRESTClient) ListParticipants(ctx context.Context, req *dial baseUrl.Path += fmt.Sprintf("/v2beta1/%v/participants", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -1291,6 +1304,7 @@ func (c *participantsRESTClient) UpdateParticipant(ctx context.Context, req *dia baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetParticipant().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -1365,6 +1379,11 @@ func (c *participantsRESTClient) AnalyzeContent(ctx context.Context, req *dialog } baseUrl.Path += fmt.Sprintf("/v2beta1/%v:analyzeContent", req.GetParticipant()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "participant", url.QueryEscape(req.GetParticipant()))) @@ -1425,6 +1444,8 @@ func (c *participantsRESTClient) AnalyzeContent(ctx context.Context, req *dialog // Note: Always use agent versions for production traffic // sent to virtual agents. See Versions and // environments (at https://cloud.google.com/dialogflow/es/docs/agents-versions). +// +// This method is not supported for the REST transport. func (c *participantsRESTClient) StreamingAnalyzeContent(ctx context.Context, opts ...gax.CallOption) (dialogflowpb.Participants_StreamingAnalyzeContentClient, error) { return nil, fmt.Errorf("StreamingAnalyzeContent not yet supported for REST clients") } @@ -1448,6 +1469,11 @@ func (c *participantsRESTClient) SuggestArticles(ctx context.Context, req *dialo } baseUrl.Path += fmt.Sprintf("/v2beta1/%v/suggestions:suggestArticles", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1508,6 +1534,11 @@ func (c *participantsRESTClient) SuggestFaqAnswers(ctx context.Context, req *dia } baseUrl.Path += fmt.Sprintf("/v2beta1/%v/suggestions:suggestFaqAnswers", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1568,6 +1599,11 @@ func (c *participantsRESTClient) SuggestSmartReplies(ctx context.Context, req *d } baseUrl.Path += fmt.Sprintf("/v2beta1/%v/suggestions:suggestSmartReplies", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1655,6 +1691,7 @@ func (c *participantsRESTClient) ListSuggestions(ctx context.Context, req *dialo baseUrl.Path += fmt.Sprintf("/v2beta1/%v/suggestions", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1746,6 +1783,11 @@ func (c *participantsRESTClient) CompileSuggestion(ctx context.Context, req *dia } baseUrl.Path += fmt.Sprintf("/v2beta1/%v/suggestions:compile", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1799,6 +1841,11 @@ func (c *participantsRESTClient) GetLocation(ctx context.Context, req *locationp } baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1866,6 +1913,7 @@ func (c *participantsRESTClient) ListLocations(ctx context.Context, req *locatio baseUrl.Path += fmt.Sprintf("/v2beta1/%v/locations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1942,6 +1990,11 @@ func (c *participantsRESTClient) CancelOperation(ctx context.Context, req *longr } baseUrl.Path += fmt.Sprintf("/v2beta1/%v:cancel", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1977,6 +2030,11 @@ func (c *participantsRESTClient) GetOperation(ctx context.Context, req *longrunn } baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2044,6 +2102,7 @@ func (c *participantsRESTClient) ListOperations(ctx context.Context, req *longru baseUrl.Path += fmt.Sprintf("/v2beta1/%v/operations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/dialogflow/apiv2beta1/session_entity_types_client.go b/dialogflow/apiv2beta1/session_entity_types_client.go index 7b467e5d5af9..0ddcf1bfc4e7 100644 --- a/dialogflow/apiv2beta1/session_entity_types_client.go +++ b/dialogflow/apiv2beta1/session_entity_types_client.go @@ -768,6 +768,7 @@ func (c *sessionEntityTypesRESTClient) ListSessionEntityTypes(ctx context.Contex baseUrl.Path += fmt.Sprintf("/v2beta1/%v/entityTypes", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -845,6 +846,11 @@ func (c *sessionEntityTypesRESTClient) GetSessionEntityType(ctx context.Context, } baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -912,6 +918,11 @@ func (c *sessionEntityTypesRESTClient) CreateSessionEntityType(ctx context.Conte } baseUrl.Path += fmt.Sprintf("/v2beta1/%v/entityTypes", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -977,6 +988,7 @@ func (c *sessionEntityTypesRESTClient) UpdateSessionEntityType(ctx context.Conte baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetSessionEntityType().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -1044,6 +1056,11 @@ func (c *sessionEntityTypesRESTClient) DeleteSessionEntityType(ctx context.Conte } baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1079,6 +1096,11 @@ func (c *sessionEntityTypesRESTClient) GetLocation(ctx context.Context, req *loc } baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1146,6 +1168,7 @@ func (c *sessionEntityTypesRESTClient) ListLocations(ctx context.Context, req *l baseUrl.Path += fmt.Sprintf("/v2beta1/%v/locations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1222,6 +1245,11 @@ func (c *sessionEntityTypesRESTClient) CancelOperation(ctx context.Context, req } baseUrl.Path += fmt.Sprintf("/v2beta1/%v:cancel", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1257,6 +1285,11 @@ func (c *sessionEntityTypesRESTClient) GetOperation(ctx context.Context, req *lo } baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1324,6 +1357,7 @@ func (c *sessionEntityTypesRESTClient) ListOperations(ctx context.Context, req * baseUrl.Path += fmt.Sprintf("/v2beta1/%v/operations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/dialogflow/apiv2beta1/sessions_client.go b/dialogflow/apiv2beta1/sessions_client.go index d16271b7921c..ec85da80b0a2 100644 --- a/dialogflow/apiv2beta1/sessions_client.go +++ b/dialogflow/apiv2beta1/sessions_client.go @@ -196,6 +196,8 @@ func (c *SessionsClient) DetectIntent(ctx context.Context, req *dialogflowpb.Det // Note: Always use agent versions for production traffic. // See Versions and // environments (at https://cloud.google.com/dialogflow/es/docs/agents-versions). +// +// This method is not supported for the REST transport. func (c *SessionsClient) StreamingDetectIntent(ctx context.Context, opts ...gax.CallOption) (dialogflowpb.Sessions_StreamingDetectIntentClient, error) { return c.internalClient.StreamingDetectIntent(ctx, opts...) } @@ -588,6 +590,11 @@ func (c *sessionsRESTClient) DetectIntent(ctx context.Context, req *dialogflowpb } baseUrl.Path += fmt.Sprintf("/v2beta1/%v:detectIntent", req.GetSession()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "session", url.QueryEscape(req.GetSession()))) @@ -647,6 +654,8 @@ func (c *sessionsRESTClient) DetectIntent(ctx context.Context, req *dialogflowpb // Note: Always use agent versions for production traffic. // See Versions and // environments (at https://cloud.google.com/dialogflow/es/docs/agents-versions). +// +// This method is not supported for the REST transport. func (c *sessionsRESTClient) StreamingDetectIntent(ctx context.Context, opts ...gax.CallOption) (dialogflowpb.Sessions_StreamingDetectIntentClient, error) { return nil, fmt.Errorf("StreamingDetectIntent not yet supported for REST clients") } @@ -659,6 +668,11 @@ func (c *sessionsRESTClient) GetLocation(ctx context.Context, req *locationpb.Ge } baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -726,6 +740,7 @@ func (c *sessionsRESTClient) ListLocations(ctx context.Context, req *locationpb. baseUrl.Path += fmt.Sprintf("/v2beta1/%v/locations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -802,6 +817,11 @@ func (c *sessionsRESTClient) CancelOperation(ctx context.Context, req *longrunni } baseUrl.Path += fmt.Sprintf("/v2beta1/%v:cancel", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -837,6 +857,11 @@ func (c *sessionsRESTClient) GetOperation(ctx context.Context, req *longrunningp } baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -904,6 +929,7 @@ func (c *sessionsRESTClient) ListOperations(ctx context.Context, req *longrunnin baseUrl.Path += fmt.Sprintf("/v2beta1/%v/operations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/dialogflow/apiv2beta1/versions_client.go b/dialogflow/apiv2beta1/versions_client.go index 9e71b0999f76..35a2ec780009 100644 --- a/dialogflow/apiv2beta1/versions_client.go +++ b/dialogflow/apiv2beta1/versions_client.go @@ -747,6 +747,7 @@ func (c *versionsRESTClient) ListVersions(ctx context.Context, req *dialogflowpb baseUrl.Path += fmt.Sprintf("/v2beta1/%v/versions", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -820,6 +821,11 @@ func (c *versionsRESTClient) GetVersion(ctx context.Context, req *dialogflowpb.G } baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -882,6 +888,11 @@ func (c *versionsRESTClient) CreateVersion(ctx context.Context, req *dialogflowp } baseUrl.Path += fmt.Sprintf("/v2beta1/%v/versions", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -947,6 +958,7 @@ func (c *versionsRESTClient) UpdateVersion(ctx context.Context, req *dialogflowp baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetVersion().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -1010,6 +1022,11 @@ func (c *versionsRESTClient) DeleteVersion(ctx context.Context, req *dialogflowp } baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1045,6 +1062,11 @@ func (c *versionsRESTClient) GetLocation(ctx context.Context, req *locationpb.Ge } baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1112,6 +1134,7 @@ func (c *versionsRESTClient) ListLocations(ctx context.Context, req *locationpb. baseUrl.Path += fmt.Sprintf("/v2beta1/%v/locations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1188,6 +1211,11 @@ func (c *versionsRESTClient) CancelOperation(ctx context.Context, req *longrunni } baseUrl.Path += fmt.Sprintf("/v2beta1/%v:cancel", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1223,6 +1251,11 @@ func (c *versionsRESTClient) GetOperation(ctx context.Context, req *longrunningp } baseUrl.Path += fmt.Sprintf("/v2beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1290,6 +1323,7 @@ func (c *versionsRESTClient) ListOperations(ctx context.Context, req *longrunnin baseUrl.Path += fmt.Sprintf("/v2beta1/%v/operations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/dialogflow/cx/apiv3/agents_client.go b/dialogflow/cx/apiv3/agents_client.go index 0029a802b6f1..f82d729e9f06 100644 --- a/dialogflow/cx/apiv3/agents_client.go +++ b/dialogflow/cx/apiv3/agents_client.go @@ -17,9 +17,12 @@ package cx import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,15 +30,18 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" structpb "google.golang.org/protobuf/types/known/structpb" ) @@ -181,6 +187,106 @@ func defaultAgentsCallOptions() *AgentsCallOptions { } } +func defaultAgentsRESTCallOptions() *AgentsCallOptions { + return &AgentsCallOptions{ + ListAgents: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetAgent: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateAgent: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UpdateAgent: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeleteAgent: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ExportAgent: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + RestoreAgent: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ValidateAgent: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetAgentValidationResult: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + CancelOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalAgentsClient is an interface that defines the methods available from Dialogflow API. type internalAgentsClient interface { Close() error @@ -466,6 +572,89 @@ func (c *agentsGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type agentsRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing AgentsClient + CallOptions **AgentsCallOptions +} + +// NewAgentsRESTClient creates a new agents rest client. +// +// Service for managing Agents. +func NewAgentsRESTClient(ctx context.Context, opts ...option.ClientOption) (*AgentsClient, error) { + clientOpts := append(defaultAgentsRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultAgentsRESTCallOptions() + c := &agentsRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &AgentsClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultAgentsRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://dialogflow.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://dialogflow.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://dialogflow.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *agentsRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *agentsRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *agentsRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *agentsGRPCClient) ListAgents(ctx context.Context, req *cxpb.ListAgentsRequest, opts ...gax.CallOption) *AgentIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -824,85 +1013,1068 @@ func (c *agentsGRPCClient) ListOperations(ctx context.Context, req *longrunningp return it } -// ExportAgentOperation manages a long-running operation from ExportAgent. -type ExportAgentOperation struct { - lro *longrunning.Operation -} +// ListAgents returns the list of all agents in the specified location. +func (c *agentsRESTClient) ListAgents(ctx context.Context, req *cxpb.ListAgentsRequest, opts ...gax.CallOption) *AgentIterator { + it := &AgentIterator{} + req = proto.Clone(req).(*cxpb.ListAgentsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*cxpb.Agent, string, error) { + resp := &cxpb.ListAgentsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/agents", req.GetParent()) -// ExportAgentOperation returns a new ExportAgentOperation from a given name. -// The name must be that of a previously created ExportAgentOperation, possibly from a different process. -func (c *agentsGRPCClient) ExportAgentOperation(name string) *ExportAgentOperation { - return &ExportAgentOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetAgents(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it } -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *ExportAgentOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*cxpb.ExportAgentResponse, error) { - var resp cxpb.ExportAgentResponse - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { +// GetAgent retrieves the specified agent. +func (c *agentsRESTClient) GetAgent(ctx context.Context, req *cxpb.GetAgentRequest, opts ...gax.CallOption) (*cxpb.Agent, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - return &resp, nil + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetAgent[0:len((*c.CallOptions).GetAgent):len((*c.CallOptions).GetAgent)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cxpb.Agent{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil } -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// CreateAgent creates an agent in the specified location. // -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *ExportAgentOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*cxpb.ExportAgentResponse, error) { - var resp cxpb.ExportAgentResponse - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { +// Note: You should always train flows prior to sending them queries. See the +// training +// documentation (at https://cloud.google.com/dialogflow/cx/docs/concept/training). +func (c *agentsRESTClient) CreateAgent(ctx context.Context, req *cxpb.CreateAgentRequest, opts ...gax.CallOption) (*cxpb.Agent, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetAgent() + jsonReq, err := m.Marshal(body) + if err != nil { return nil, err } - if !op.Done() { - return nil, nil - } - return &resp, nil -} -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *ExportAgentOperation) Metadata() (*structpb.Struct, error) { - var meta structpb.Struct - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - return &meta, nil -} + baseUrl.Path += fmt.Sprintf("/v3/%v/agents", req.GetParent()) -// Done reports whether the long-running operation has completed. -func (op *ExportAgentOperation) Done() bool { - return op.lro.Done() -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") -// 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 *ExportAgentOperation) Name() string { - return op.lro.Name() -} + baseUrl.RawQuery = params.Encode() -// RestoreAgentOperation manages a long-running operation from RestoreAgent. -type RestoreAgentOperation struct { - lro *longrunning.Operation -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) -// RestoreAgentOperation returns a new RestoreAgentOperation from a given name. -// The name must be that of a previously created RestoreAgentOperation, possibly from a different process. -func (c *agentsGRPCClient) RestoreAgentOperation(name string) *RestoreAgentOperation { - return &RestoreAgentOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateAgent[0:len((*c.CallOptions).CreateAgent):len((*c.CallOptions).CreateAgent)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cxpb.Agent{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateAgent updates the specified agent. +// +// Note: You should always train flows prior to sending them queries. See the +// training +// documentation (at https://cloud.google.com/dialogflow/cx/docs/concept/training). +func (c *agentsRESTClient) UpdateAgent(ctx context.Context, req *cxpb.UpdateAgentRequest, opts ...gax.CallOption) (*cxpb.Agent, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetAgent() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetAgent().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "agent.name", url.QueryEscape(req.GetAgent().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateAgent[0:len((*c.CallOptions).UpdateAgent):len((*c.CallOptions).UpdateAgent)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cxpb.Agent{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteAgent deletes the specified agent. +func (c *agentsRESTClient) DeleteAgent(ctx context.Context, req *cxpb.DeleteAgentRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// ExportAgent exports the specified agent to a binary file. +// +// This method is a long-running +// operation (at https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation). +// The returned Operation type has the following method-specific fields: +// +// metadata: An empty Struct +// message (at https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) +// +// response: ExportAgentResponse +func (c *agentsRESTClient) ExportAgent(ctx context.Context, req *cxpb.ExportAgentRequest, opts ...gax.CallOption) (*ExportAgentOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v:export", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v3/%s", resp.GetName()) + return &ExportAgentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// RestoreAgent restores the specified agent from a binary file. +// +// Replaces the current agent with a new one. Note that all existing resources +// in agent (e.g. intents, entity types, flows) will be removed. +// +// This method is a long-running +// operation (at https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation). +// The returned Operation type has the following method-specific fields: +// +// metadata: An empty Struct +// message (at https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) +// +// response: An Empty +// message (at https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) +// +// Note: You should always train flows prior to sending them queries. See the +// training +// documentation (at https://cloud.google.com/dialogflow/cx/docs/concept/training). +func (c *agentsRESTClient) RestoreAgent(ctx context.Context, req *cxpb.RestoreAgentRequest, opts ...gax.CallOption) (*RestoreAgentOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v:restore", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v3/%s", resp.GetName()) + return &RestoreAgentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ValidateAgent validates the specified agent and creates or updates validation results. +// The agent in draft version is validated. Please call this API after the +// training is completed to get the complete validation results. +func (c *agentsRESTClient) ValidateAgent(ctx context.Context, req *cxpb.ValidateAgentRequest, opts ...gax.CallOption) (*cxpb.AgentValidationResult, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v:validate", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).ValidateAgent[0:len((*c.CallOptions).ValidateAgent):len((*c.CallOptions).ValidateAgent)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cxpb.AgentValidationResult{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetAgentValidationResult gets the latest agent validation result. Agent validation is performed +// when ValidateAgent is called. +func (c *agentsRESTClient) GetAgentValidationResult(ctx context.Context, req *cxpb.GetAgentValidationResultRequest, opts ...gax.CallOption) (*cxpb.AgentValidationResult, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetLanguageCode() != "" { + params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetAgentValidationResult[0:len((*c.CallOptions).GetAgentValidationResult):len((*c.CallOptions).GetAgentValidationResult)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cxpb.AgentValidationResult{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetLocation gets information about a location. +func (c *agentsRESTClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *agentsRESTClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *agentsRESTClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v3/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *agentsRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *agentsRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// ExportAgentOperation manages a long-running operation from ExportAgent. +type ExportAgentOperation struct { + lro *longrunning.Operation + pollPath string +} + +// ExportAgentOperation returns a new ExportAgentOperation from a given name. +// The name must be that of a previously created ExportAgentOperation, possibly from a different process. +func (c *agentsGRPCClient) ExportAgentOperation(name string) *ExportAgentOperation { + return &ExportAgentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// ExportAgentOperation returns a new ExportAgentOperation from a given name. +// The name must be that of a previously created ExportAgentOperation, possibly from a different process. +func (c *agentsRESTClient) ExportAgentOperation(name string) *ExportAgentOperation { + override := fmt.Sprintf("/v3/%s", name) + return &ExportAgentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *ExportAgentOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*cxpb.ExportAgentResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp cxpb.ExportAgentResponse + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *ExportAgentOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*cxpb.ExportAgentResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp cxpb.ExportAgentResponse + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *ExportAgentOperation) Metadata() (*structpb.Struct, error) { + var meta structpb.Struct + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *ExportAgentOperation) Done() bool { + return op.lro.Done() +} + +// 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 *ExportAgentOperation) Name() string { + return op.lro.Name() +} + +// RestoreAgentOperation manages a long-running operation from RestoreAgent. +type RestoreAgentOperation struct { + lro *longrunning.Operation + pollPath string +} + +// RestoreAgentOperation returns a new RestoreAgentOperation from a given name. +// The name must be that of a previously created RestoreAgentOperation, possibly from a different process. +func (c *agentsGRPCClient) RestoreAgentOperation(name string) *RestoreAgentOperation { + return &RestoreAgentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// RestoreAgentOperation returns a new RestoreAgentOperation from a given name. +// The name must be that of a previously created RestoreAgentOperation, possibly from a different process. +func (c *agentsRESTClient) RestoreAgentOperation(name string) *RestoreAgentOperation { + override := fmt.Sprintf("/v3/%s", name) + return &RestoreAgentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, } } @@ -910,6 +2082,7 @@ func (c *agentsGRPCClient) RestoreAgentOperation(name string) *RestoreAgentOpera // // See documentation of Poll for error-handling information. func (op *RestoreAgentOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -923,6 +2096,7 @@ func (op *RestoreAgentOperation) Wait(ctx context.Context, opts ...gax.CallOptio // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *RestoreAgentOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } diff --git a/dialogflow/cx/apiv3/agents_client_example_test.go b/dialogflow/cx/apiv3/agents_client_example_test.go index 54b2ee7fec9e..1333cb94e9b4 100644 --- a/dialogflow/cx/apiv3/agents_client_example_test.go +++ b/dialogflow/cx/apiv3/agents_client_example_test.go @@ -43,6 +43,23 @@ func ExampleNewAgentsClient() { _ = c } +func ExampleNewAgentsRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := cx.NewAgentsRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleAgentsClient_ListAgents() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/dialogflow/cx/apiv3/changelogs_client.go b/dialogflow/cx/apiv3/changelogs_client.go index 71399df7646d..abb495e0413e 100644 --- a/dialogflow/cx/apiv3/changelogs_client.go +++ b/dialogflow/cx/apiv3/changelogs_client.go @@ -19,21 +19,26 @@ package cx import ( "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" cxpb "cloud.google.com/go/dialogflow/cx/apiv3/cxpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -94,6 +99,36 @@ func defaultChangelogsCallOptions() *ChangelogsCallOptions { } } +func defaultChangelogsRESTCallOptions() *ChangelogsCallOptions { + return &ChangelogsCallOptions{ + ListChangelogs: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetChangelog: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + CancelOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalChangelogsClient is an interface that defines the methods available from Dialogflow API. type internalChangelogsClient interface { Close() error @@ -265,6 +300,74 @@ func (c *changelogsGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type changelogsRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing ChangelogsClient + CallOptions **ChangelogsCallOptions +} + +// NewChangelogsRESTClient creates a new changelogs rest client. +// +// Service for managing Changelogs. +func NewChangelogsRESTClient(ctx context.Context, opts ...option.ClientOption) (*ChangelogsClient, error) { + clientOpts := append(defaultChangelogsRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultChangelogsRESTCallOptions() + c := &changelogsRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &ChangelogsClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultChangelogsRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://dialogflow.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://dialogflow.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://dialogflow.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *changelogsRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *changelogsRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *changelogsRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *changelogsGRPCClient) ListChangelogs(ctx context.Context, req *cxpb.ListChangelogsRequest, opts ...gax.CallOption) *ChangelogIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -469,6 +572,493 @@ func (c *changelogsGRPCClient) ListOperations(ctx context.Context, req *longrunn return it } +// ListChangelogs returns the list of Changelogs. +func (c *changelogsRESTClient) ListChangelogs(ctx context.Context, req *cxpb.ListChangelogsRequest, opts ...gax.CallOption) *ChangelogIterator { + it := &ChangelogIterator{} + req = proto.Clone(req).(*cxpb.ListChangelogsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*cxpb.Changelog, string, error) { + resp := &cxpb.ListChangelogsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/changelogs", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetChangelogs(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetChangelog retrieves the specified Changelog. +func (c *changelogsRESTClient) GetChangelog(ctx context.Context, req *cxpb.GetChangelogRequest, opts ...gax.CallOption) (*cxpb.Changelog, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetChangelog[0:len((*c.CallOptions).GetChangelog):len((*c.CallOptions).GetChangelog)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cxpb.Changelog{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetLocation gets information about a location. +func (c *changelogsRESTClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *changelogsRESTClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *changelogsRESTClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v3/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *changelogsRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *changelogsRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + // ChangelogIterator manages a stream of *cxpb.Changelog. type ChangelogIterator struct { items []*cxpb.Changelog diff --git a/dialogflow/cx/apiv3/changelogs_client_example_test.go b/dialogflow/cx/apiv3/changelogs_client_example_test.go index 1cc0ec67469f..b8f82b945931 100644 --- a/dialogflow/cx/apiv3/changelogs_client_example_test.go +++ b/dialogflow/cx/apiv3/changelogs_client_example_test.go @@ -43,6 +43,23 @@ func ExampleNewChangelogsClient() { _ = c } +func ExampleNewChangelogsRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := cx.NewChangelogsRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleChangelogsClient_ListChangelogs() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/dialogflow/cx/apiv3/cxpb/advanced_settings.pb.go b/dialogflow/cx/apiv3/cxpb/advanced_settings.pb.go index 701f188d5c75..709d58824ceb 100644 --- a/dialogflow/cx/apiv3/cxpb/advanced_settings.pb.go +++ b/dialogflow/cx/apiv3/cxpb/advanced_settings.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dialogflow/cx/v3/advanced_settings.proto package cxpb diff --git a/dialogflow/cx/apiv3/cxpb/agent.pb.go b/dialogflow/cx/apiv3/cxpb/agent.pb.go index 2b923fa08bb0..33d9819fb424 100644 --- a/dialogflow/cx/apiv3/cxpb/agent.pb.go +++ b/dialogflow/cx/apiv3/cxpb/agent.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dialogflow/cx/v3/agent.proto package cxpb @@ -842,7 +842,6 @@ type ExportAgentResponse struct { // The exported agent. // // Types that are assignable to Agent: - // // *ExportAgentResponse_AgentUri // *ExportAgentResponse_AgentContent Agent isExportAgentResponse_Agent `protobuf_oneof:"agent"` @@ -932,7 +931,6 @@ type RestoreAgentRequest struct { // Required. The agent to restore. // // Types that are assignable to Agent: - // // *RestoreAgentRequest_AgentUri // *RestoreAgentRequest_AgentContent Agent isRestoreAgentRequest_Agent `protobuf_oneof:"agent"` @@ -1873,9 +1871,9 @@ type AgentsClient interface { // operation](https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: An empty [Struct - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) - // - `response`: [ExportAgentResponse][google.cloud.dialogflow.cx.v3.ExportAgentResponse] + // - `metadata`: An empty [Struct + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) + // - `response`: [ExportAgentResponse][google.cloud.dialogflow.cx.v3.ExportAgentResponse] ExportAgent(ctx context.Context, in *ExportAgentRequest, opts ...grpc.CallOption) (*longrunning.Operation, error) // Restores the specified agent from a binary file. // @@ -1886,10 +1884,10 @@ type AgentsClient interface { // operation](https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: An empty [Struct - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) - // - `response`: An [Empty - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) + // - `metadata`: An empty [Struct + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) + // - `response`: An [Empty + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) // // Note: You should always train flows prior to sending them queries. See the // [training @@ -2019,9 +2017,9 @@ type AgentsServer interface { // operation](https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: An empty [Struct - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) - // - `response`: [ExportAgentResponse][google.cloud.dialogflow.cx.v3.ExportAgentResponse] + // - `metadata`: An empty [Struct + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) + // - `response`: [ExportAgentResponse][google.cloud.dialogflow.cx.v3.ExportAgentResponse] ExportAgent(context.Context, *ExportAgentRequest) (*longrunning.Operation, error) // Restores the specified agent from a binary file. // @@ -2032,10 +2030,10 @@ type AgentsServer interface { // operation](https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: An empty [Struct - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) - // - `response`: An [Empty - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) + // - `metadata`: An empty [Struct + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) + // - `response`: An [Empty + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) // // Note: You should always train flows prior to sending them queries. See the // [training diff --git a/dialogflow/cx/apiv3/cxpb/audio_config.pb.go b/dialogflow/cx/apiv3/cxpb/audio_config.pb.go index 98c2d41ad4f1..b49dab30d4f6 100644 --- a/dialogflow/cx/apiv3/cxpb/audio_config.pb.go +++ b/dialogflow/cx/apiv3/cxpb/audio_config.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dialogflow/cx/v3/audio_config.proto package cxpb @@ -159,18 +159,18 @@ const ( SpeechModelVariant_USE_STANDARD SpeechModelVariant = 2 // Use an enhanced model variant: // - // - If an enhanced variant does not exist for the given - // [model][google.cloud.dialogflow.cx.v3.InputAudioConfig.model] and request language, Dialogflow falls - // back to the standard variant. + // * If an enhanced variant does not exist for the given + // [model][google.cloud.dialogflow.cx.v3.InputAudioConfig.model] and request language, Dialogflow falls + // back to the standard variant. // - // The [Cloud Speech - // documentation](https://cloud.google.com/speech-to-text/docs/enhanced-models) - // describes which models have enhanced variants. + // The [Cloud Speech + // documentation](https://cloud.google.com/speech-to-text/docs/enhanced-models) + // describes which models have enhanced variants. // - // - If the API caller isn't eligible for enhanced models, Dialogflow returns - // an error. Please see the [Dialogflow - // docs](https://cloud.google.com/dialogflow/docs/data-logging) - // for how to make your project eligible. + // * If the API caller isn't eligible for enhanced models, Dialogflow returns + // an error. Please see the [Dialogflow + // docs](https://cloud.google.com/dialogflow/docs/data-logging) + // for how to make your project eligible. SpeechModelVariant_USE_ENHANCED SpeechModelVariant = 3 ) diff --git a/dialogflow/cx/apiv3/cxpb/changelog.pb.go b/dialogflow/cx/apiv3/cxpb/changelog.pb.go index 3bd0bc2310f3..03e1960f68d3 100644 --- a/dialogflow/cx/apiv3/cxpb/changelog.pb.go +++ b/dialogflow/cx/apiv3/cxpb/changelog.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dialogflow/cx/v3/changelog.proto package cxpb @@ -52,24 +52,24 @@ type ListChangelogsRequest struct { Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // The filter string. Supports filter by user_email, resource, type and // create_time. Some examples: - // 1. By user email: - // user_email = "someone@google.com" - // 2. By resource name: - // resource = "projects/123/locations/global/agents/456/flows/789" - // 3. By resource display name: - // display_name = "my agent" - // 4. By action: - // action = "Create" - // 5. By type: - // type = "flows" - // 6. By create time. Currently predicates on `create_time` and - // `create_time_epoch_seconds` are supported: - // create_time_epoch_seconds > 1551790877 AND create_time <= - // 2017-01-15T01:30:15.01Z - // 7. Combination of above filters: - // resource = "projects/123/locations/global/agents/456/flows/789" - // AND user_email = "someone@google.com" - // AND create_time <= 2017-01-15T01:30:15.01Z + // 1. By user email: + // user_email = "someone@google.com" + // 2. By resource name: + // resource = "projects/123/locations/global/agents/456/flows/789" + // 3. By resource display name: + // display_name = "my agent" + // 4. By action: + // action = "Create" + // 5. By type: + // type = "flows" + // 6. By create time. Currently predicates on `create_time` and + // `create_time_epoch_seconds` are supported: + // create_time_epoch_seconds > 1551790877 AND create_time <= + // 2017-01-15T01:30:15.01Z + // 7. Combination of above filters: + // resource = "projects/123/locations/global/agents/456/flows/789" + // AND user_email = "someone@google.com" + // AND create_time <= 2017-01-15T01:30:15.01Z Filter string `protobuf:"bytes,2,opt,name=filter,proto3" json:"filter,omitempty"` // The maximum number of items to return in a single page. By default 100 and // at most 1000. diff --git a/dialogflow/cx/apiv3/cxpb/deployment.pb.go b/dialogflow/cx/apiv3/cxpb/deployment.pb.go index be5f60392833..1ae7f9ea143f 100644 --- a/dialogflow/cx/apiv3/cxpb/deployment.pb.go +++ b/dialogflow/cx/apiv3/cxpb/deployment.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dialogflow/cx/v3/deployment.proto package cxpb diff --git a/dialogflow/cx/apiv3/cxpb/entity_type.pb.go b/dialogflow/cx/apiv3/cxpb/entity_type.pb.go index 90b5106e38ab..6fb65f488ed9 100644 --- a/dialogflow/cx/apiv3/cxpb/entity_type.pb.go +++ b/dialogflow/cx/apiv3/cxpb/entity_type.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dialogflow/cx/v3/entity_type.proto package cxpb @@ -690,13 +690,13 @@ type DeleteEntityTypeRequest struct { // This field has no effect for entity type not being used. // For entity types that are used by intents or pages: // - // - If `force` is set to false, an error will be returned with message - // indicating the referencing resources. - // - If `force` is set to true, Dialogflow will remove the entity type, as - // well as any references to the entity type (i.e. Page - // [parameter][google.cloud.dialogflow.cx.v3.Form.Parameter] of the entity type will be changed to - // '@sys.any' and intent [parameter][google.cloud.dialogflow.cx.v3.Intent.Parameter] of the entity type - // will be removed). + // * If `force` is set to false, an error will be returned with message + // indicating the referencing resources. + // * If `force` is set to true, Dialogflow will remove the entity type, as + // well as any references to the entity type (i.e. Page + // [parameter][google.cloud.dialogflow.cx.v3.Form.Parameter] of the entity type will be changed to + // '@sys.any' and intent [parameter][google.cloud.dialogflow.cx.v3.Intent.Parameter] of the entity type + // will be removed). Force bool `protobuf:"varint,2,opt,name=force,proto3" json:"force,omitempty"` } @@ -762,7 +762,7 @@ type EntityType_Entity struct { // // For `KIND_LIST` entity types: // - // - A string that can contain references to other entity types (with or + // * A string that can contain references to other entity types (with or // without aliases). Value string `protobuf:"bytes,1,opt,name=value,proto3" json:"value,omitempty"` // Required. A collection of value synonyms. For example, if the entity type diff --git a/dialogflow/cx/apiv3/cxpb/environment.pb.go b/dialogflow/cx/apiv3/cxpb/environment.pb.go index c1893425f963..cead04cbe273 100644 --- a/dialogflow/cx/apiv3/cxpb/environment.pb.go +++ b/dialogflow/cx/apiv3/cxpb/environment.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dialogflow/cx/v3/environment.proto package cxpb @@ -2214,9 +2214,9 @@ type EnvironmentsClient interface { // operation](https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: An empty [Struct - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) - // - `response`: [Environment][google.cloud.dialogflow.cx.v3.Environment] + // - `metadata`: An empty [Struct + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) + // - `response`: [Environment][google.cloud.dialogflow.cx.v3.Environment] CreateEnvironment(ctx context.Context, in *CreateEnvironmentRequest, opts ...grpc.CallOption) (*longrunning.Operation, error) // Updates the specified [Environment][google.cloud.dialogflow.cx.v3.Environment]. // @@ -2224,9 +2224,9 @@ type EnvironmentsClient interface { // operation](https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: An empty [Struct - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) - // - `response`: [Environment][google.cloud.dialogflow.cx.v3.Environment] + // - `metadata`: An empty [Struct + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) + // - `response`: [Environment][google.cloud.dialogflow.cx.v3.Environment] UpdateEnvironment(ctx context.Context, in *UpdateEnvironmentRequest, opts ...grpc.CallOption) (*longrunning.Operation, error) // Deletes the specified [Environment][google.cloud.dialogflow.cx.v3.Environment]. DeleteEnvironment(ctx context.Context, in *DeleteEnvironmentRequest, opts ...grpc.CallOption) (*emptypb.Empty, error) @@ -2355,9 +2355,9 @@ type EnvironmentsServer interface { // operation](https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: An empty [Struct - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) - // - `response`: [Environment][google.cloud.dialogflow.cx.v3.Environment] + // - `metadata`: An empty [Struct + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) + // - `response`: [Environment][google.cloud.dialogflow.cx.v3.Environment] CreateEnvironment(context.Context, *CreateEnvironmentRequest) (*longrunning.Operation, error) // Updates the specified [Environment][google.cloud.dialogflow.cx.v3.Environment]. // @@ -2365,9 +2365,9 @@ type EnvironmentsServer interface { // operation](https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: An empty [Struct - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) - // - `response`: [Environment][google.cloud.dialogflow.cx.v3.Environment] + // - `metadata`: An empty [Struct + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) + // - `response`: [Environment][google.cloud.dialogflow.cx.v3.Environment] UpdateEnvironment(context.Context, *UpdateEnvironmentRequest) (*longrunning.Operation, error) // Deletes the specified [Environment][google.cloud.dialogflow.cx.v3.Environment]. DeleteEnvironment(context.Context, *DeleteEnvironmentRequest) (*emptypb.Empty, error) diff --git a/dialogflow/cx/apiv3/cxpb/experiment.pb.go b/dialogflow/cx/apiv3/cxpb/experiment.pb.go index fa9104bd3304..c948107325ed 100644 --- a/dialogflow/cx/apiv3/cxpb/experiment.pb.go +++ b/dialogflow/cx/apiv3/cxpb/experiment.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dialogflow/cx/v3/experiment.proto package cxpb @@ -475,7 +475,6 @@ type VariantsHistory struct { // experiment. // // Types that are assignable to Variants: - // // *VariantsHistory_VersionVariants Variants isVariantsHistory_Variants `protobuf_oneof:"variants"` // Update time of the variants. @@ -1157,7 +1156,6 @@ type Experiment_Definition struct { // experiment. // // Types that are assignable to Variants: - // // *Experiment_Definition_VersionVariants Variants isExperiment_Definition_Variants `protobuf_oneof:"variants"` } @@ -1380,7 +1378,6 @@ type Experiment_Result_Metric struct { // The actual value of the metric. // // Types that are assignable to Value: - // // *Experiment_Result_Metric_Ratio // *Experiment_Result_Metric_Count Value isExperiment_Result_Metric_Value `protobuf_oneof:"value"` diff --git a/dialogflow/cx/apiv3/cxpb/flow.pb.go b/dialogflow/cx/apiv3/cxpb/flow.pb.go index 1414e0f038dc..ad8d5a151052 100644 --- a/dialogflow/cx/apiv3/cxpb/flow.pb.go +++ b/dialogflow/cx/apiv3/cxpb/flow.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dialogflow/cx/v3/flow.proto package cxpb @@ -527,13 +527,13 @@ type DeleteFlowRequest struct { // This field has no effect for flows with no incoming transitions. // For flows with incoming transitions: // - // - If `force` is set to false, an error will be returned with message - // indicating the incoming transitions. - // - If `force` is set to true, Dialogflow will remove the flow, as well as - // any transitions to the flow (i.e. [Target - // flow][EventHandler.target_flow] in event handlers or [Target - // flow][TransitionRoute.target_flow] in transition routes that point to - // this flow will be cleared). + // * If `force` is set to false, an error will be returned with message + // indicating the incoming transitions. + // * If `force` is set to true, Dialogflow will remove the flow, as well as + // any transitions to the flow (i.e. [Target + // flow][EventHandler.target_flow] in event handlers or [Target + // flow][TransitionRoute.target_flow] in transition routes that point to + // this flow will be cleared). Force bool `protobuf:"varint,2,opt,name=force,proto3" json:"force,omitempty"` } @@ -1136,7 +1136,6 @@ type ImportFlowRequest struct { // Required. The flow to import. // // Types that are assignable to Flow: - // // *ImportFlowRequest_FlowUri // *ImportFlowRequest_FlowContent Flow isImportFlowRequest_Flow `protobuf_oneof:"flow"` @@ -1375,7 +1374,6 @@ type ExportFlowResponse struct { // The exported flow. // // Types that are assignable to Flow: - // // *ExportFlowResponse_FlowUri // *ExportFlowResponse_FlowContent Flow isExportFlowResponse_Flow `protobuf_oneof:"flow"` @@ -2184,10 +2182,10 @@ type FlowsClient interface { // operation](https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: An empty [Struct - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) - // - `response`: An [Empty - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) + // - `metadata`: An empty [Struct + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) + // - `response`: An [Empty + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) // // Note: You should always train a flow prior to sending it queries. See the // [training @@ -2206,9 +2204,9 @@ type FlowsClient interface { // operation](https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: An empty [Struct - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) - // - `response`: [ImportFlowResponse][google.cloud.dialogflow.cx.v3.ImportFlowResponse] + // - `metadata`: An empty [Struct + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) + // - `response`: [ImportFlowResponse][google.cloud.dialogflow.cx.v3.ImportFlowResponse] // // Note: You should always train a flow prior to sending it queries. See the // [training @@ -2220,9 +2218,9 @@ type FlowsClient interface { // operation](https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: An empty [Struct - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) - // - `response`: [ExportFlowResponse][google.cloud.dialogflow.cx.v3.ExportFlowResponse] + // - `metadata`: An empty [Struct + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) + // - `response`: [ExportFlowResponse][google.cloud.dialogflow.cx.v3.ExportFlowResponse] // // Note that resources (e.g. intents, entities, webhooks) that the flow // references will also be exported. @@ -2354,10 +2352,10 @@ type FlowsServer interface { // operation](https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: An empty [Struct - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) - // - `response`: An [Empty - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) + // - `metadata`: An empty [Struct + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) + // - `response`: An [Empty + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) // // Note: You should always train a flow prior to sending it queries. See the // [training @@ -2376,9 +2374,9 @@ type FlowsServer interface { // operation](https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: An empty [Struct - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) - // - `response`: [ImportFlowResponse][google.cloud.dialogflow.cx.v3.ImportFlowResponse] + // - `metadata`: An empty [Struct + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) + // - `response`: [ImportFlowResponse][google.cloud.dialogflow.cx.v3.ImportFlowResponse] // // Note: You should always train a flow prior to sending it queries. See the // [training @@ -2390,9 +2388,9 @@ type FlowsServer interface { // operation](https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: An empty [Struct - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) - // - `response`: [ExportFlowResponse][google.cloud.dialogflow.cx.v3.ExportFlowResponse] + // - `metadata`: An empty [Struct + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) + // - `response`: [ExportFlowResponse][google.cloud.dialogflow.cx.v3.ExportFlowResponse] // // Note that resources (e.g. intents, entities, webhooks) that the flow // references will also be exported. diff --git a/dialogflow/cx/apiv3/cxpb/fulfillment.pb.go b/dialogflow/cx/apiv3/cxpb/fulfillment.pb.go index b54ad453af78..c9f740ded962 100644 --- a/dialogflow/cx/apiv3/cxpb/fulfillment.pb.go +++ b/dialogflow/cx/apiv3/cxpb/fulfillment.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dialogflow/cx/v3/fulfillment.proto package cxpb @@ -338,7 +338,6 @@ type Fulfillment_ConditionalCases_Case_CaseContent struct { // Either a message is returned or additional cases to be evaluated. // // Types that are assignable to CasesOrMessage: - // // *Fulfillment_ConditionalCases_Case_CaseContent_Message // *Fulfillment_ConditionalCases_Case_CaseContent_AdditionalCases CasesOrMessage isFulfillment_ConditionalCases_Case_CaseContent_CasesOrMessage `protobuf_oneof:"cases_or_message"` diff --git a/dialogflow/cx/apiv3/cxpb/intent.pb.go b/dialogflow/cx/apiv3/cxpb/intent.pb.go index 5ecd3e0ac6fc..a82d758b8eb2 100644 --- a/dialogflow/cx/apiv3/cxpb/intent.pb.go +++ b/dialogflow/cx/apiv3/cxpb/intent.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dialogflow/cx/v3/intent.proto package cxpb @@ -123,11 +123,11 @@ type Intent struct { // The priority of this intent. Higher numbers represent higher // priorities. // - // - If the supplied value is unspecified or 0, the service - // translates the value to 500,000, which corresponds to the - // `Normal` priority in the console. - // - If the supplied value is negative, the intent is ignored - // in runtime detect intent requests. + // - If the supplied value is unspecified or 0, the service + // translates the value to 500,000, which corresponds to the + // `Normal` priority in the console. + // - If the supplied value is negative, the intent is ignored + // in runtime detect intent requests. Priority int32 `protobuf:"varint,5,opt,name=priority,proto3" json:"priority,omitempty"` // Indicates whether this is a fallback intent. Currently only default // fallback intent is allowed in the agent, which is added upon agent @@ -693,8 +693,8 @@ type Intent_TrainingPhrase struct { // If you want to annotate the training phrase, you must create multiple // parts, where the fields of each part are populated in one of two ways: // - // - `Part.text` is set to a part of the phrase that has no parameters. - // - `Part.text` is set to a part of the phrase that you want to annotate, + // - `Part.text` is set to a part of the phrase that has no parameters. + // - `Part.text` is set to a part of the phrase that you want to annotate, // and the `parameter_id` field is set. Parts []*Intent_TrainingPhrase_Part `protobuf:"bytes,2,rep,name=parts,proto3" json:"parts,omitempty"` // Indicates how many times this example was added to the intent. diff --git a/dialogflow/cx/apiv3/cxpb/page.pb.go b/dialogflow/cx/apiv3/cxpb/page.pb.go index 9846cbcbc597..c4f493c2cb25 100644 --- a/dialogflow/cx/apiv3/cxpb/page.pb.go +++ b/dialogflow/cx/apiv3/cxpb/page.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dialogflow/cx/v3/page.proto package cxpb @@ -80,11 +80,11 @@ type Page struct { // Ordered list of [`TransitionRouteGroups`][google.cloud.dialogflow.cx.v3.TransitionRouteGroup] associated // with the page. Transition route groups must be unique within a page. // - // - If multiple transition routes within a page scope refer to the same + // * If multiple transition routes within a page scope refer to the same // intent, then the precedence order is: page's transition route -> page's // transition route group -> flow's transition routes. // - // - If multiple transition route groups within a page contain the same + // * If multiple transition route groups within a page contain the same // intent, then the first group in the ordered list takes precedence. // // Format:`projects//locations//agents/ [OR name = ] ... + // name = [OR name = ] ... // // For example: // - // - "name = t1 OR name = t2" matches the test case with the exact resource + // * "name = t1 OR name = t2" matches the test case with the exact resource // name "t1" or "t2". Filter string `protobuf:"bytes,4,opt,name=filter,proto3" json:"filter,omitempty"` } @@ -2230,7 +2227,6 @@ type ExportTestCasesResponse struct { // The exported test cases. // // Types that are assignable to Destination: - // // *ExportTestCasesResponse_GcsUri // *ExportTestCasesResponse_Content Destination isExportTestCasesResponse_Destination `protobuf_oneof:"destination"` @@ -2372,8 +2368,8 @@ type ListTestCaseResultsRequest struct { // The expression is case insensitive. Only 'AND' is supported for logical // operators. The supported syntax is listed below in detail: // - // [AND ] ... - // [AND latest] + // [AND ] ... + // [AND latest] // // The supported fields and operators are: // field operator @@ -2384,11 +2380,11 @@ type ListTestCaseResultsRequest struct { // case. // // Examples: - // - "environment=draft AND latest" matches the latest test result for each + // * "environment=draft AND latest" matches the latest test result for each // test case in the draft environment. - // - "environment IN (e1,e2)" matches any test case results with an + // * "environment IN (e1,e2)" matches any test case results with an // environment resource name of either "e1" or "e2". - // - "test_time > 1602540713" matches any test case results with test time + // * "test_time > 1602540713" matches any test case results with test time // later than a unix timestamp in seconds 1602540713. Filter string `protobuf:"bytes,4,opt,name=filter,proto3" json:"filter,omitempty"` } @@ -2762,7 +2758,6 @@ type TransitionCoverage_TransitionNode struct { // A TransitionNode can be either a page or a flow. // // Types that are assignable to Kind: - // // *TransitionCoverage_TransitionNode_Page // *TransitionCoverage_TransitionNode_Flow Kind isTransitionCoverage_TransitionNode_Kind `protobuf_oneof:"kind"` @@ -2859,7 +2854,6 @@ type TransitionCoverage_Transition struct { // The detailed transition. // // Types that are assignable to Detail: - // // *TransitionCoverage_Transition_TransitionRoute // *TransitionCoverage_Transition_EventHandler Detail isTransitionCoverage_Transition_Detail `protobuf_oneof:"detail"` diff --git a/dialogflow/cx/apiv3/cxpb/transition_route_group.pb.go b/dialogflow/cx/apiv3/cxpb/transition_route_group.pb.go index f9c1c8a115ef..ac250eb35d24 100644 --- a/dialogflow/cx/apiv3/cxpb/transition_route_group.pb.go +++ b/dialogflow/cx/apiv3/cxpb/transition_route_group.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dialogflow/cx/v3/transition_route_group.proto package cxpb @@ -137,6 +137,7 @@ type ListTransitionRouteGroupsRequest struct { // * // `TransitionRouteGroup.transition_routes.trigger_fulfillment.conditional_cases` // + // // If not specified, the agent's default language is used. // [Many // languages](https://cloud.google.com/dialogflow/cx/docs/reference/language) @@ -507,10 +508,10 @@ type DeleteTransitionRouteGroupRequest struct { // This field has no effect for transition route group that no page is using. // If the transition route group is referenced by any page: // - // - If `force` is set to false, an error will be returned with message - // indicating pages that reference the transition route group. - // - If `force` is set to true, Dialogflow will remove the transition route - // group, as well as any reference to it. + // * If `force` is set to false, an error will be returned with message + // indicating pages that reference the transition route group. + // * If `force` is set to true, Dialogflow will remove the transition route + // group, as well as any reference to it. Force bool `protobuf:"varint,2,opt,name=force,proto3" json:"force,omitempty"` } diff --git a/dialogflow/cx/apiv3/cxpb/validation_message.pb.go b/dialogflow/cx/apiv3/cxpb/validation_message.pb.go index 6488d78fa893..cc29cd60c02f 100644 --- a/dialogflow/cx/apiv3/cxpb/validation_message.pb.go +++ b/dialogflow/cx/apiv3/cxpb/validation_message.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dialogflow/cx/v3/validation_message.proto package cxpb diff --git a/dialogflow/cx/apiv3/cxpb/version.pb.go b/dialogflow/cx/apiv3/cxpb/version.pb.go index 23f51909b8a8..a0a3b1d538b0 100644 --- a/dialogflow/cx/apiv3/cxpb/version.pb.go +++ b/dialogflow/cx/apiv3/cxpb/version.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dialogflow/cx/v3/version.proto package cxpb @@ -1340,10 +1340,10 @@ type VersionsClient interface { // operation](https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: An empty [Struct - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) - // - `response`: An [Empty - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) + // - `metadata`: An empty [Struct + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) + // - `response`: An [Empty + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) LoadVersion(ctx context.Context, in *LoadVersionRequest, opts ...grpc.CallOption) (*longrunning.Operation, error) // Compares the specified base version with target version. CompareVersions(ctx context.Context, in *CompareVersionsRequest, opts ...grpc.CallOption) (*CompareVersionsResponse, error) @@ -1445,10 +1445,10 @@ type VersionsServer interface { // operation](https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: An empty [Struct - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) - // - `response`: An [Empty - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) + // - `metadata`: An empty [Struct + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) + // - `response`: An [Empty + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) LoadVersion(context.Context, *LoadVersionRequest) (*longrunning.Operation, error) // Compares the specified base version with target version. CompareVersions(context.Context, *CompareVersionsRequest) (*CompareVersionsResponse, error) diff --git a/dialogflow/cx/apiv3/cxpb/webhook.pb.go b/dialogflow/cx/apiv3/cxpb/webhook.pb.go index daf17a781358..1c1b0aa3a3fd 100644 --- a/dialogflow/cx/apiv3/cxpb/webhook.pb.go +++ b/dialogflow/cx/apiv3/cxpb/webhook.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dialogflow/cx/v3/webhook.proto package cxpb @@ -178,7 +178,6 @@ type Webhook struct { // Required. The webhook configuration. // // Types that are assignable to Webhook: - // // *Webhook_GenericWebService_ // *Webhook_ServiceDirectory Webhook isWebhook_Webhook `protobuf_oneof:"webhook"` @@ -601,12 +600,12 @@ type DeleteWebhookRequest struct { // This field has no effect for webhook not being used. // For webhooks that are used by pages/flows/transition route groups: // - // - If `force` is set to false, an error will be returned with message - // indicating the referenced resources. - // - If `force` is set to true, Dialogflow will remove the webhook, as well - // as any references to the webhook (i.e. [Webhook][google.cloud.dialogflow.cx.v3.Fulfillment.webhook] - // and [tag][google.cloud.dialogflow.cx.v3.Fulfillment.tag]in fulfillments that point to this webhook - // will be removed). + // * If `force` is set to false, an error will be returned with message + // indicating the referenced resources. + // * If `force` is set to true, Dialogflow will remove the webhook, as well + // as any references to the webhook (i.e. [Webhook][google.cloud.dialogflow.cx.v3.Fulfillment.webhook] + // and [tag][google.cloud.dialogflow.cx.v3.Fulfillment.tag]in fulfillments that point to this webhook + // will be removed). Force bool `protobuf:"varint,2,opt,name=force,proto3" json:"force,omitempty"` } @@ -672,7 +671,6 @@ type WebhookRequest struct { // The original conversational query. // // Types that are assignable to Query: - // // *WebhookRequest_Text // *WebhookRequest_TriggerIntent // *WebhookRequest_Transcript @@ -891,7 +889,6 @@ type WebhookResponse struct { // different flow in the same agent. // // Types that are assignable to Transition: - // // *WebhookResponse_TargetPage // *WebhookResponse_TargetFlow Transition isWebhookResponse_Transition `protobuf_oneof:"transition"` @@ -1168,12 +1165,10 @@ type Webhook_GenericWebService struct { // name". For instance a certificate can be self-signed using the following // command, // ``` - // - // openssl x509 -req -days 200 -in example.com.csr \ - // -signkey example.com.key \ - // -out example.com.crt \ - // -extfile <(printf "\nsubjectAltName='DNS:www.example.com'") - // + // openssl x509 -req -days 200 -in example.com.csr \ + // -signkey example.com.key \ + // -out example.com.crt \ + // -extfile <(printf "\nsubjectAltName='DNS:www.example.com'") // ``` AllowedCaCerts [][]byte `protobuf:"bytes,5,rep,name=allowed_ca_certs,json=allowedCaCerts,proto3" json:"allowed_ca_certs,omitempty"` } diff --git a/dialogflow/cx/apiv3/deployments_client.go b/dialogflow/cx/apiv3/deployments_client.go index d9399c7b9b8b..9a6f8f2d70dc 100644 --- a/dialogflow/cx/apiv3/deployments_client.go +++ b/dialogflow/cx/apiv3/deployments_client.go @@ -19,21 +19,26 @@ package cx import ( "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" cxpb "cloud.google.com/go/dialogflow/cx/apiv3/cxpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -94,6 +99,36 @@ func defaultDeploymentsCallOptions() *DeploymentsCallOptions { } } +func defaultDeploymentsRESTCallOptions() *DeploymentsCallOptions { + return &DeploymentsCallOptions{ + ListDeployments: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetDeployment: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + CancelOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalDeploymentsClient is an interface that defines the methods available from Dialogflow API. type internalDeploymentsClient interface { Close() error @@ -265,6 +300,74 @@ func (c *deploymentsGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type deploymentsRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing DeploymentsClient + CallOptions **DeploymentsCallOptions +} + +// NewDeploymentsRESTClient creates a new deployments rest client. +// +// Service for managing Deployments. +func NewDeploymentsRESTClient(ctx context.Context, opts ...option.ClientOption) (*DeploymentsClient, error) { + clientOpts := append(defaultDeploymentsRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultDeploymentsRESTCallOptions() + c := &deploymentsRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &DeploymentsClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultDeploymentsRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://dialogflow.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://dialogflow.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://dialogflow.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *deploymentsRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *deploymentsRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *deploymentsRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *deploymentsGRPCClient) ListDeployments(ctx context.Context, req *cxpb.ListDeploymentsRequest, opts ...gax.CallOption) *DeploymentIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -469,6 +572,490 @@ func (c *deploymentsGRPCClient) ListOperations(ctx context.Context, req *longrun return it } +// ListDeployments returns the list of all deployments in the specified Environment. +func (c *deploymentsRESTClient) ListDeployments(ctx context.Context, req *cxpb.ListDeploymentsRequest, opts ...gax.CallOption) *DeploymentIterator { + it := &DeploymentIterator{} + req = proto.Clone(req).(*cxpb.ListDeploymentsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*cxpb.Deployment, string, error) { + resp := &cxpb.ListDeploymentsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/deployments", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetDeployments(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetDeployment retrieves the specified Deployment. +func (c *deploymentsRESTClient) GetDeployment(ctx context.Context, req *cxpb.GetDeploymentRequest, opts ...gax.CallOption) (*cxpb.Deployment, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetDeployment[0:len((*c.CallOptions).GetDeployment):len((*c.CallOptions).GetDeployment)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cxpb.Deployment{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetLocation gets information about a location. +func (c *deploymentsRESTClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *deploymentsRESTClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *deploymentsRESTClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v3/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *deploymentsRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *deploymentsRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + // DeploymentIterator manages a stream of *cxpb.Deployment. type DeploymentIterator struct { items []*cxpb.Deployment diff --git a/dialogflow/cx/apiv3/deployments_client_example_test.go b/dialogflow/cx/apiv3/deployments_client_example_test.go index c1ab6c252d39..8f20d06eeada 100644 --- a/dialogflow/cx/apiv3/deployments_client_example_test.go +++ b/dialogflow/cx/apiv3/deployments_client_example_test.go @@ -43,6 +43,23 @@ func ExampleNewDeploymentsClient() { _ = c } +func ExampleNewDeploymentsRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := cx.NewDeploymentsRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleDeploymentsClient_ListDeployments() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/dialogflow/cx/apiv3/doc.go b/dialogflow/cx/apiv3/doc.go index 134556a86c93..ac040af40bfe 100644 --- a/dialogflow/cx/apiv3/doc.go +++ b/dialogflow/cx/apiv3/doc.go @@ -87,6 +87,8 @@ package cx // import "cloud.google.com/go/dialogflow/cx/apiv3" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -176,3 +178,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/dialogflow/cx/apiv3/entity_types_client.go b/dialogflow/cx/apiv3/entity_types_client.go index 308d04fa98f4..9592954f8b87 100644 --- a/dialogflow/cx/apiv3/entity_types_client.go +++ b/dialogflow/cx/apiv3/entity_types_client.go @@ -17,23 +17,29 @@ package cx import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" cxpb "cloud.google.com/go/dialogflow/cx/apiv3/cxpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -130,6 +136,66 @@ func defaultEntityTypesCallOptions() *EntityTypesCallOptions { } } +func defaultEntityTypesRESTCallOptions() *EntityTypesCallOptions { + return &EntityTypesCallOptions{ + ListEntityTypes: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetEntityType: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateEntityType: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UpdateEntityType: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeleteEntityType: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + CancelOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalEntityTypesClient is an interface that defines the methods available from Dialogflow API. type internalEntityTypesClient interface { Close() error @@ -331,6 +397,74 @@ func (c *entityTypesGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type entityTypesRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing EntityTypesClient + CallOptions **EntityTypesCallOptions +} + +// NewEntityTypesRESTClient creates a new entity types rest client. +// +// Service for managing EntityTypes. +func NewEntityTypesRESTClient(ctx context.Context, opts ...option.ClientOption) (*EntityTypesClient, error) { + clientOpts := append(defaultEntityTypesRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultEntityTypesRESTCallOptions() + c := &entityTypesRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &EntityTypesClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultEntityTypesRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://dialogflow.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://dialogflow.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://dialogflow.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *entityTypesRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *entityTypesRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *entityTypesRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *entityTypesGRPCClient) ListEntityTypes(ctx context.Context, req *cxpb.ListEntityTypesRequest, opts ...gax.CallOption) *EntityTypeIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -597,6 +731,694 @@ func (c *entityTypesGRPCClient) ListOperations(ctx context.Context, req *longrun return it } +// ListEntityTypes returns the list of all entity types in the specified agent. +func (c *entityTypesRESTClient) ListEntityTypes(ctx context.Context, req *cxpb.ListEntityTypesRequest, opts ...gax.CallOption) *EntityTypeIterator { + it := &EntityTypeIterator{} + req = proto.Clone(req).(*cxpb.ListEntityTypesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*cxpb.EntityType, string, error) { + resp := &cxpb.ListEntityTypesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/entityTypes", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetLanguageCode() != "" { + params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetEntityTypes(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetEntityType retrieves the specified entity type. +func (c *entityTypesRESTClient) GetEntityType(ctx context.Context, req *cxpb.GetEntityTypeRequest, opts ...gax.CallOption) (*cxpb.EntityType, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetLanguageCode() != "" { + params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetEntityType[0:len((*c.CallOptions).GetEntityType):len((*c.CallOptions).GetEntityType)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cxpb.EntityType{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateEntityType creates an entity type in the specified agent. +// +// Note: You should always train a flow prior to sending it queries. See the +// training +// documentation (at https://cloud.google.com/dialogflow/cx/docs/concept/training). +func (c *entityTypesRESTClient) CreateEntityType(ctx context.Context, req *cxpb.CreateEntityTypeRequest, opts ...gax.CallOption) (*cxpb.EntityType, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetEntityType() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/entityTypes", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetLanguageCode() != "" { + params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateEntityType[0:len((*c.CallOptions).CreateEntityType):len((*c.CallOptions).CreateEntityType)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cxpb.EntityType{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateEntityType updates the specified entity type. +// +// Note: You should always train a flow prior to sending it queries. See the +// training +// documentation (at https://cloud.google.com/dialogflow/cx/docs/concept/training). +func (c *entityTypesRESTClient) UpdateEntityType(ctx context.Context, req *cxpb.UpdateEntityTypeRequest, opts ...gax.CallOption) (*cxpb.EntityType, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetEntityType() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetEntityType().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetLanguageCode() != "" { + params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) + } + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "entity_type.name", url.QueryEscape(req.GetEntityType().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateEntityType[0:len((*c.CallOptions).UpdateEntityType):len((*c.CallOptions).UpdateEntityType)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cxpb.EntityType{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteEntityType deletes the specified entity type. +// +// Note: You should always train a flow prior to sending it queries. See the +// training +// documentation (at https://cloud.google.com/dialogflow/cx/docs/concept/training). +func (c *entityTypesRESTClient) DeleteEntityType(ctx context.Context, req *cxpb.DeleteEntityTypeRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetForce() { + params.Add("force", fmt.Sprintf("%v", req.GetForce())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetLocation gets information about a location. +func (c *entityTypesRESTClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *entityTypesRESTClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *entityTypesRESTClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v3/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *entityTypesRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *entityTypesRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + // EntityTypeIterator manages a stream of *cxpb.EntityType. type EntityTypeIterator struct { items []*cxpb.EntityType diff --git a/dialogflow/cx/apiv3/entity_types_client_example_test.go b/dialogflow/cx/apiv3/entity_types_client_example_test.go index eae160d4ff3b..2a325d1c516a 100644 --- a/dialogflow/cx/apiv3/entity_types_client_example_test.go +++ b/dialogflow/cx/apiv3/entity_types_client_example_test.go @@ -43,6 +43,23 @@ func ExampleNewEntityTypesClient() { _ = c } +func ExampleNewEntityTypesRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := cx.NewEntityTypesRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleEntityTypesClient_ListEntityTypes() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/dialogflow/cx/apiv3/environments_client.go b/dialogflow/cx/apiv3/environments_client.go index e293585c3f94..4aee3671804a 100644 --- a/dialogflow/cx/apiv3/environments_client.go +++ b/dialogflow/cx/apiv3/environments_client.go @@ -17,9 +17,12 @@ package cx import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,15 +30,18 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" structpb "google.golang.org/protobuf/types/known/structpb" ) @@ -181,6 +187,106 @@ func defaultEnvironmentsCallOptions() *EnvironmentsCallOptions { } } +func defaultEnvironmentsRESTCallOptions() *EnvironmentsCallOptions { + return &EnvironmentsCallOptions{ + ListEnvironments: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetEnvironment: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateEnvironment: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UpdateEnvironment: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeleteEnvironment: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + LookupEnvironmentHistory: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + RunContinuousTest: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListContinuousTestResults: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeployFlow: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + CancelOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalEnvironmentsClient is an interface that defines the methods available from Dialogflow API. type internalEnvironmentsClient interface { Close() error @@ -477,6 +583,89 @@ func (c *environmentsGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type environmentsRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing EnvironmentsClient + CallOptions **EnvironmentsCallOptions +} + +// NewEnvironmentsRESTClient creates a new environments rest client. +// +// Service for managing Environments. +func NewEnvironmentsRESTClient(ctx context.Context, opts ...option.ClientOption) (*EnvironmentsClient, error) { + clientOpts := append(defaultEnvironmentsRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultEnvironmentsRESTCallOptions() + c := &environmentsRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &EnvironmentsClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultEnvironmentsRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://dialogflow.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://dialogflow.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://dialogflow.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *environmentsRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *environmentsRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *environmentsRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *environmentsGRPCClient) ListEnvironments(ctx context.Context, req *cxpb.ListEnvironmentsRequest, opts ...gax.CallOption) *EnvironmentIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -885,92 +1074,1132 @@ func (c *environmentsGRPCClient) ListOperations(ctx context.Context, req *longru return it } -// CreateEnvironmentOperation manages a long-running operation from CreateEnvironment. -type CreateEnvironmentOperation struct { - lro *longrunning.Operation -} +// ListEnvironments returns the list of all environments in the specified Agent. +func (c *environmentsRESTClient) ListEnvironments(ctx context.Context, req *cxpb.ListEnvironmentsRequest, opts ...gax.CallOption) *EnvironmentIterator { + it := &EnvironmentIterator{} + req = proto.Clone(req).(*cxpb.ListEnvironmentsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*cxpb.Environment, string, error) { + resp := &cxpb.ListEnvironmentsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/environments", req.GetParent()) -// CreateEnvironmentOperation returns a new CreateEnvironmentOperation from a given name. -// The name must be that of a previously created CreateEnvironmentOperation, possibly from a different process. -func (c *environmentsGRPCClient) CreateEnvironmentOperation(name string) *CreateEnvironmentOperation { - return &CreateEnvironmentOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetEnvironments(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it } -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *CreateEnvironmentOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*cxpb.Environment, error) { - var resp cxpb.Environment - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { +// GetEnvironment retrieves the specified Environment. +func (c *environmentsRESTClient) GetEnvironment(ctx context.Context, req *cxpb.GetEnvironmentRequest, opts ...gax.CallOption) (*cxpb.Environment, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - return &resp, nil + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetEnvironment[0:len((*c.CallOptions).GetEnvironment):len((*c.CallOptions).GetEnvironment)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cxpb.Environment{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil } -// Poll fetches the latest state of the long-running operation. +// CreateEnvironment creates an Environment in the specified Agent. // -// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// This method is a long-running +// operation (at https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation). +// The returned Operation type has the following method-specific fields: // -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *CreateEnvironmentOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*cxpb.Environment, error) { - var resp cxpb.Environment - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { +// metadata: An empty Struct +// message (at https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) +// +// response: Environment +func (c *environmentsRESTClient) CreateEnvironment(ctx context.Context, req *cxpb.CreateEnvironmentRequest, opts ...gax.CallOption) (*CreateEnvironmentOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetEnvironment() + jsonReq, err := m.Marshal(body) + if err != nil { return nil, err } - if !op.Done() { - return nil, nil - } - return &resp, nil -} -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *CreateEnvironmentOperation) Metadata() (*structpb.Struct, error) { - var meta structpb.Struct - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - return &meta, nil -} + baseUrl.Path += fmt.Sprintf("/v3/%v/environments", req.GetParent()) -// Done reports whether the long-running operation has completed. -func (op *CreateEnvironmentOperation) Done() bool { - return op.lro.Done() -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") -// 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 *CreateEnvironmentOperation) Name() string { - return op.lro.Name() -} + baseUrl.RawQuery = params.Encode() -// DeployFlowOperation manages a long-running operation from DeployFlow. -type DeployFlowOperation struct { - lro *longrunning.Operation -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) -// DeployFlowOperation returns a new DeployFlowOperation from a given name. -// The name must be that of a previously created DeployFlowOperation, possibly from a different process. + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v3/%s", resp.GetName()) + return &CreateEnvironmentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateEnvironment updates the specified Environment. +// +// This method is a long-running +// operation (at https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation). +// The returned Operation type has the following method-specific fields: +// +// metadata: An empty Struct +// message (at https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) +// +// response: Environment +func (c *environmentsRESTClient) UpdateEnvironment(ctx context.Context, req *cxpb.UpdateEnvironmentRequest, opts ...gax.CallOption) (*UpdateEnvironmentOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetEnvironment() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetEnvironment().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "environment.name", url.QueryEscape(req.GetEnvironment().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v3/%s", resp.GetName()) + return &UpdateEnvironmentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteEnvironment deletes the specified Environment. +func (c *environmentsRESTClient) DeleteEnvironment(ctx context.Context, req *cxpb.DeleteEnvironmentRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// LookupEnvironmentHistory looks up the history of the specified Environment. +func (c *environmentsRESTClient) LookupEnvironmentHistory(ctx context.Context, req *cxpb.LookupEnvironmentHistoryRequest, opts ...gax.CallOption) *EnvironmentIterator { + it := &EnvironmentIterator{} + req = proto.Clone(req).(*cxpb.LookupEnvironmentHistoryRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*cxpb.Environment, string, error) { + resp := &cxpb.LookupEnvironmentHistoryResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v:lookupEnvironmentHistory", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetEnvironments(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// RunContinuousTest kicks off a continuous test under the specified Environment. +// +// This method is a long-running +// operation (at https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation). +// The returned Operation type has the following method-specific fields: +// +// metadata: RunContinuousTestMetadata +// +// response: RunContinuousTestResponse +func (c *environmentsRESTClient) RunContinuousTest(ctx context.Context, req *cxpb.RunContinuousTestRequest, opts ...gax.CallOption) (*RunContinuousTestOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v:runContinuousTest", req.GetEnvironment()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "environment", url.QueryEscape(req.GetEnvironment()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v3/%s", resp.GetName()) + return &RunContinuousTestOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListContinuousTestResults fetches a list of continuous test results for a given environment. +func (c *environmentsRESTClient) ListContinuousTestResults(ctx context.Context, req *cxpb.ListContinuousTestResultsRequest, opts ...gax.CallOption) *ContinuousTestResultIterator { + it := &ContinuousTestResultIterator{} + req = proto.Clone(req).(*cxpb.ListContinuousTestResultsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*cxpb.ContinuousTestResult, string, error) { + resp := &cxpb.ListContinuousTestResultsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/continuousTestResults", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetContinuousTestResults(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// DeployFlow deploys a flow to the specified Environment. +// +// This method is a long-running +// operation (at https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation). +// The returned Operation type has the following method-specific fields: +// +// metadata: DeployFlowMetadata +// +// response: DeployFlowResponse +func (c *environmentsRESTClient) DeployFlow(ctx context.Context, req *cxpb.DeployFlowRequest, opts ...gax.CallOption) (*DeployFlowOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v:deployFlow", req.GetEnvironment()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "environment", url.QueryEscape(req.GetEnvironment()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v3/%s", resp.GetName()) + return &DeployFlowOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetLocation gets information about a location. +func (c *environmentsRESTClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *environmentsRESTClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *environmentsRESTClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v3/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *environmentsRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *environmentsRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CreateEnvironmentOperation manages a long-running operation from CreateEnvironment. +type CreateEnvironmentOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateEnvironmentOperation returns a new CreateEnvironmentOperation from a given name. +// The name must be that of a previously created CreateEnvironmentOperation, possibly from a different process. +func (c *environmentsGRPCClient) CreateEnvironmentOperation(name string) *CreateEnvironmentOperation { + return &CreateEnvironmentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateEnvironmentOperation returns a new CreateEnvironmentOperation from a given name. +// The name must be that of a previously created CreateEnvironmentOperation, possibly from a different process. +func (c *environmentsRESTClient) CreateEnvironmentOperation(name string) *CreateEnvironmentOperation { + override := fmt.Sprintf("/v3/%s", name) + return &CreateEnvironmentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CreateEnvironmentOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*cxpb.Environment, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp cxpb.Environment + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *CreateEnvironmentOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*cxpb.Environment, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp cxpb.Environment + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *CreateEnvironmentOperation) Metadata() (*structpb.Struct, error) { + var meta structpb.Struct + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *CreateEnvironmentOperation) Done() bool { + return op.lro.Done() +} + +// 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 *CreateEnvironmentOperation) Name() string { + return op.lro.Name() +} + +// DeployFlowOperation manages a long-running operation from DeployFlow. +type DeployFlowOperation struct { + lro *longrunning.Operation + pollPath string +} + +// DeployFlowOperation returns a new DeployFlowOperation from a given name. +// The name must be that of a previously created DeployFlowOperation, possibly from a different process. func (c *environmentsGRPCClient) DeployFlowOperation(name string) *DeployFlowOperation { return &DeployFlowOperation{ lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } +// DeployFlowOperation returns a new DeployFlowOperation from a given name. +// The name must be that of a previously created DeployFlowOperation, possibly from a different process. +func (c *environmentsRESTClient) DeployFlowOperation(name string) *DeployFlowOperation { + override := fmt.Sprintf("/v3/%s", name) + return &DeployFlowOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeployFlowOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*cxpb.DeployFlowResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp cxpb.DeployFlowResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -988,6 +2217,7 @@ func (op *DeployFlowOperation) Wait(ctx context.Context, opts ...gax.CallOption) // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeployFlowOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*cxpb.DeployFlowResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp cxpb.DeployFlowResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1025,7 +2255,8 @@ func (op *DeployFlowOperation) Name() string { // RunContinuousTestOperation manages a long-running operation from RunContinuousTest. type RunContinuousTestOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // RunContinuousTestOperation returns a new RunContinuousTestOperation from a given name. @@ -1036,10 +2267,21 @@ func (c *environmentsGRPCClient) RunContinuousTestOperation(name string) *RunCon } } +// RunContinuousTestOperation returns a new RunContinuousTestOperation from a given name. +// The name must be that of a previously created RunContinuousTestOperation, possibly from a different process. +func (c *environmentsRESTClient) RunContinuousTestOperation(name string) *RunContinuousTestOperation { + override := fmt.Sprintf("/v3/%s", name) + return &RunContinuousTestOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *RunContinuousTestOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*cxpb.RunContinuousTestResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp cxpb.RunContinuousTestResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1057,6 +2299,7 @@ func (op *RunContinuousTestOperation) Wait(ctx context.Context, opts ...gax.Call // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *RunContinuousTestOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*cxpb.RunContinuousTestResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp cxpb.RunContinuousTestResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1094,7 +2337,8 @@ func (op *RunContinuousTestOperation) Name() string { // UpdateEnvironmentOperation manages a long-running operation from UpdateEnvironment. type UpdateEnvironmentOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateEnvironmentOperation returns a new UpdateEnvironmentOperation from a given name. @@ -1105,10 +2349,21 @@ func (c *environmentsGRPCClient) UpdateEnvironmentOperation(name string) *Update } } +// UpdateEnvironmentOperation returns a new UpdateEnvironmentOperation from a given name. +// The name must be that of a previously created UpdateEnvironmentOperation, possibly from a different process. +func (c *environmentsRESTClient) UpdateEnvironmentOperation(name string) *UpdateEnvironmentOperation { + override := fmt.Sprintf("/v3/%s", name) + return &UpdateEnvironmentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateEnvironmentOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*cxpb.Environment, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp cxpb.Environment if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1126,6 +2381,7 @@ func (op *UpdateEnvironmentOperation) Wait(ctx context.Context, opts ...gax.Call // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateEnvironmentOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*cxpb.Environment, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp cxpb.Environment if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/dialogflow/cx/apiv3/environments_client_example_test.go b/dialogflow/cx/apiv3/environments_client_example_test.go index 2b41daa576d4..03de040fcc70 100644 --- a/dialogflow/cx/apiv3/environments_client_example_test.go +++ b/dialogflow/cx/apiv3/environments_client_example_test.go @@ -43,6 +43,23 @@ func ExampleNewEnvironmentsClient() { _ = c } +func ExampleNewEnvironmentsRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := cx.NewEnvironmentsRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleEnvironmentsClient_ListEnvironments() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/dialogflow/cx/apiv3/experiments_client.go b/dialogflow/cx/apiv3/experiments_client.go index da2783b46031..45640c4fb125 100644 --- a/dialogflow/cx/apiv3/experiments_client.go +++ b/dialogflow/cx/apiv3/experiments_client.go @@ -17,23 +17,29 @@ package cx import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" cxpb "cloud.google.com/go/dialogflow/cx/apiv3/cxpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -154,6 +160,86 @@ func defaultExperimentsCallOptions() *ExperimentsCallOptions { } } +func defaultExperimentsRESTCallOptions() *ExperimentsCallOptions { + return &ExperimentsCallOptions{ + ListExperiments: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetExperiment: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateExperiment: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UpdateExperiment: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeleteExperiment: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + StartExperiment: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + StopExperiment: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + CancelOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalExperimentsClient is an interface that defines the methods available from Dialogflow API. type internalExperimentsClient interface { Close() error @@ -357,6 +443,74 @@ func (c *experimentsGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type experimentsRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing ExperimentsClient + CallOptions **ExperimentsCallOptions +} + +// NewExperimentsRESTClient creates a new experiments rest client. +// +// Service for managing Experiments. +func NewExperimentsRESTClient(ctx context.Context, opts ...option.ClientOption) (*ExperimentsClient, error) { + clientOpts := append(defaultExperimentsRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultExperimentsRESTCallOptions() + c := &experimentsRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &ExperimentsClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultExperimentsRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://dialogflow.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://dialogflow.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://dialogflow.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *experimentsRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *experimentsRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *experimentsRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *experimentsGRPCClient) ListExperiments(ctx context.Context, req *cxpb.ListExperimentsRequest, opts ...gax.CallOption) *ExperimentIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -667,6 +821,797 @@ func (c *experimentsGRPCClient) ListOperations(ctx context.Context, req *longrun return it } +// ListExperiments returns the list of all experiments in the specified Environment. +func (c *experimentsRESTClient) ListExperiments(ctx context.Context, req *cxpb.ListExperimentsRequest, opts ...gax.CallOption) *ExperimentIterator { + it := &ExperimentIterator{} + req = proto.Clone(req).(*cxpb.ListExperimentsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*cxpb.Experiment, string, error) { + resp := &cxpb.ListExperimentsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/experiments", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetExperiments(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetExperiment retrieves the specified Experiment. +func (c *experimentsRESTClient) GetExperiment(ctx context.Context, req *cxpb.GetExperimentRequest, opts ...gax.CallOption) (*cxpb.Experiment, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetExperiment[0:len((*c.CallOptions).GetExperiment):len((*c.CallOptions).GetExperiment)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cxpb.Experiment{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateExperiment creates an Experiment in the specified Environment. +func (c *experimentsRESTClient) CreateExperiment(ctx context.Context, req *cxpb.CreateExperimentRequest, opts ...gax.CallOption) (*cxpb.Experiment, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetExperiment() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/experiments", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateExperiment[0:len((*c.CallOptions).CreateExperiment):len((*c.CallOptions).CreateExperiment)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cxpb.Experiment{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateExperiment updates the specified Experiment. +func (c *experimentsRESTClient) UpdateExperiment(ctx context.Context, req *cxpb.UpdateExperimentRequest, opts ...gax.CallOption) (*cxpb.Experiment, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetExperiment() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetExperiment().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "experiment.name", url.QueryEscape(req.GetExperiment().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateExperiment[0:len((*c.CallOptions).UpdateExperiment):len((*c.CallOptions).UpdateExperiment)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cxpb.Experiment{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteExperiment deletes the specified Experiment. +func (c *experimentsRESTClient) DeleteExperiment(ctx context.Context, req *cxpb.DeleteExperimentRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// StartExperiment starts the specified Experiment. This rpc only changes the state of +// experiment from PENDING to RUNNING. +func (c *experimentsRESTClient) StartExperiment(ctx context.Context, req *cxpb.StartExperimentRequest, opts ...gax.CallOption) (*cxpb.Experiment, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v:start", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).StartExperiment[0:len((*c.CallOptions).StartExperiment):len((*c.CallOptions).StartExperiment)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cxpb.Experiment{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// StopExperiment stops the specified Experiment. This rpc only changes the state of +// experiment from RUNNING to DONE. +func (c *experimentsRESTClient) StopExperiment(ctx context.Context, req *cxpb.StopExperimentRequest, opts ...gax.CallOption) (*cxpb.Experiment, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v:stop", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).StopExperiment[0:len((*c.CallOptions).StopExperiment):len((*c.CallOptions).StopExperiment)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cxpb.Experiment{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetLocation gets information about a location. +func (c *experimentsRESTClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *experimentsRESTClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *experimentsRESTClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v3/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *experimentsRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *experimentsRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + // ExperimentIterator manages a stream of *cxpb.Experiment. type ExperimentIterator struct { items []*cxpb.Experiment diff --git a/dialogflow/cx/apiv3/experiments_client_example_test.go b/dialogflow/cx/apiv3/experiments_client_example_test.go index 5b5272b53050..7937f4dad51e 100644 --- a/dialogflow/cx/apiv3/experiments_client_example_test.go +++ b/dialogflow/cx/apiv3/experiments_client_example_test.go @@ -43,6 +43,23 @@ func ExampleNewExperimentsClient() { _ = c } +func ExampleNewExperimentsRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := cx.NewExperimentsRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleExperimentsClient_ListExperiments() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/dialogflow/cx/apiv3/flows_client.go b/dialogflow/cx/apiv3/flows_client.go index a412c294d01e..5c61bf424805 100644 --- a/dialogflow/cx/apiv3/flows_client.go +++ b/dialogflow/cx/apiv3/flows_client.go @@ -17,9 +17,12 @@ package cx import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,15 +30,18 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" structpb "google.golang.org/protobuf/types/known/structpb" ) @@ -193,6 +199,116 @@ func defaultFlowsCallOptions() *FlowsCallOptions { } } +func defaultFlowsRESTCallOptions() *FlowsCallOptions { + return &FlowsCallOptions{ + CreateFlow: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeleteFlow: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListFlows: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetFlow: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UpdateFlow: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + TrainFlow: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ValidateFlow: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetFlowValidationResult: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ImportFlow: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ExportFlow: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + CancelOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalFlowsClient is an interface that defines the methods available from Dialogflow API. type internalFlowsClient interface { Close() error @@ -505,6 +621,89 @@ func (c *flowsGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type flowsRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing FlowsClient + CallOptions **FlowsCallOptions +} + +// NewFlowsRESTClient creates a new flows rest client. +// +// Service for managing Flows. +func NewFlowsRESTClient(ctx context.Context, opts ...option.ClientOption) (*FlowsClient, error) { + clientOpts := append(defaultFlowsRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultFlowsRESTCallOptions() + c := &flowsRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &FlowsClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultFlowsRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://dialogflow.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://dialogflow.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://dialogflow.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *flowsRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *flowsRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *flowsRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *flowsGRPCClient) CreateFlow(ctx context.Context, req *cxpb.CreateFlowRequest, opts ...gax.CallOption) (*cxpb.Flow, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) @@ -887,123 +1086,1205 @@ func (c *flowsGRPCClient) ListOperations(ctx context.Context, req *longrunningpb return it } -// ExportFlowOperation manages a long-running operation from ExportFlow. -type ExportFlowOperation struct { - lro *longrunning.Operation -} - -// ExportFlowOperation returns a new ExportFlowOperation from a given name. -// The name must be that of a previously created ExportFlowOperation, possibly from a different process. -func (c *flowsGRPCClient) ExportFlowOperation(name string) *ExportFlowOperation { - return &ExportFlowOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} - -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// CreateFlow creates a flow in the specified agent. // -// See documentation of Poll for error-handling information. -func (op *ExportFlowOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*cxpb.ExportFlowResponse, error) { - var resp cxpb.ExportFlowResponse - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { +// Note: You should always train a flow prior to sending it queries. See the +// training +// documentation (at https://cloud.google.com/dialogflow/cx/docs/concept/training). +func (c *flowsRESTClient) CreateFlow(ctx context.Context, req *cxpb.CreateFlowRequest, opts ...gax.CallOption) (*cxpb.Flow, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetFlow() + jsonReq, err := m.Marshal(body) + if err != nil { return nil, err } - return &resp, nil -} -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *ExportFlowOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*cxpb.ExportFlowResponse, error) { - var resp cxpb.ExportFlowResponse - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - if !op.Done() { - return nil, nil - } - return &resp, nil -} + baseUrl.Path += fmt.Sprintf("/v3/%v/flows", req.GetParent()) -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *ExportFlowOperation) Metadata() (*structpb.Struct, error) { - var meta structpb.Struct - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { - return nil, err + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetLanguageCode() != "" { + params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) } - return &meta, nil -} -// Done reports whether the long-running operation has completed. -func (op *ExportFlowOperation) Done() bool { - return op.lro.Done() -} + baseUrl.RawQuery = params.Encode() -// 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 *ExportFlowOperation) Name() string { - return op.lro.Name() -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) -// ImportFlowOperation manages a long-running operation from ImportFlow. -type ImportFlowOperation struct { - lro *longrunning.Operation -} + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateFlow[0:len((*c.CallOptions).CreateFlow):len((*c.CallOptions).CreateFlow)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cxpb.Flow{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers -// ImportFlowOperation returns a new ImportFlowOperation from a given name. -// The name must be that of a previously created ImportFlowOperation, possibly from a different process. -func (c *flowsGRPCClient) ImportFlowOperation(name string) *ImportFlowOperation { - return &ImportFlowOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *ImportFlowOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*cxpb.ImportFlowResponse, error) { - var resp cxpb.ImportFlowResponse - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { - return nil, err + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e } - return &resp, nil + return resp, nil } -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *ImportFlowOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*cxpb.ImportFlowResponse, error) { - var resp cxpb.ImportFlowResponse - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { - return nil, err +// DeleteFlow deletes a specified flow. +func (c *flowsRESTClient) DeleteFlow(ctx context.Context, req *cxpb.DeleteFlowRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err } - if !op.Done() { - return nil, nil + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetForce() { + params.Add("force", fmt.Sprintf("%v", req.GetForce())) } - return &resp, nil -} -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// ListFlows returns the list of all flows in the specified agent. +func (c *flowsRESTClient) ListFlows(ctx context.Context, req *cxpb.ListFlowsRequest, opts ...gax.CallOption) *FlowIterator { + it := &FlowIterator{} + req = proto.Clone(req).(*cxpb.ListFlowsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*cxpb.Flow, string, error) { + resp := &cxpb.ListFlowsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/flows", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetLanguageCode() != "" { + params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetFlows(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetFlow retrieves the specified flow. +func (c *flowsRESTClient) GetFlow(ctx context.Context, req *cxpb.GetFlowRequest, opts ...gax.CallOption) (*cxpb.Flow, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetLanguageCode() != "" { + params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetFlow[0:len((*c.CallOptions).GetFlow):len((*c.CallOptions).GetFlow)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cxpb.Flow{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateFlow updates the specified flow. +// +// Note: You should always train a flow prior to sending it queries. See the +// training +// documentation (at https://cloud.google.com/dialogflow/cx/docs/concept/training). +func (c *flowsRESTClient) UpdateFlow(ctx context.Context, req *cxpb.UpdateFlowRequest, opts ...gax.CallOption) (*cxpb.Flow, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetFlow() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetFlow().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetLanguageCode() != "" { + params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) + } + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "flow.name", url.QueryEscape(req.GetFlow().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateFlow[0:len((*c.CallOptions).UpdateFlow):len((*c.CallOptions).UpdateFlow)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cxpb.Flow{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// TrainFlow trains the specified flow. Note that only the flow in ‘draft’ environment +// is trained. +// +// This method is a long-running +// operation (at https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation). +// The returned Operation type has the following method-specific fields: +// +// metadata: An empty Struct +// message (at https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) +// +// response: An Empty +// message (at https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) +// +// Note: You should always train a flow prior to sending it queries. See the +// training +// documentation (at https://cloud.google.com/dialogflow/cx/docs/concept/training). +func (c *flowsRESTClient) TrainFlow(ctx context.Context, req *cxpb.TrainFlowRequest, opts ...gax.CallOption) (*TrainFlowOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v:train", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v3/%s", resp.GetName()) + return &TrainFlowOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ValidateFlow validates the specified flow and creates or updates validation results. +// Please call this API after the training is completed to get the complete +// validation results. +func (c *flowsRESTClient) ValidateFlow(ctx context.Context, req *cxpb.ValidateFlowRequest, opts ...gax.CallOption) (*cxpb.FlowValidationResult, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v:validate", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).ValidateFlow[0:len((*c.CallOptions).ValidateFlow):len((*c.CallOptions).ValidateFlow)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cxpb.FlowValidationResult{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetFlowValidationResult gets the latest flow validation result. Flow validation is performed +// when ValidateFlow is called. +func (c *flowsRESTClient) GetFlowValidationResult(ctx context.Context, req *cxpb.GetFlowValidationResultRequest, opts ...gax.CallOption) (*cxpb.FlowValidationResult, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetLanguageCode() != "" { + params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetFlowValidationResult[0:len((*c.CallOptions).GetFlowValidationResult):len((*c.CallOptions).GetFlowValidationResult)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cxpb.FlowValidationResult{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ImportFlow imports the specified flow to the specified agent from a binary file. +// +// This method is a long-running +// operation (at https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation). +// The returned Operation type has the following method-specific fields: +// +// metadata: An empty Struct +// message (at https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) +// +// response: ImportFlowResponse +// +// Note: You should always train a flow prior to sending it queries. See the +// training +// documentation (at https://cloud.google.com/dialogflow/cx/docs/concept/training). +func (c *flowsRESTClient) ImportFlow(ctx context.Context, req *cxpb.ImportFlowRequest, opts ...gax.CallOption) (*ImportFlowOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/flows:import", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v3/%s", resp.GetName()) + return &ImportFlowOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ExportFlow exports the specified flow to a binary file. +// +// This method is a long-running +// operation (at https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation). +// The returned Operation type has the following method-specific fields: +// +// metadata: An empty Struct +// message (at https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) +// +// response: ExportFlowResponse +// +// Note that resources (e.g. intents, entities, webhooks) that the flow +// references will also be exported. +func (c *flowsRESTClient) ExportFlow(ctx context.Context, req *cxpb.ExportFlowRequest, opts ...gax.CallOption) (*ExportFlowOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v:export", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v3/%s", resp.GetName()) + return &ExportFlowOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetLocation gets information about a location. +func (c *flowsRESTClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *flowsRESTClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *flowsRESTClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v3/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *flowsRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *flowsRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// ExportFlowOperation manages a long-running operation from ExportFlow. +type ExportFlowOperation struct { + lro *longrunning.Operation + pollPath string +} + +// ExportFlowOperation returns a new ExportFlowOperation from a given name. +// The name must be that of a previously created ExportFlowOperation, possibly from a different process. +func (c *flowsGRPCClient) ExportFlowOperation(name string) *ExportFlowOperation { + return &ExportFlowOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// ExportFlowOperation returns a new ExportFlowOperation from a given name. +// The name must be that of a previously created ExportFlowOperation, possibly from a different process. +func (c *flowsRESTClient) ExportFlowOperation(name string) *ExportFlowOperation { + override := fmt.Sprintf("/v3/%s", name) + return &ExportFlowOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *ExportFlowOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*cxpb.ExportFlowResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp cxpb.ExportFlowResponse + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *ExportFlowOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*cxpb.ExportFlowResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp cxpb.ExportFlowResponse + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *ExportFlowOperation) Metadata() (*structpb.Struct, error) { + var meta structpb.Struct + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *ExportFlowOperation) Done() bool { + return op.lro.Done() +} + +// 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 *ExportFlowOperation) Name() string { + return op.lro.Name() +} + +// ImportFlowOperation manages a long-running operation from ImportFlow. +type ImportFlowOperation struct { + lro *longrunning.Operation + pollPath string +} + +// ImportFlowOperation returns a new ImportFlowOperation from a given name. +// The name must be that of a previously created ImportFlowOperation, possibly from a different process. +func (c *flowsGRPCClient) ImportFlowOperation(name string) *ImportFlowOperation { + return &ImportFlowOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// ImportFlowOperation returns a new ImportFlowOperation from a given name. +// The name must be that of a previously created ImportFlowOperation, possibly from a different process. +func (c *flowsRESTClient) ImportFlowOperation(name string) *ImportFlowOperation { + override := fmt.Sprintf("/v3/%s", name) + return &ImportFlowOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *ImportFlowOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*cxpb.ImportFlowResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp cxpb.ImportFlowResponse + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *ImportFlowOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*cxpb.ImportFlowResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp cxpb.ImportFlowResponse + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. func (op *ImportFlowOperation) Metadata() (*structpb.Struct, error) { var meta structpb.Struct if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { @@ -1027,7 +2308,8 @@ func (op *ImportFlowOperation) Name() string { // TrainFlowOperation manages a long-running operation from TrainFlow. type TrainFlowOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // TrainFlowOperation returns a new TrainFlowOperation from a given name. @@ -1038,10 +2320,21 @@ func (c *flowsGRPCClient) TrainFlowOperation(name string) *TrainFlowOperation { } } +// TrainFlowOperation returns a new TrainFlowOperation from a given name. +// The name must be that of a previously created TrainFlowOperation, possibly from a different process. +func (c *flowsRESTClient) TrainFlowOperation(name string) *TrainFlowOperation { + override := fmt.Sprintf("/v3/%s", name) + return &TrainFlowOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *TrainFlowOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -1055,6 +2348,7 @@ func (op *TrainFlowOperation) Wait(ctx context.Context, opts ...gax.CallOption) // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *TrainFlowOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } diff --git a/dialogflow/cx/apiv3/flows_client_example_test.go b/dialogflow/cx/apiv3/flows_client_example_test.go index 421b7870f7ad..ea49e5c256c6 100644 --- a/dialogflow/cx/apiv3/flows_client_example_test.go +++ b/dialogflow/cx/apiv3/flows_client_example_test.go @@ -43,6 +43,23 @@ func ExampleNewFlowsClient() { _ = c } +func ExampleNewFlowsRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := cx.NewFlowsRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleFlowsClient_CreateFlow() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/dialogflow/cx/apiv3/gapic_metadata.json b/dialogflow/cx/apiv3/gapic_metadata.json index 3359afa24182..149df0f1edde 100644 --- a/dialogflow/cx/apiv3/gapic_metadata.json +++ b/dialogflow/cx/apiv3/gapic_metadata.json @@ -81,6 +81,81 @@ ] } } + }, + "rest": { + "libraryClient": "AgentsClient", + "rpcs": { + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "CreateAgent": { + "methods": [ + "CreateAgent" + ] + }, + "DeleteAgent": { + "methods": [ + "DeleteAgent" + ] + }, + "ExportAgent": { + "methods": [ + "ExportAgent" + ] + }, + "GetAgent": { + "methods": [ + "GetAgent" + ] + }, + "GetAgentValidationResult": { + "methods": [ + "GetAgentValidationResult" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ListAgents": { + "methods": [ + "ListAgents" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "RestoreAgent": { + "methods": [ + "RestoreAgent" + ] + }, + "UpdateAgent": { + "methods": [ + "UpdateAgent" + ] + }, + "ValidateAgent": { + "methods": [ + "ValidateAgent" + ] + } + } } } }, @@ -125,6 +200,46 @@ ] } } + }, + "rest": { + "libraryClient": "ChangelogsClient", + "rpcs": { + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "GetChangelog": { + "methods": [ + "GetChangelog" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ListChangelogs": { + "methods": [ + "ListChangelogs" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + } + } } } }, @@ -169,32 +284,747 @@ ] } } + }, + "rest": { + "libraryClient": "DeploymentsClient", + "rpcs": { + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "GetDeployment": { + "methods": [ + "GetDeployment" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ListDeployments": { + "methods": [ + "ListDeployments" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + } + } + } + } + }, + "EntityTypes": { + "clients": { + "grpc": { + "libraryClient": "EntityTypesClient", + "rpcs": { + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "CreateEntityType": { + "methods": [ + "CreateEntityType" + ] + }, + "DeleteEntityType": { + "methods": [ + "DeleteEntityType" + ] + }, + "GetEntityType": { + "methods": [ + "GetEntityType" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ListEntityTypes": { + "methods": [ + "ListEntityTypes" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "UpdateEntityType": { + "methods": [ + "UpdateEntityType" + ] + } + } + }, + "rest": { + "libraryClient": "EntityTypesClient", + "rpcs": { + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "CreateEntityType": { + "methods": [ + "CreateEntityType" + ] + }, + "DeleteEntityType": { + "methods": [ + "DeleteEntityType" + ] + }, + "GetEntityType": { + "methods": [ + "GetEntityType" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ListEntityTypes": { + "methods": [ + "ListEntityTypes" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "UpdateEntityType": { + "methods": [ + "UpdateEntityType" + ] + } + } + } + } + }, + "Environments": { + "clients": { + "grpc": { + "libraryClient": "EnvironmentsClient", + "rpcs": { + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "CreateEnvironment": { + "methods": [ + "CreateEnvironment" + ] + }, + "DeleteEnvironment": { + "methods": [ + "DeleteEnvironment" + ] + }, + "DeployFlow": { + "methods": [ + "DeployFlow" + ] + }, + "GetEnvironment": { + "methods": [ + "GetEnvironment" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ListContinuousTestResults": { + "methods": [ + "ListContinuousTestResults" + ] + }, + "ListEnvironments": { + "methods": [ + "ListEnvironments" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "LookupEnvironmentHistory": { + "methods": [ + "LookupEnvironmentHistory" + ] + }, + "RunContinuousTest": { + "methods": [ + "RunContinuousTest" + ] + }, + "UpdateEnvironment": { + "methods": [ + "UpdateEnvironment" + ] + } + } + }, + "rest": { + "libraryClient": "EnvironmentsClient", + "rpcs": { + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "CreateEnvironment": { + "methods": [ + "CreateEnvironment" + ] + }, + "DeleteEnvironment": { + "methods": [ + "DeleteEnvironment" + ] + }, + "DeployFlow": { + "methods": [ + "DeployFlow" + ] + }, + "GetEnvironment": { + "methods": [ + "GetEnvironment" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ListContinuousTestResults": { + "methods": [ + "ListContinuousTestResults" + ] + }, + "ListEnvironments": { + "methods": [ + "ListEnvironments" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "LookupEnvironmentHistory": { + "methods": [ + "LookupEnvironmentHistory" + ] + }, + "RunContinuousTest": { + "methods": [ + "RunContinuousTest" + ] + }, + "UpdateEnvironment": { + "methods": [ + "UpdateEnvironment" + ] + } + } + } + } + }, + "Experiments": { + "clients": { + "grpc": { + "libraryClient": "ExperimentsClient", + "rpcs": { + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "CreateExperiment": { + "methods": [ + "CreateExperiment" + ] + }, + "DeleteExperiment": { + "methods": [ + "DeleteExperiment" + ] + }, + "GetExperiment": { + "methods": [ + "GetExperiment" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ListExperiments": { + "methods": [ + "ListExperiments" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "StartExperiment": { + "methods": [ + "StartExperiment" + ] + }, + "StopExperiment": { + "methods": [ + "StopExperiment" + ] + }, + "UpdateExperiment": { + "methods": [ + "UpdateExperiment" + ] + } + } + }, + "rest": { + "libraryClient": "ExperimentsClient", + "rpcs": { + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "CreateExperiment": { + "methods": [ + "CreateExperiment" + ] + }, + "DeleteExperiment": { + "methods": [ + "DeleteExperiment" + ] + }, + "GetExperiment": { + "methods": [ + "GetExperiment" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ListExperiments": { + "methods": [ + "ListExperiments" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "StartExperiment": { + "methods": [ + "StartExperiment" + ] + }, + "StopExperiment": { + "methods": [ + "StopExperiment" + ] + }, + "UpdateExperiment": { + "methods": [ + "UpdateExperiment" + ] + } + } + } + } + }, + "Flows": { + "clients": { + "grpc": { + "libraryClient": "FlowsClient", + "rpcs": { + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "CreateFlow": { + "methods": [ + "CreateFlow" + ] + }, + "DeleteFlow": { + "methods": [ + "DeleteFlow" + ] + }, + "ExportFlow": { + "methods": [ + "ExportFlow" + ] + }, + "GetFlow": { + "methods": [ + "GetFlow" + ] + }, + "GetFlowValidationResult": { + "methods": [ + "GetFlowValidationResult" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ImportFlow": { + "methods": [ + "ImportFlow" + ] + }, + "ListFlows": { + "methods": [ + "ListFlows" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "TrainFlow": { + "methods": [ + "TrainFlow" + ] + }, + "UpdateFlow": { + "methods": [ + "UpdateFlow" + ] + }, + "ValidateFlow": { + "methods": [ + "ValidateFlow" + ] + } + } + }, + "rest": { + "libraryClient": "FlowsClient", + "rpcs": { + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "CreateFlow": { + "methods": [ + "CreateFlow" + ] + }, + "DeleteFlow": { + "methods": [ + "DeleteFlow" + ] + }, + "ExportFlow": { + "methods": [ + "ExportFlow" + ] + }, + "GetFlow": { + "methods": [ + "GetFlow" + ] + }, + "GetFlowValidationResult": { + "methods": [ + "GetFlowValidationResult" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ImportFlow": { + "methods": [ + "ImportFlow" + ] + }, + "ListFlows": { + "methods": [ + "ListFlows" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "TrainFlow": { + "methods": [ + "TrainFlow" + ] + }, + "UpdateFlow": { + "methods": [ + "UpdateFlow" + ] + }, + "ValidateFlow": { + "methods": [ + "ValidateFlow" + ] + } + } + } + } + }, + "Intents": { + "clients": { + "grpc": { + "libraryClient": "IntentsClient", + "rpcs": { + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "CreateIntent": { + "methods": [ + "CreateIntent" + ] + }, + "DeleteIntent": { + "methods": [ + "DeleteIntent" + ] + }, + "GetIntent": { + "methods": [ + "GetIntent" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ListIntents": { + "methods": [ + "ListIntents" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "UpdateIntent": { + "methods": [ + "UpdateIntent" + ] + } + } + }, + "rest": { + "libraryClient": "IntentsClient", + "rpcs": { + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "CreateIntent": { + "methods": [ + "CreateIntent" + ] + }, + "DeleteIntent": { + "methods": [ + "DeleteIntent" + ] + }, + "GetIntent": { + "methods": [ + "GetIntent" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ListIntents": { + "methods": [ + "ListIntents" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "UpdateIntent": { + "methods": [ + "UpdateIntent" + ] + } + } } } }, - "EntityTypes": { + "Pages": { "clients": { "grpc": { - "libraryClient": "EntityTypesClient", + "libraryClient": "PagesClient", "rpcs": { "CancelOperation": { "methods": [ "CancelOperation" ] }, - "CreateEntityType": { - "methods": [ - "CreateEntityType" - ] - }, - "DeleteEntityType": { + "CreatePage": { "methods": [ - "DeleteEntityType" + "CreatePage" ] }, - "GetEntityType": { + "DeletePage": { "methods": [ - "GetEntityType" + "DeletePage" ] }, "GetLocation": { @@ -207,9 +1037,9 @@ "GetOperation" ] }, - "ListEntityTypes": { + "GetPage": { "methods": [ - "ListEntityTypes" + "GetPage" ] }, "ListLocations": { @@ -222,43 +1052,34 @@ "ListOperations" ] }, - "UpdateEntityType": { + "ListPages": { "methods": [ - "UpdateEntityType" + "ListPages" + ] + }, + "UpdatePage": { + "methods": [ + "UpdatePage" ] } } - } - } - }, - "Environments": { - "clients": { - "grpc": { - "libraryClient": "EnvironmentsClient", + }, + "rest": { + "libraryClient": "PagesClient", "rpcs": { "CancelOperation": { "methods": [ "CancelOperation" ] }, - "CreateEnvironment": { - "methods": [ - "CreateEnvironment" - ] - }, - "DeleteEnvironment": { - "methods": [ - "DeleteEnvironment" - ] - }, - "DeployFlow": { + "CreatePage": { "methods": [ - "DeployFlow" + "CreatePage" ] }, - "GetEnvironment": { + "DeletePage": { "methods": [ - "GetEnvironment" + "DeletePage" ] }, "GetLocation": { @@ -271,14 +1092,9 @@ "GetOperation" ] }, - "ListContinuousTestResults": { - "methods": [ - "ListContinuousTestResults" - ] - }, - "ListEnvironments": { + "GetPage": { "methods": [ - "ListEnvironments" + "GetPage" ] }, "ListLocations": { @@ -291,48 +1107,38 @@ "ListOperations" ] }, - "LookupEnvironmentHistory": { - "methods": [ - "LookupEnvironmentHistory" - ] - }, - "RunContinuousTest": { + "ListPages": { "methods": [ - "RunContinuousTest" + "ListPages" ] }, - "UpdateEnvironment": { + "UpdatePage": { "methods": [ - "UpdateEnvironment" + "UpdatePage" ] } } } } }, - "Experiments": { + "SecuritySettingsService": { "clients": { "grpc": { - "libraryClient": "ExperimentsClient", + "libraryClient": "SecuritySettingsClient", "rpcs": { "CancelOperation": { "methods": [ "CancelOperation" ] }, - "CreateExperiment": { - "methods": [ - "CreateExperiment" - ] - }, - "DeleteExperiment": { + "CreateSecuritySettings": { "methods": [ - "DeleteExperiment" + "CreateSecuritySettings" ] }, - "GetExperiment": { + "DeleteSecuritySettings": { "methods": [ - "GetExperiment" + "DeleteSecuritySettings" ] }, "GetLocation": { @@ -345,9 +1151,9 @@ "GetOperation" ] }, - "ListExperiments": { + "GetSecuritySettings": { "methods": [ - "ListExperiments" + "GetSecuritySettings" ] }, "ListLocations": { @@ -360,58 +1166,34 @@ "ListOperations" ] }, - "StartExperiment": { - "methods": [ - "StartExperiment" - ] - }, - "StopExperiment": { + "ListSecuritySettings": { "methods": [ - "StopExperiment" + "ListSecuritySettings" ] }, - "UpdateExperiment": { + "UpdateSecuritySettings": { "methods": [ - "UpdateExperiment" + "UpdateSecuritySettings" ] } } - } - } - }, - "Flows": { - "clients": { - "grpc": { - "libraryClient": "FlowsClient", + }, + "rest": { + "libraryClient": "SecuritySettingsClient", "rpcs": { "CancelOperation": { "methods": [ "CancelOperation" ] }, - "CreateFlow": { - "methods": [ - "CreateFlow" - ] - }, - "DeleteFlow": { - "methods": [ - "DeleteFlow" - ] - }, - "ExportFlow": { - "methods": [ - "ExportFlow" - ] - }, - "GetFlow": { + "CreateSecuritySettings": { "methods": [ - "GetFlow" + "CreateSecuritySettings" ] }, - "GetFlowValidationResult": { + "DeleteSecuritySettings": { "methods": [ - "GetFlowValidationResult" + "DeleteSecuritySettings" ] }, "GetLocation": { @@ -424,14 +1206,9 @@ "GetOperation" ] }, - "ImportFlow": { - "methods": [ - "ImportFlow" - ] - }, - "ListFlows": { + "GetSecuritySettings": { "methods": [ - "ListFlows" + "GetSecuritySettings" ] }, "ListLocations": { @@ -444,48 +1221,38 @@ "ListOperations" ] }, - "TrainFlow": { - "methods": [ - "TrainFlow" - ] - }, - "UpdateFlow": { + "ListSecuritySettings": { "methods": [ - "UpdateFlow" + "ListSecuritySettings" ] }, - "ValidateFlow": { + "UpdateSecuritySettings": { "methods": [ - "ValidateFlow" + "UpdateSecuritySettings" ] } } } } }, - "Intents": { + "SessionEntityTypes": { "clients": { "grpc": { - "libraryClient": "IntentsClient", + "libraryClient": "SessionEntityTypesClient", "rpcs": { "CancelOperation": { "methods": [ "CancelOperation" ] }, - "CreateIntent": { - "methods": [ - "CreateIntent" - ] - }, - "DeleteIntent": { + "CreateSessionEntityType": { "methods": [ - "DeleteIntent" + "CreateSessionEntityType" ] }, - "GetIntent": { + "DeleteSessionEntityType": { "methods": [ - "GetIntent" + "DeleteSessionEntityType" ] }, "GetLocation": { @@ -498,9 +1265,9 @@ "GetOperation" ] }, - "ListIntents": { + "GetSessionEntityType": { "methods": [ - "ListIntents" + "GetSessionEntityType" ] }, "ListLocations": { @@ -513,33 +1280,34 @@ "ListOperations" ] }, - "UpdateIntent": { + "ListSessionEntityTypes": { "methods": [ - "UpdateIntent" + "ListSessionEntityTypes" + ] + }, + "UpdateSessionEntityType": { + "methods": [ + "UpdateSessionEntityType" ] } } - } - } - }, - "Pages": { - "clients": { - "grpc": { - "libraryClient": "PagesClient", + }, + "rest": { + "libraryClient": "SessionEntityTypesClient", "rpcs": { "CancelOperation": { "methods": [ "CancelOperation" ] }, - "CreatePage": { + "CreateSessionEntityType": { "methods": [ - "CreatePage" + "CreateSessionEntityType" ] }, - "DeletePage": { + "DeleteSessionEntityType": { "methods": [ - "DeletePage" + "DeleteSessionEntityType" ] }, "GetLocation": { @@ -552,9 +1320,9 @@ "GetOperation" ] }, - "GetPage": { + "GetSessionEntityType": { "methods": [ - "GetPage" + "GetSessionEntityType" ] }, "ListLocations": { @@ -567,38 +1335,38 @@ "ListOperations" ] }, - "ListPages": { + "ListSessionEntityTypes": { "methods": [ - "ListPages" + "ListSessionEntityTypes" ] }, - "UpdatePage": { + "UpdateSessionEntityType": { "methods": [ - "UpdatePage" + "UpdateSessionEntityType" ] } } } } }, - "SecuritySettingsService": { + "Sessions": { "clients": { "grpc": { - "libraryClient": "SecuritySettingsClient", + "libraryClient": "SessionsClient", "rpcs": { "CancelOperation": { "methods": [ "CancelOperation" ] }, - "CreateSecuritySettings": { + "DetectIntent": { "methods": [ - "CreateSecuritySettings" + "DetectIntent" ] }, - "DeleteSecuritySettings": { + "FulfillIntent": { "methods": [ - "DeleteSecuritySettings" + "FulfillIntent" ] }, "GetLocation": { @@ -611,11 +1379,6 @@ "GetOperation" ] }, - "GetSecuritySettings": { - "methods": [ - "GetSecuritySettings" - ] - }, "ListLocations": { "methods": [ "ListLocations" @@ -626,38 +1389,34 @@ "ListOperations" ] }, - "ListSecuritySettings": { + "MatchIntent": { "methods": [ - "ListSecuritySettings" + "MatchIntent" ] }, - "UpdateSecuritySettings": { + "StreamingDetectIntent": { "methods": [ - "UpdateSecuritySettings" + "StreamingDetectIntent" ] } } - } - } - }, - "SessionEntityTypes": { - "clients": { - "grpc": { - "libraryClient": "SessionEntityTypesClient", + }, + "rest": { + "libraryClient": "SessionsClient", "rpcs": { "CancelOperation": { "methods": [ "CancelOperation" ] }, - "CreateSessionEntityType": { + "DetectIntent": { "methods": [ - "CreateSessionEntityType" + "DetectIntent" ] }, - "DeleteSessionEntityType": { + "FulfillIntent": { "methods": [ - "DeleteSessionEntityType" + "FulfillIntent" ] }, "GetLocation": { @@ -670,11 +1429,6 @@ "GetOperation" ] }, - "GetSessionEntityType": { - "methods": [ - "GetSessionEntityType" - ] - }, "ListLocations": { "methods": [ "ListLocations" @@ -685,38 +1439,53 @@ "ListOperations" ] }, - "ListSessionEntityTypes": { + "MatchIntent": { "methods": [ - "ListSessionEntityTypes" + "MatchIntent" ] }, - "UpdateSessionEntityType": { + "StreamingDetectIntent": { "methods": [ - "UpdateSessionEntityType" + "StreamingDetectIntent" ] } } } } }, - "Sessions": { + "TestCases": { "clients": { "grpc": { - "libraryClient": "SessionsClient", + "libraryClient": "TestCasesClient", "rpcs": { + "BatchDeleteTestCases": { + "methods": [ + "BatchDeleteTestCases" + ] + }, + "BatchRunTestCases": { + "methods": [ + "BatchRunTestCases" + ] + }, + "CalculateCoverage": { + "methods": [ + "CalculateCoverage" + ] + }, "CancelOperation": { "methods": [ "CancelOperation" ] }, - "DetectIntent": { + "CreateTestCase": { "methods": [ - "DetectIntent" + "CreateTestCase" ] }, - "FulfillIntent": { + "ExportTestCases": { "methods": [ - "FulfillIntent" + "ExportTestCases" ] }, "GetLocation": { @@ -729,6 +1498,21 @@ "GetOperation" ] }, + "GetTestCase": { + "methods": [ + "GetTestCase" + ] + }, + "GetTestCaseResult": { + "methods": [ + "GetTestCaseResult" + ] + }, + "ImportTestCases": { + "methods": [ + "ImportTestCases" + ] + }, "ListLocations": { "methods": [ "ListLocations" @@ -739,23 +1523,29 @@ "ListOperations" ] }, - "MatchIntent": { + "ListTestCaseResults": { "methods": [ - "MatchIntent" + "ListTestCaseResults" ] }, - "StreamingDetectIntent": { + "ListTestCases": { "methods": [ - "StreamingDetectIntent" + "ListTestCases" + ] + }, + "RunTestCase": { + "methods": [ + "RunTestCase" + ] + }, + "UpdateTestCase": { + "methods": [ + "UpdateTestCase" ] } } - } - } - }, - "TestCases": { - "clients": { - "grpc": { + }, + "rest": { "libraryClient": "TestCasesClient", "rpcs": { "BatchDeleteTestCases": { @@ -903,6 +1693,61 @@ ] } } + }, + "rest": { + "libraryClient": "TransitionRouteGroupsClient", + "rpcs": { + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "CreateTransitionRouteGroup": { + "methods": [ + "CreateTransitionRouteGroup" + ] + }, + "DeleteTransitionRouteGroup": { + "methods": [ + "DeleteTransitionRouteGroup" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "GetTransitionRouteGroup": { + "methods": [ + "GetTransitionRouteGroup" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "ListTransitionRouteGroups": { + "methods": [ + "ListTransitionRouteGroups" + ] + }, + "UpdateTransitionRouteGroup": { + "methods": [ + "UpdateTransitionRouteGroup" + ] + } + } } } }, @@ -972,6 +1817,71 @@ ] } } + }, + "rest": { + "libraryClient": "VersionsClient", + "rpcs": { + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "CompareVersions": { + "methods": [ + "CompareVersions" + ] + }, + "CreateVersion": { + "methods": [ + "CreateVersion" + ] + }, + "DeleteVersion": { + "methods": [ + "DeleteVersion" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "GetVersion": { + "methods": [ + "GetVersion" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "ListVersions": { + "methods": [ + "ListVersions" + ] + }, + "LoadVersion": { + "methods": [ + "LoadVersion" + ] + }, + "UpdateVersion": { + "methods": [ + "UpdateVersion" + ] + } + } } } }, @@ -1031,6 +1941,61 @@ ] } } + }, + "rest": { + "libraryClient": "WebhooksClient", + "rpcs": { + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "CreateWebhook": { + "methods": [ + "CreateWebhook" + ] + }, + "DeleteWebhook": { + "methods": [ + "DeleteWebhook" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "GetWebhook": { + "methods": [ + "GetWebhook" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "ListWebhooks": { + "methods": [ + "ListWebhooks" + ] + }, + "UpdateWebhook": { + "methods": [ + "UpdateWebhook" + ] + } + } } } } diff --git a/dialogflow/cx/apiv3/intents_client.go b/dialogflow/cx/apiv3/intents_client.go index acf8d6ec5151..e25e1d9c89fb 100644 --- a/dialogflow/cx/apiv3/intents_client.go +++ b/dialogflow/cx/apiv3/intents_client.go @@ -17,23 +17,29 @@ package cx import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" cxpb "cloud.google.com/go/dialogflow/cx/apiv3/cxpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -130,6 +136,66 @@ func defaultIntentsCallOptions() *IntentsCallOptions { } } +func defaultIntentsRESTCallOptions() *IntentsCallOptions { + return &IntentsCallOptions{ + ListIntents: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetIntent: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateIntent: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UpdateIntent: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeleteIntent: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + CancelOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalIntentsClient is an interface that defines the methods available from Dialogflow API. type internalIntentsClient interface { Close() error @@ -331,6 +397,74 @@ func (c *intentsGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type intentsRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing IntentsClient + CallOptions **IntentsCallOptions +} + +// NewIntentsRESTClient creates a new intents rest client. +// +// Service for managing Intents. +func NewIntentsRESTClient(ctx context.Context, opts ...option.ClientOption) (*IntentsClient, error) { + clientOpts := append(defaultIntentsRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultIntentsRESTCallOptions() + c := &intentsRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &IntentsClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultIntentsRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://dialogflow.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://dialogflow.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://dialogflow.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *intentsRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *intentsRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *intentsRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *intentsGRPCClient) ListIntents(ctx context.Context, req *cxpb.ListIntentsRequest, opts ...gax.CallOption) *IntentIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -597,6 +731,694 @@ func (c *intentsGRPCClient) ListOperations(ctx context.Context, req *longrunning return it } +// ListIntents returns the list of all intents in the specified agent. +func (c *intentsRESTClient) ListIntents(ctx context.Context, req *cxpb.ListIntentsRequest, opts ...gax.CallOption) *IntentIterator { + it := &IntentIterator{} + req = proto.Clone(req).(*cxpb.ListIntentsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*cxpb.Intent, string, error) { + resp := &cxpb.ListIntentsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/intents", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetIntentView() != 0 { + params.Add("intentView", fmt.Sprintf("%v", req.GetIntentView())) + } + if req.GetLanguageCode() != "" { + params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetIntents(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetIntent retrieves the specified intent. +func (c *intentsRESTClient) GetIntent(ctx context.Context, req *cxpb.GetIntentRequest, opts ...gax.CallOption) (*cxpb.Intent, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetLanguageCode() != "" { + params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetIntent[0:len((*c.CallOptions).GetIntent):len((*c.CallOptions).GetIntent)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cxpb.Intent{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateIntent creates an intent in the specified agent. +// +// Note: You should always train a flow prior to sending it queries. See the +// training +// documentation (at https://cloud.google.com/dialogflow/cx/docs/concept/training). +func (c *intentsRESTClient) CreateIntent(ctx context.Context, req *cxpb.CreateIntentRequest, opts ...gax.CallOption) (*cxpb.Intent, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetIntent() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/intents", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetLanguageCode() != "" { + params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateIntent[0:len((*c.CallOptions).CreateIntent):len((*c.CallOptions).CreateIntent)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cxpb.Intent{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateIntent updates the specified intent. +// +// Note: You should always train a flow prior to sending it queries. See the +// training +// documentation (at https://cloud.google.com/dialogflow/cx/docs/concept/training). +func (c *intentsRESTClient) UpdateIntent(ctx context.Context, req *cxpb.UpdateIntentRequest, opts ...gax.CallOption) (*cxpb.Intent, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetIntent() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetIntent().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetLanguageCode() != "" { + params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) + } + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "intent.name", url.QueryEscape(req.GetIntent().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateIntent[0:len((*c.CallOptions).UpdateIntent):len((*c.CallOptions).UpdateIntent)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cxpb.Intent{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteIntent deletes the specified intent. +// +// Note: You should always train a flow prior to sending it queries. See the +// training +// documentation (at https://cloud.google.com/dialogflow/cx/docs/concept/training). +func (c *intentsRESTClient) DeleteIntent(ctx context.Context, req *cxpb.DeleteIntentRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetLocation gets information about a location. +func (c *intentsRESTClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *intentsRESTClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *intentsRESTClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v3/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *intentsRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *intentsRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + // IntentIterator manages a stream of *cxpb.Intent. type IntentIterator struct { items []*cxpb.Intent diff --git a/dialogflow/cx/apiv3/intents_client_example_test.go b/dialogflow/cx/apiv3/intents_client_example_test.go index eb9f66a741e3..ada1547a4200 100644 --- a/dialogflow/cx/apiv3/intents_client_example_test.go +++ b/dialogflow/cx/apiv3/intents_client_example_test.go @@ -43,6 +43,23 @@ func ExampleNewIntentsClient() { _ = c } +func ExampleNewIntentsRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := cx.NewIntentsRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleIntentsClient_ListIntents() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/dialogflow/cx/apiv3/pages_client.go b/dialogflow/cx/apiv3/pages_client.go index e6719892ab8b..890edf96459e 100644 --- a/dialogflow/cx/apiv3/pages_client.go +++ b/dialogflow/cx/apiv3/pages_client.go @@ -17,23 +17,29 @@ package cx import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" cxpb "cloud.google.com/go/dialogflow/cx/apiv3/cxpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -130,6 +136,66 @@ func defaultPagesCallOptions() *PagesCallOptions { } } +func defaultPagesRESTCallOptions() *PagesCallOptions { + return &PagesCallOptions{ + ListPages: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetPage: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreatePage: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UpdatePage: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeletePage: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + CancelOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalPagesClient is an interface that defines the methods available from Dialogflow API. type internalPagesClient interface { Close() error @@ -331,6 +397,74 @@ func (c *pagesGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type pagesRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing PagesClient + CallOptions **PagesCallOptions +} + +// NewPagesRESTClient creates a new pages rest client. +// +// Service for managing [Pages][google.cloud.dialogflow.cx.v3.Page (at http://google.cloud.dialogflow.cx.v3.Page)]. +func NewPagesRESTClient(ctx context.Context, opts ...option.ClientOption) (*PagesClient, error) { + clientOpts := append(defaultPagesRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultPagesRESTCallOptions() + c := &pagesRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &PagesClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultPagesRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://dialogflow.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://dialogflow.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://dialogflow.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *pagesRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *pagesRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *pagesRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *pagesGRPCClient) ListPages(ctx context.Context, req *cxpb.ListPagesRequest, opts ...gax.CallOption) *PageIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -597,6 +731,694 @@ func (c *pagesGRPCClient) ListOperations(ctx context.Context, req *longrunningpb return it } +// ListPages returns the list of all pages in the specified flow. +func (c *pagesRESTClient) ListPages(ctx context.Context, req *cxpb.ListPagesRequest, opts ...gax.CallOption) *PageIterator { + it := &PageIterator{} + req = proto.Clone(req).(*cxpb.ListPagesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*cxpb.Page, string, error) { + resp := &cxpb.ListPagesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/pages", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetLanguageCode() != "" { + params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetPages(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetPage retrieves the specified page. +func (c *pagesRESTClient) GetPage(ctx context.Context, req *cxpb.GetPageRequest, opts ...gax.CallOption) (*cxpb.Page, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetLanguageCode() != "" { + params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetPage[0:len((*c.CallOptions).GetPage):len((*c.CallOptions).GetPage)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cxpb.Page{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreatePage creates a page in the specified flow. +// +// Note: You should always train a flow prior to sending it queries. See the +// training +// documentation (at https://cloud.google.com/dialogflow/cx/docs/concept/training). +func (c *pagesRESTClient) CreatePage(ctx context.Context, req *cxpb.CreatePageRequest, opts ...gax.CallOption) (*cxpb.Page, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetPage() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/pages", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetLanguageCode() != "" { + params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreatePage[0:len((*c.CallOptions).CreatePage):len((*c.CallOptions).CreatePage)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cxpb.Page{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdatePage updates the specified page. +// +// Note: You should always train a flow prior to sending it queries. See the +// training +// documentation (at https://cloud.google.com/dialogflow/cx/docs/concept/training). +func (c *pagesRESTClient) UpdatePage(ctx context.Context, req *cxpb.UpdatePageRequest, opts ...gax.CallOption) (*cxpb.Page, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetPage() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetPage().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetLanguageCode() != "" { + params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) + } + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "page.name", url.QueryEscape(req.GetPage().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdatePage[0:len((*c.CallOptions).UpdatePage):len((*c.CallOptions).UpdatePage)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cxpb.Page{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeletePage deletes the specified page. +// +// Note: You should always train a flow prior to sending it queries. See the +// training +// documentation (at https://cloud.google.com/dialogflow/cx/docs/concept/training). +func (c *pagesRESTClient) DeletePage(ctx context.Context, req *cxpb.DeletePageRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetForce() { + params.Add("force", fmt.Sprintf("%v", req.GetForce())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetLocation gets information about a location. +func (c *pagesRESTClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *pagesRESTClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *pagesRESTClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v3/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *pagesRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *pagesRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + // LocationIterator manages a stream of *locationpb.Location. type LocationIterator struct { items []*locationpb.Location diff --git a/dialogflow/cx/apiv3/pages_client_example_test.go b/dialogflow/cx/apiv3/pages_client_example_test.go index 29d38eb456d6..39dad1220bdc 100644 --- a/dialogflow/cx/apiv3/pages_client_example_test.go +++ b/dialogflow/cx/apiv3/pages_client_example_test.go @@ -43,6 +43,23 @@ func ExampleNewPagesClient() { _ = c } +func ExampleNewPagesRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := cx.NewPagesRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExamplePagesClient_ListPages() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/dialogflow/cx/apiv3/security_settings_client.go b/dialogflow/cx/apiv3/security_settings_client.go index 81f935e960d7..516c3b4e638a 100644 --- a/dialogflow/cx/apiv3/security_settings_client.go +++ b/dialogflow/cx/apiv3/security_settings_client.go @@ -17,23 +17,29 @@ package cx import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" cxpb "cloud.google.com/go/dialogflow/cx/apiv3/cxpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -130,6 +136,66 @@ func defaultSecuritySettingsCallOptions() *SecuritySettingsCallOptions { } } +func defaultSecuritySettingsRESTCallOptions() *SecuritySettingsCallOptions { + return &SecuritySettingsCallOptions{ + CreateSecuritySettings: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetSecuritySettings: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UpdateSecuritySettings: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListSecuritySettings: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeleteSecuritySettings: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + CancelOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalSecuritySettingsClient is an interface that defines the methods available from Dialogflow API. type internalSecuritySettingsClient interface { Close() error @@ -320,6 +386,74 @@ func (c *securitySettingsGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type securitySettingsRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing SecuritySettingsClient + CallOptions **SecuritySettingsCallOptions +} + +// NewSecuritySettingsRESTClient creates a new security settings service rest client. +// +// Service for managing security settings for Dialogflow. +func NewSecuritySettingsRESTClient(ctx context.Context, opts ...option.ClientOption) (*SecuritySettingsClient, error) { + clientOpts := append(defaultSecuritySettingsRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultSecuritySettingsRESTCallOptions() + c := &securitySettingsRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &SecuritySettingsClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultSecuritySettingsRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://dialogflow.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://dialogflow.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://dialogflow.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *securitySettingsRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *securitySettingsRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *securitySettingsRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *securitySettingsGRPCClient) CreateSecuritySettings(ctx context.Context, req *cxpb.CreateSecuritySettingsRequest, opts ...gax.CallOption) (*cxpb.SecuritySettings, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) @@ -586,6 +720,668 @@ func (c *securitySettingsGRPCClient) ListOperations(ctx context.Context, req *lo return it } +// CreateSecuritySettings create security settings in the specified location. +func (c *securitySettingsRESTClient) CreateSecuritySettings(ctx context.Context, req *cxpb.CreateSecuritySettingsRequest, opts ...gax.CallOption) (*cxpb.SecuritySettings, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetSecuritySettings() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/securitySettings", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateSecuritySettings[0:len((*c.CallOptions).CreateSecuritySettings):len((*c.CallOptions).CreateSecuritySettings)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cxpb.SecuritySettings{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetSecuritySettings retrieves the specified SecuritySettings. +// The returned settings may be stale by up to 1 minute. +func (c *securitySettingsRESTClient) GetSecuritySettings(ctx context.Context, req *cxpb.GetSecuritySettingsRequest, opts ...gax.CallOption) (*cxpb.SecuritySettings, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetSecuritySettings[0:len((*c.CallOptions).GetSecuritySettings):len((*c.CallOptions).GetSecuritySettings)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cxpb.SecuritySettings{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateSecuritySettings updates the specified SecuritySettings. +func (c *securitySettingsRESTClient) UpdateSecuritySettings(ctx context.Context, req *cxpb.UpdateSecuritySettingsRequest, opts ...gax.CallOption) (*cxpb.SecuritySettings, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetSecuritySettings() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetSecuritySettings().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "security_settings.name", url.QueryEscape(req.GetSecuritySettings().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateSecuritySettings[0:len((*c.CallOptions).UpdateSecuritySettings):len((*c.CallOptions).UpdateSecuritySettings)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cxpb.SecuritySettings{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListSecuritySettings returns the list of all security settings in the specified location. +func (c *securitySettingsRESTClient) ListSecuritySettings(ctx context.Context, req *cxpb.ListSecuritySettingsRequest, opts ...gax.CallOption) *SecuritySettingsIterator { + it := &SecuritySettingsIterator{} + req = proto.Clone(req).(*cxpb.ListSecuritySettingsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*cxpb.SecuritySettings, string, error) { + resp := &cxpb.ListSecuritySettingsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/securitySettings", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetSecuritySettings(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// DeleteSecuritySettings deletes the specified SecuritySettings. +func (c *securitySettingsRESTClient) DeleteSecuritySettings(ctx context.Context, req *cxpb.DeleteSecuritySettingsRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetLocation gets information about a location. +func (c *securitySettingsRESTClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *securitySettingsRESTClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *securitySettingsRESTClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v3/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *securitySettingsRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *securitySettingsRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + // SecuritySettingsIterator manages a stream of *cxpb.SecuritySettings. type SecuritySettingsIterator struct { items []*cxpb.SecuritySettings diff --git a/dialogflow/cx/apiv3/security_settings_client_example_test.go b/dialogflow/cx/apiv3/security_settings_client_example_test.go index edff6e0b2837..1b2b46e571cd 100644 --- a/dialogflow/cx/apiv3/security_settings_client_example_test.go +++ b/dialogflow/cx/apiv3/security_settings_client_example_test.go @@ -43,6 +43,23 @@ func ExampleNewSecuritySettingsClient() { _ = c } +func ExampleNewSecuritySettingsRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := cx.NewSecuritySettingsRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleSecuritySettingsClient_CreateSecuritySettings() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/dialogflow/cx/apiv3/session_entity_types_client.go b/dialogflow/cx/apiv3/session_entity_types_client.go index 8777a6e35aab..3c6b9c30fff3 100644 --- a/dialogflow/cx/apiv3/session_entity_types_client.go +++ b/dialogflow/cx/apiv3/session_entity_types_client.go @@ -17,23 +17,29 @@ package cx import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" cxpb "cloud.google.com/go/dialogflow/cx/apiv3/cxpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -130,6 +136,66 @@ func defaultSessionEntityTypesCallOptions() *SessionEntityTypesCallOptions { } } +func defaultSessionEntityTypesRESTCallOptions() *SessionEntityTypesCallOptions { + return &SessionEntityTypesCallOptions{ + ListSessionEntityTypes: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetSessionEntityType: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateSessionEntityType: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UpdateSessionEntityType: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeleteSessionEntityType: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + CancelOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalSessionEntityTypesClient is an interface that defines the methods available from Dialogflow API. type internalSessionEntityTypesClient interface { Close() error @@ -319,6 +385,74 @@ func (c *sessionEntityTypesGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type sessionEntityTypesRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing SessionEntityTypesClient + CallOptions **SessionEntityTypesCallOptions +} + +// NewSessionEntityTypesRESTClient creates a new session entity types rest client. +// +// Service for managing SessionEntityTypes. +func NewSessionEntityTypesRESTClient(ctx context.Context, opts ...option.ClientOption) (*SessionEntityTypesClient, error) { + clientOpts := append(defaultSessionEntityTypesRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultSessionEntityTypesRESTCallOptions() + c := &sessionEntityTypesRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &SessionEntityTypesClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultSessionEntityTypesRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://dialogflow.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://dialogflow.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://dialogflow.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *sessionEntityTypesRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *sessionEntityTypesRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *sessionEntityTypesRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *sessionEntityTypesGRPCClient) ListSessionEntityTypes(ctx context.Context, req *cxpb.ListSessionEntityTypesRequest, opts ...gax.CallOption) *SessionEntityTypeIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -585,6 +719,667 @@ func (c *sessionEntityTypesGRPCClient) ListOperations(ctx context.Context, req * return it } +// ListSessionEntityTypes returns the list of all session entity types in the specified session. +func (c *sessionEntityTypesRESTClient) ListSessionEntityTypes(ctx context.Context, req *cxpb.ListSessionEntityTypesRequest, opts ...gax.CallOption) *SessionEntityTypeIterator { + it := &SessionEntityTypeIterator{} + req = proto.Clone(req).(*cxpb.ListSessionEntityTypesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*cxpb.SessionEntityType, string, error) { + resp := &cxpb.ListSessionEntityTypesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/entityTypes", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetSessionEntityTypes(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetSessionEntityType retrieves the specified session entity type. +func (c *sessionEntityTypesRESTClient) GetSessionEntityType(ctx context.Context, req *cxpb.GetSessionEntityTypeRequest, opts ...gax.CallOption) (*cxpb.SessionEntityType, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetSessionEntityType[0:len((*c.CallOptions).GetSessionEntityType):len((*c.CallOptions).GetSessionEntityType)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cxpb.SessionEntityType{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateSessionEntityType creates a session entity type. +func (c *sessionEntityTypesRESTClient) CreateSessionEntityType(ctx context.Context, req *cxpb.CreateSessionEntityTypeRequest, opts ...gax.CallOption) (*cxpb.SessionEntityType, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetSessionEntityType() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/entityTypes", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateSessionEntityType[0:len((*c.CallOptions).CreateSessionEntityType):len((*c.CallOptions).CreateSessionEntityType)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cxpb.SessionEntityType{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateSessionEntityType updates the specified session entity type. +func (c *sessionEntityTypesRESTClient) UpdateSessionEntityType(ctx context.Context, req *cxpb.UpdateSessionEntityTypeRequest, opts ...gax.CallOption) (*cxpb.SessionEntityType, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetSessionEntityType() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetSessionEntityType().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "session_entity_type.name", url.QueryEscape(req.GetSessionEntityType().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateSessionEntityType[0:len((*c.CallOptions).UpdateSessionEntityType):len((*c.CallOptions).UpdateSessionEntityType)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cxpb.SessionEntityType{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteSessionEntityType deletes the specified session entity type. +func (c *sessionEntityTypesRESTClient) DeleteSessionEntityType(ctx context.Context, req *cxpb.DeleteSessionEntityTypeRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetLocation gets information about a location. +func (c *sessionEntityTypesRESTClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *sessionEntityTypesRESTClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *sessionEntityTypesRESTClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v3/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *sessionEntityTypesRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *sessionEntityTypesRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + // SessionEntityTypeIterator manages a stream of *cxpb.SessionEntityType. type SessionEntityTypeIterator struct { items []*cxpb.SessionEntityType diff --git a/dialogflow/cx/apiv3/session_entity_types_client_example_test.go b/dialogflow/cx/apiv3/session_entity_types_client_example_test.go index 1590028aac86..183c508b6662 100644 --- a/dialogflow/cx/apiv3/session_entity_types_client_example_test.go +++ b/dialogflow/cx/apiv3/session_entity_types_client_example_test.go @@ -43,6 +43,23 @@ func ExampleNewSessionEntityTypesClient() { _ = c } +func ExampleNewSessionEntityTypesRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := cx.NewSessionEntityTypesRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleSessionEntityTypesClient_ListSessionEntityTypes() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/dialogflow/cx/apiv3/sessions_client.go b/dialogflow/cx/apiv3/sessions_client.go index 33321e7650d3..63dc02a084bf 100644 --- a/dialogflow/cx/apiv3/sessions_client.go +++ b/dialogflow/cx/apiv3/sessions_client.go @@ -17,23 +17,29 @@ package cx import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" cxpb "cloud.google.com/go/dialogflow/cx/apiv3/cxpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -108,6 +114,47 @@ func defaultSessionsCallOptions() *SessionsCallOptions { } } +func defaultSessionsRESTCallOptions() *SessionsCallOptions { + return &SessionsCallOptions{ + DetectIntent: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + StreamingDetectIntent: []gax.CallOption{}, + MatchIntent: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + FulfillIntent: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + CancelOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalSessionsClient is an interface that defines the methods available from Dialogflow API. type internalSessionsClient interface { Close() error @@ -180,6 +227,8 @@ func (c *SessionsClient) DetectIntent(ctx context.Context, req *cxpb.DetectInten // Note: Always use agent versions for production traffic. // See Versions and // environments (at https://cloud.google.com/dialogflow/cx/docs/concept/version). +// +// This method is not supported for the REST transport. func (c *SessionsClient) StreamingDetectIntent(ctx context.Context, opts ...gax.CallOption) (cxpb.Sessions_StreamingDetectIntentClient, error) { return c.internalClient.StreamingDetectIntent(ctx, opts...) } @@ -311,6 +360,76 @@ func (c *sessionsGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type sessionsRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing SessionsClient + CallOptions **SessionsCallOptions +} + +// NewSessionsRESTClient creates a new sessions rest client. +// +// A session represents an interaction with a user. You retrieve user input +// and pass it to the DetectIntent method to determine +// user intent and respond. +func NewSessionsRESTClient(ctx context.Context, opts ...option.ClientOption) (*SessionsClient, error) { + clientOpts := append(defaultSessionsRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultSessionsRESTCallOptions() + c := &sessionsRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &SessionsClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultSessionsRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://dialogflow.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://dialogflow.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://dialogflow.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *sessionsRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *sessionsRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *sessionsRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *sessionsGRPCClient) DetectIntent(ctx context.Context, req *cxpb.DetectIntentRequest, opts ...gax.CallOption) (*cxpb.DetectIntentResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 220000*time.Millisecond) @@ -528,3 +647,556 @@ func (c *sessionsGRPCClient) ListOperations(ctx context.Context, req *longrunnin return it } + +// DetectIntent processes a natural language query and returns structured, actionable data +// as a result. This method is not idempotent, because it may cause session +// entity types to be updated, which in turn might affect results of future +// queries. +// +// Note: Always use agent versions for production traffic. +// See Versions and +// environments (at https://cloud.google.com/dialogflow/cx/docs/concept/version). +func (c *sessionsRESTClient) DetectIntent(ctx context.Context, req *cxpb.DetectIntentRequest, opts ...gax.CallOption) (*cxpb.DetectIntentResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v:detectIntent", req.GetSession()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "session", url.QueryEscape(req.GetSession()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).DetectIntent[0:len((*c.CallOptions).DetectIntent):len((*c.CallOptions).DetectIntent)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cxpb.DetectIntentResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// StreamingDetectIntent processes a natural language query in audio format in a streaming fashion +// and returns structured, actionable data as a result. This method is only +// available via the gRPC API (not REST). +// +// Note: Always use agent versions for production traffic. +// See Versions and +// environments (at https://cloud.google.com/dialogflow/cx/docs/concept/version). +// +// This method is not supported for the REST transport. +func (c *sessionsRESTClient) StreamingDetectIntent(ctx context.Context, opts ...gax.CallOption) (cxpb.Sessions_StreamingDetectIntentClient, error) { + return nil, fmt.Errorf("StreamingDetectIntent not yet supported for REST clients") +} + +// MatchIntent returns preliminary intent match results, doesn’t change the session +// status. +func (c *sessionsRESTClient) MatchIntent(ctx context.Context, req *cxpb.MatchIntentRequest, opts ...gax.CallOption) (*cxpb.MatchIntentResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v:matchIntent", req.GetSession()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "session", url.QueryEscape(req.GetSession()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).MatchIntent[0:len((*c.CallOptions).MatchIntent):len((*c.CallOptions).MatchIntent)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cxpb.MatchIntentResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// FulfillIntent fulfills a matched intent returned by MatchIntent. +// Must be called after MatchIntent, with input from +// MatchIntentResponse. Otherwise, the behavior is undefined. +func (c *sessionsRESTClient) FulfillIntent(ctx context.Context, req *cxpb.FulfillIntentRequest, opts ...gax.CallOption) (*cxpb.FulfillIntentResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v:fulfillIntent", req.GetMatchIntentRequest().GetSession()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "match_intent_request.session", url.QueryEscape(req.GetMatchIntentRequest().GetSession()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).FulfillIntent[0:len((*c.CallOptions).FulfillIntent):len((*c.CallOptions).FulfillIntent)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cxpb.FulfillIntentResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetLocation gets information about a location. +func (c *sessionsRESTClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *sessionsRESTClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *sessionsRESTClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v3/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *sessionsRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *sessionsRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} diff --git a/dialogflow/cx/apiv3/sessions_client_example_test.go b/dialogflow/cx/apiv3/sessions_client_example_test.go index 50fd3cdbaa19..37265cba9e16 100644 --- a/dialogflow/cx/apiv3/sessions_client_example_test.go +++ b/dialogflow/cx/apiv3/sessions_client_example_test.go @@ -44,6 +44,23 @@ func ExampleNewSessionsClient() { _ = c } +func ExampleNewSessionsRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := cx.NewSessionsRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleSessionsClient_DetectIntent() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/dialogflow/cx/apiv3/test_cases_client.go b/dialogflow/cx/apiv3/test_cases_client.go index b7c336f6c56a..a01aac7a91fe 100644 --- a/dialogflow/cx/apiv3/test_cases_client.go +++ b/dialogflow/cx/apiv3/test_cases_client.go @@ -17,9 +17,12 @@ package cx import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,15 +30,18 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -216,6 +222,136 @@ func defaultTestCasesCallOptions() *TestCasesCallOptions { } } +func defaultTestCasesRESTCallOptions() *TestCasesCallOptions { + return &TestCasesCallOptions{ + ListTestCases: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + BatchDeleteTestCases: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetTestCase: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateTestCase: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UpdateTestCase: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + RunTestCase: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + BatchRunTestCases: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CalculateCoverage: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ImportTestCases: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ExportTestCases: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListTestCaseResults: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetTestCaseResult: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + CancelOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalTestCasesClient is an interface that defines the methods available from Dialogflow API. type internalTestCasesClient interface { Close() error @@ -533,6 +669,90 @@ func (c *testCasesGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type testCasesRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing TestCasesClient + CallOptions **TestCasesCallOptions +} + +// NewTestCasesRESTClient creates a new test cases rest client. +// +// Service for managing [Test Cases][google.cloud.dialogflow.cx.v3.TestCase] and +// [Test Case Results][google.cloud.dialogflow.cx.v3.TestCaseResult]. +func NewTestCasesRESTClient(ctx context.Context, opts ...option.ClientOption) (*TestCasesClient, error) { + clientOpts := append(defaultTestCasesRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultTestCasesRESTCallOptions() + c := &testCasesRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &TestCasesClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultTestCasesRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://dialogflow.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://dialogflow.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://dialogflow.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *testCasesRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *testCasesRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *testCasesRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *testCasesGRPCClient) ListTestCases(ctx context.Context, req *cxpb.ListTestCasesRequest, opts ...gax.CallOption) *TestCaseIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -984,78 +1204,1277 @@ func (c *testCasesGRPCClient) ListOperations(ctx context.Context, req *longrunni return it } -// BatchRunTestCasesOperation manages a long-running operation from BatchRunTestCases. -type BatchRunTestCasesOperation struct { - lro *longrunning.Operation -} +// ListTestCases fetches a list of test cases for a given agent. +func (c *testCasesRESTClient) ListTestCases(ctx context.Context, req *cxpb.ListTestCasesRequest, opts ...gax.CallOption) *TestCaseIterator { + it := &TestCaseIterator{} + req = proto.Clone(req).(*cxpb.ListTestCasesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*cxpb.TestCase, string, error) { + resp := &cxpb.ListTestCasesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/testCases", req.GetParent()) -// BatchRunTestCasesOperation returns a new BatchRunTestCasesOperation from a given name. -// The name must be that of a previously created BatchRunTestCasesOperation, possibly from a different process. -func (c *testCasesGRPCClient) BatchRunTestCasesOperation(name string) *BatchRunTestCasesOperation { - return &BatchRunTestCasesOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + if req.GetView() != 0 { + params.Add("view", fmt.Sprintf("%v", req.GetView())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetTestCases(), resp.GetNextPageToken(), nil } -} -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *BatchRunTestCasesOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*cxpb.BatchRunTestCasesResponse, error) { - var resp cxpb.BatchRunTestCasesResponse - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { - return nil, err + 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 } - return &resp, nil + + it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it } -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *BatchRunTestCasesOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*cxpb.BatchRunTestCasesResponse, error) { - var resp cxpb.BatchRunTestCasesResponse - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { - return nil, err +// BatchDeleteTestCases batch deletes test cases. +func (c *testCasesRESTClient) BatchDeleteTestCases(ctx context.Context, req *cxpb.BatchDeleteTestCasesRequest, opts ...gax.CallOption) error { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return err } - if !op.Done() { - return nil, nil + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err } - return &resp, nil + baseUrl.Path += fmt.Sprintf("/v3/%v/testCases:batchDelete", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) } -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *BatchRunTestCasesOperation) Metadata() (*cxpb.BatchRunTestCasesMetadata, error) { - var meta cxpb.BatchRunTestCasesMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { +// GetTestCase gets a test case. +func (c *testCasesRESTClient) GetTestCase(ctx context.Context, req *cxpb.GetTestCaseRequest, opts ...gax.CallOption) (*cxpb.TestCase, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - return &meta, nil -} + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) -// Done reports whether the long-running operation has completed. -func (op *BatchRunTestCasesOperation) Done() bool { - return op.lro.Done() -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") -// 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 *BatchRunTestCasesOperation) Name() string { + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetTestCase[0:len((*c.CallOptions).GetTestCase):len((*c.CallOptions).GetTestCase)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cxpb.TestCase{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateTestCase creates a test case for the given agent. +func (c *testCasesRESTClient) CreateTestCase(ctx context.Context, req *cxpb.CreateTestCaseRequest, opts ...gax.CallOption) (*cxpb.TestCase, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetTestCase() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/testCases", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateTestCase[0:len((*c.CallOptions).CreateTestCase):len((*c.CallOptions).CreateTestCase)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cxpb.TestCase{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateTestCase updates the specified test case. +func (c *testCasesRESTClient) UpdateTestCase(ctx context.Context, req *cxpb.UpdateTestCaseRequest, opts ...gax.CallOption) (*cxpb.TestCase, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetTestCase() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetTestCase().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "test_case.name", url.QueryEscape(req.GetTestCase().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateTestCase[0:len((*c.CallOptions).UpdateTestCase):len((*c.CallOptions).UpdateTestCase)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cxpb.TestCase{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// RunTestCase kicks off a test case run. +// +// This method is a long-running +// operation (at https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation). +// The returned Operation type has the following method-specific fields: +// +// metadata: RunTestCaseMetadata +// +// response: RunTestCaseResponse +func (c *testCasesRESTClient) RunTestCase(ctx context.Context, req *cxpb.RunTestCaseRequest, opts ...gax.CallOption) (*RunTestCaseOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v:run", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v3/%s", resp.GetName()) + return &RunTestCaseOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// BatchRunTestCases kicks off a batch run of test cases. +// +// This method is a long-running +// operation (at https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation). +// The returned Operation type has the following method-specific fields: +// +// metadata: BatchRunTestCasesMetadata +// +// response: BatchRunTestCasesResponse +func (c *testCasesRESTClient) BatchRunTestCases(ctx context.Context, req *cxpb.BatchRunTestCasesRequest, opts ...gax.CallOption) (*BatchRunTestCasesOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/testCases:batchRun", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v3/%s", resp.GetName()) + return &BatchRunTestCasesOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// CalculateCoverage calculates the test coverage for an agent. +func (c *testCasesRESTClient) CalculateCoverage(ctx context.Context, req *cxpb.CalculateCoverageRequest, opts ...gax.CallOption) (*cxpb.CalculateCoverageResponse, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/testCases:calculateCoverage", req.GetAgent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("type", fmt.Sprintf("%v", req.GetType())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "agent", url.QueryEscape(req.GetAgent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CalculateCoverage[0:len((*c.CallOptions).CalculateCoverage):len((*c.CallOptions).CalculateCoverage)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cxpb.CalculateCoverageResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ImportTestCases imports the test cases from a Cloud Storage bucket or a local file. It +// always creates new test cases and won’t overwrite any existing ones. The +// provided ID in the imported test case is neglected. +// +// This method is a long-running +// operation (at https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation). +// The returned Operation type has the following method-specific fields: +// +// metadata: ImportTestCasesMetadata +// +// response: ImportTestCasesResponse +func (c *testCasesRESTClient) ImportTestCases(ctx context.Context, req *cxpb.ImportTestCasesRequest, opts ...gax.CallOption) (*ImportTestCasesOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/testCases:import", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v3/%s", resp.GetName()) + return &ImportTestCasesOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ExportTestCases exports the test cases under the agent to a Cloud Storage bucket or a local +// file. Filter can be applied to export a subset of test cases. +// +// This method is a long-running +// operation (at https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation). +// The returned Operation type has the following method-specific fields: +// +// metadata: ExportTestCasesMetadata +// +// response: ExportTestCasesResponse +func (c *testCasesRESTClient) ExportTestCases(ctx context.Context, req *cxpb.ExportTestCasesRequest, opts ...gax.CallOption) (*ExportTestCasesOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/testCases:export", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v3/%s", resp.GetName()) + return &ExportTestCasesOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListTestCaseResults fetches a list of results for a given test case. +func (c *testCasesRESTClient) ListTestCaseResults(ctx context.Context, req *cxpb.ListTestCaseResultsRequest, opts ...gax.CallOption) *TestCaseResultIterator { + it := &TestCaseResultIterator{} + req = proto.Clone(req).(*cxpb.ListTestCaseResultsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*cxpb.TestCaseResult, string, error) { + resp := &cxpb.ListTestCaseResultsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/results", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetTestCaseResults(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetTestCaseResult gets a test case result. +func (c *testCasesRESTClient) GetTestCaseResult(ctx context.Context, req *cxpb.GetTestCaseResultRequest, opts ...gax.CallOption) (*cxpb.TestCaseResult, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetTestCaseResult[0:len((*c.CallOptions).GetTestCaseResult):len((*c.CallOptions).GetTestCaseResult)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cxpb.TestCaseResult{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetLocation gets information about a location. +func (c *testCasesRESTClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *testCasesRESTClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *testCasesRESTClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v3/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *testCasesRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *testCasesRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// BatchRunTestCasesOperation manages a long-running operation from BatchRunTestCases. +type BatchRunTestCasesOperation struct { + lro *longrunning.Operation + pollPath string +} + +// BatchRunTestCasesOperation returns a new BatchRunTestCasesOperation from a given name. +// The name must be that of a previously created BatchRunTestCasesOperation, possibly from a different process. +func (c *testCasesGRPCClient) BatchRunTestCasesOperation(name string) *BatchRunTestCasesOperation { + return &BatchRunTestCasesOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// BatchRunTestCasesOperation returns a new BatchRunTestCasesOperation from a given name. +// The name must be that of a previously created BatchRunTestCasesOperation, possibly from a different process. +func (c *testCasesRESTClient) BatchRunTestCasesOperation(name string) *BatchRunTestCasesOperation { + override := fmt.Sprintf("/v3/%s", name) + return &BatchRunTestCasesOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *BatchRunTestCasesOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*cxpb.BatchRunTestCasesResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp cxpb.BatchRunTestCasesResponse + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *BatchRunTestCasesOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*cxpb.BatchRunTestCasesResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp cxpb.BatchRunTestCasesResponse + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *BatchRunTestCasesOperation) Metadata() (*cxpb.BatchRunTestCasesMetadata, error) { + var meta cxpb.BatchRunTestCasesMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *BatchRunTestCasesOperation) Done() bool { + return op.lro.Done() +} + +// 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 *BatchRunTestCasesOperation) Name() string { return op.lro.Name() } // ExportTestCasesOperation manages a long-running operation from ExportTestCases. type ExportTestCasesOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // ExportTestCasesOperation returns a new ExportTestCasesOperation from a given name. @@ -1066,10 +2485,21 @@ func (c *testCasesGRPCClient) ExportTestCasesOperation(name string) *ExportTestC } } +// ExportTestCasesOperation returns a new ExportTestCasesOperation from a given name. +// The name must be that of a previously created ExportTestCasesOperation, possibly from a different process. +func (c *testCasesRESTClient) ExportTestCasesOperation(name string) *ExportTestCasesOperation { + override := fmt.Sprintf("/v3/%s", name) + return &ExportTestCasesOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *ExportTestCasesOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*cxpb.ExportTestCasesResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp cxpb.ExportTestCasesResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1087,6 +2517,7 @@ func (op *ExportTestCasesOperation) Wait(ctx context.Context, opts ...gax.CallOp // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *ExportTestCasesOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*cxpb.ExportTestCasesResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp cxpb.ExportTestCasesResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1124,7 +2555,8 @@ func (op *ExportTestCasesOperation) Name() string { // ImportTestCasesOperation manages a long-running operation from ImportTestCases. type ImportTestCasesOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // ImportTestCasesOperation returns a new ImportTestCasesOperation from a given name. @@ -1135,10 +2567,21 @@ func (c *testCasesGRPCClient) ImportTestCasesOperation(name string) *ImportTestC } } +// ImportTestCasesOperation returns a new ImportTestCasesOperation from a given name. +// The name must be that of a previously created ImportTestCasesOperation, possibly from a different process. +func (c *testCasesRESTClient) ImportTestCasesOperation(name string) *ImportTestCasesOperation { + override := fmt.Sprintf("/v3/%s", name) + return &ImportTestCasesOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *ImportTestCasesOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*cxpb.ImportTestCasesResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp cxpb.ImportTestCasesResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1156,6 +2599,7 @@ func (op *ImportTestCasesOperation) Wait(ctx context.Context, opts ...gax.CallOp // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *ImportTestCasesOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*cxpb.ImportTestCasesResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp cxpb.ImportTestCasesResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1193,7 +2637,8 @@ func (op *ImportTestCasesOperation) Name() string { // RunTestCaseOperation manages a long-running operation from RunTestCase. type RunTestCaseOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // RunTestCaseOperation returns a new RunTestCaseOperation from a given name. @@ -1204,10 +2649,21 @@ func (c *testCasesGRPCClient) RunTestCaseOperation(name string) *RunTestCaseOper } } +// RunTestCaseOperation returns a new RunTestCaseOperation from a given name. +// The name must be that of a previously created RunTestCaseOperation, possibly from a different process. +func (c *testCasesRESTClient) RunTestCaseOperation(name string) *RunTestCaseOperation { + override := fmt.Sprintf("/v3/%s", name) + return &RunTestCaseOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *RunTestCaseOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*cxpb.RunTestCaseResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp cxpb.RunTestCaseResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1225,6 +2681,7 @@ func (op *RunTestCaseOperation) Wait(ctx context.Context, opts ...gax.CallOption // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *RunTestCaseOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*cxpb.RunTestCaseResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp cxpb.RunTestCaseResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/dialogflow/cx/apiv3/test_cases_client_example_test.go b/dialogflow/cx/apiv3/test_cases_client_example_test.go index f0ec86e39197..6aebe95176d7 100644 --- a/dialogflow/cx/apiv3/test_cases_client_example_test.go +++ b/dialogflow/cx/apiv3/test_cases_client_example_test.go @@ -43,6 +43,23 @@ func ExampleNewTestCasesClient() { _ = c } +func ExampleNewTestCasesRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := cx.NewTestCasesRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleTestCasesClient_ListTestCases() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/dialogflow/cx/apiv3/transition_route_groups_client.go b/dialogflow/cx/apiv3/transition_route_groups_client.go index 9d5794938130..c079edbb2952 100644 --- a/dialogflow/cx/apiv3/transition_route_groups_client.go +++ b/dialogflow/cx/apiv3/transition_route_groups_client.go @@ -17,23 +17,29 @@ package cx import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" cxpb "cloud.google.com/go/dialogflow/cx/apiv3/cxpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -130,6 +136,66 @@ func defaultTransitionRouteGroupsCallOptions() *TransitionRouteGroupsCallOptions } } +func defaultTransitionRouteGroupsRESTCallOptions() *TransitionRouteGroupsCallOptions { + return &TransitionRouteGroupsCallOptions{ + ListTransitionRouteGroups: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetTransitionRouteGroup: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateTransitionRouteGroup: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UpdateTransitionRouteGroup: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeleteTransitionRouteGroup: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + CancelOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalTransitionRouteGroupsClient is an interface that defines the methods available from Dialogflow API. type internalTransitionRouteGroupsClient interface { Close() error @@ -331,6 +397,74 @@ func (c *transitionRouteGroupsGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type transitionRouteGroupsRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing TransitionRouteGroupsClient + CallOptions **TransitionRouteGroupsCallOptions +} + +// NewTransitionRouteGroupsRESTClient creates a new transition route groups rest client. +// +// Service for managing TransitionRouteGroups. +func NewTransitionRouteGroupsRESTClient(ctx context.Context, opts ...option.ClientOption) (*TransitionRouteGroupsClient, error) { + clientOpts := append(defaultTransitionRouteGroupsRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultTransitionRouteGroupsRESTCallOptions() + c := &transitionRouteGroupsRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &TransitionRouteGroupsClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultTransitionRouteGroupsRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://dialogflow.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://dialogflow.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://dialogflow.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *transitionRouteGroupsRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *transitionRouteGroupsRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *transitionRouteGroupsRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *transitionRouteGroupsGRPCClient) ListTransitionRouteGroups(ctx context.Context, req *cxpb.ListTransitionRouteGroupsRequest, opts ...gax.CallOption) *TransitionRouteGroupIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -597,6 +731,694 @@ func (c *transitionRouteGroupsGRPCClient) ListOperations(ctx context.Context, re return it } +// ListTransitionRouteGroups returns the list of all transition route groups in the specified flow. +func (c *transitionRouteGroupsRESTClient) ListTransitionRouteGroups(ctx context.Context, req *cxpb.ListTransitionRouteGroupsRequest, opts ...gax.CallOption) *TransitionRouteGroupIterator { + it := &TransitionRouteGroupIterator{} + req = proto.Clone(req).(*cxpb.ListTransitionRouteGroupsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*cxpb.TransitionRouteGroup, string, error) { + resp := &cxpb.ListTransitionRouteGroupsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/transitionRouteGroups", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetLanguageCode() != "" { + params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetTransitionRouteGroups(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetTransitionRouteGroup retrieves the specified TransitionRouteGroup. +func (c *transitionRouteGroupsRESTClient) GetTransitionRouteGroup(ctx context.Context, req *cxpb.GetTransitionRouteGroupRequest, opts ...gax.CallOption) (*cxpb.TransitionRouteGroup, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetLanguageCode() != "" { + params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetTransitionRouteGroup[0:len((*c.CallOptions).GetTransitionRouteGroup):len((*c.CallOptions).GetTransitionRouteGroup)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cxpb.TransitionRouteGroup{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateTransitionRouteGroup creates an TransitionRouteGroup in the specified flow. +// +// Note: You should always train a flow prior to sending it queries. See the +// training +// documentation (at https://cloud.google.com/dialogflow/cx/docs/concept/training). +func (c *transitionRouteGroupsRESTClient) CreateTransitionRouteGroup(ctx context.Context, req *cxpb.CreateTransitionRouteGroupRequest, opts ...gax.CallOption) (*cxpb.TransitionRouteGroup, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetTransitionRouteGroup() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/transitionRouteGroups", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetLanguageCode() != "" { + params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateTransitionRouteGroup[0:len((*c.CallOptions).CreateTransitionRouteGroup):len((*c.CallOptions).CreateTransitionRouteGroup)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cxpb.TransitionRouteGroup{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateTransitionRouteGroup updates the specified TransitionRouteGroup. +// +// Note: You should always train a flow prior to sending it queries. See the +// training +// documentation (at https://cloud.google.com/dialogflow/cx/docs/concept/training). +func (c *transitionRouteGroupsRESTClient) UpdateTransitionRouteGroup(ctx context.Context, req *cxpb.UpdateTransitionRouteGroupRequest, opts ...gax.CallOption) (*cxpb.TransitionRouteGroup, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetTransitionRouteGroup() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetTransitionRouteGroup().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetLanguageCode() != "" { + params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) + } + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "transition_route_group.name", url.QueryEscape(req.GetTransitionRouteGroup().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateTransitionRouteGroup[0:len((*c.CallOptions).UpdateTransitionRouteGroup):len((*c.CallOptions).UpdateTransitionRouteGroup)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cxpb.TransitionRouteGroup{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteTransitionRouteGroup deletes the specified TransitionRouteGroup. +// +// Note: You should always train a flow prior to sending it queries. See the +// training +// documentation (at https://cloud.google.com/dialogflow/cx/docs/concept/training). +func (c *transitionRouteGroupsRESTClient) DeleteTransitionRouteGroup(ctx context.Context, req *cxpb.DeleteTransitionRouteGroupRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetForce() { + params.Add("force", fmt.Sprintf("%v", req.GetForce())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetLocation gets information about a location. +func (c *transitionRouteGroupsRESTClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *transitionRouteGroupsRESTClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *transitionRouteGroupsRESTClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v3/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *transitionRouteGroupsRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *transitionRouteGroupsRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + // TransitionRouteGroupIterator manages a stream of *cxpb.TransitionRouteGroup. type TransitionRouteGroupIterator struct { items []*cxpb.TransitionRouteGroup diff --git a/dialogflow/cx/apiv3/transition_route_groups_client_example_test.go b/dialogflow/cx/apiv3/transition_route_groups_client_example_test.go index e468a2c61ff3..b01659fc23ba 100644 --- a/dialogflow/cx/apiv3/transition_route_groups_client_example_test.go +++ b/dialogflow/cx/apiv3/transition_route_groups_client_example_test.go @@ -43,6 +43,23 @@ func ExampleNewTransitionRouteGroupsClient() { _ = c } +func ExampleNewTransitionRouteGroupsRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := cx.NewTransitionRouteGroupsRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleTransitionRouteGroupsClient_ListTransitionRouteGroups() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/dialogflow/cx/apiv3/versions_client.go b/dialogflow/cx/apiv3/versions_client.go index 4ea008ea3740..3e55ecdde427 100644 --- a/dialogflow/cx/apiv3/versions_client.go +++ b/dialogflow/cx/apiv3/versions_client.go @@ -17,9 +17,12 @@ package cx import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,15 +30,18 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" structpb "google.golang.org/protobuf/types/known/structpb" ) @@ -157,6 +163,86 @@ func defaultVersionsCallOptions() *VersionsCallOptions { } } +func defaultVersionsRESTCallOptions() *VersionsCallOptions { + return &VersionsCallOptions{ + ListVersions: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetVersion: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateVersion: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UpdateVersion: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeleteVersion: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + LoadVersion: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CompareVersions: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + CancelOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalVersionsClient is an interface that defines the methods available from Dialogflow API. type internalVersionsClient interface { Close() error @@ -411,6 +497,89 @@ func (c *versionsGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type versionsRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing VersionsClient + CallOptions **VersionsCallOptions +} + +// NewVersionsRESTClient creates a new versions rest client. +// +// Service for managing Versions. +func NewVersionsRESTClient(ctx context.Context, opts ...option.ClientOption) (*VersionsClient, error) { + clientOpts := append(defaultVersionsRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultVersionsRESTCallOptions() + c := &versionsRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &VersionsClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultVersionsRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://dialogflow.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://dialogflow.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://dialogflow.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *versionsRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *versionsRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *versionsRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *versionsGRPCClient) ListVersions(ctx context.Context, req *cxpb.ListVersionsRequest, opts ...gax.CallOption) *VersionIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -725,85 +894,924 @@ func (c *versionsGRPCClient) ListOperations(ctx context.Context, req *longrunnin return it } -// CreateVersionOperation manages a long-running operation from CreateVersion. -type CreateVersionOperation struct { - lro *longrunning.Operation -} +// ListVersions returns the list of all versions in the specified Flow. +func (c *versionsRESTClient) ListVersions(ctx context.Context, req *cxpb.ListVersionsRequest, opts ...gax.CallOption) *VersionIterator { + it := &VersionIterator{} + req = proto.Clone(req).(*cxpb.ListVersionsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*cxpb.Version, string, error) { + resp := &cxpb.ListVersionsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/versions", req.GetParent()) -// CreateVersionOperation returns a new CreateVersionOperation from a given name. -// The name must be that of a previously created CreateVersionOperation, possibly from a different process. -func (c *versionsGRPCClient) CreateVersionOperation(name string) *CreateVersionOperation { - return &CreateVersionOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetVersions(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it } -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *CreateVersionOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*cxpb.Version, error) { - var resp cxpb.Version - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { +// GetVersion retrieves the specified Version. +func (c *versionsRESTClient) GetVersion(ctx context.Context, req *cxpb.GetVersionRequest, opts ...gax.CallOption) (*cxpb.Version, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - return &resp, nil + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetVersion[0:len((*c.CallOptions).GetVersion):len((*c.CallOptions).GetVersion)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cxpb.Version{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil } -// Poll fetches the latest state of the long-running operation. +// CreateVersion creates a Version in the specified Flow. // -// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// This method is a long-running +// operation (at https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation). +// The returned Operation type has the following method-specific fields: // -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *CreateVersionOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*cxpb.Version, error) { - var resp cxpb.Version - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { +// metadata: CreateVersionOperationMetadata +// +// response: Version +func (c *versionsRESTClient) CreateVersion(ctx context.Context, req *cxpb.CreateVersionRequest, opts ...gax.CallOption) (*CreateVersionOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetVersion() + jsonReq, err := m.Marshal(body) + if err != nil { return nil, err } - if !op.Done() { - return nil, nil - } - return &resp, nil -} -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *CreateVersionOperation) Metadata() (*cxpb.CreateVersionOperationMetadata, error) { - var meta cxpb.CreateVersionOperationMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - return &meta, nil -} + baseUrl.Path += fmt.Sprintf("/v3/%v/versions", req.GetParent()) -// Done reports whether the long-running operation has completed. -func (op *CreateVersionOperation) Done() bool { - return op.lro.Done() -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") -// 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 *CreateVersionOperation) Name() string { - return op.lro.Name() -} + baseUrl.RawQuery = params.Encode() -// LoadVersionOperation manages a long-running operation from LoadVersion. -type LoadVersionOperation struct { - lro *longrunning.Operation -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) -// LoadVersionOperation returns a new LoadVersionOperation from a given name. -// The name must be that of a previously created LoadVersionOperation, possibly from a different process. -func (c *versionsGRPCClient) LoadVersionOperation(name string) *LoadVersionOperation { - return &LoadVersionOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v3/%s", resp.GetName()) + return &CreateVersionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateVersion updates the specified Version. +func (c *versionsRESTClient) UpdateVersion(ctx context.Context, req *cxpb.UpdateVersionRequest, opts ...gax.CallOption) (*cxpb.Version, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetVersion() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetVersion().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "version.name", url.QueryEscape(req.GetVersion().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateVersion[0:len((*c.CallOptions).UpdateVersion):len((*c.CallOptions).UpdateVersion)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cxpb.Version{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteVersion deletes the specified Version. +func (c *versionsRESTClient) DeleteVersion(ctx context.Context, req *cxpb.DeleteVersionRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// LoadVersion loads resources in the specified version to the draft flow. +// +// This method is a long-running +// operation (at https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation). +// The returned Operation type has the following method-specific fields: +// +// metadata: An empty Struct +// message (at https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) +// +// response: An Empty +// message (at https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) +func (c *versionsRESTClient) LoadVersion(ctx context.Context, req *cxpb.LoadVersionRequest, opts ...gax.CallOption) (*LoadVersionOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v:load", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v3/%s", resp.GetName()) + return &LoadVersionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// CompareVersions compares the specified base version with target version. +func (c *versionsRESTClient) CompareVersions(ctx context.Context, req *cxpb.CompareVersionsRequest, opts ...gax.CallOption) (*cxpb.CompareVersionsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v:compareVersions", req.GetBaseVersion()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "base_version", url.QueryEscape(req.GetBaseVersion()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CompareVersions[0:len((*c.CallOptions).CompareVersions):len((*c.CallOptions).CompareVersions)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cxpb.CompareVersionsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetLocation gets information about a location. +func (c *versionsRESTClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *versionsRESTClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *versionsRESTClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v3/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *versionsRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *versionsRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CreateVersionOperation manages a long-running operation from CreateVersion. +type CreateVersionOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateVersionOperation returns a new CreateVersionOperation from a given name. +// The name must be that of a previously created CreateVersionOperation, possibly from a different process. +func (c *versionsGRPCClient) CreateVersionOperation(name string) *CreateVersionOperation { + return &CreateVersionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateVersionOperation returns a new CreateVersionOperation from a given name. +// The name must be that of a previously created CreateVersionOperation, possibly from a different process. +func (c *versionsRESTClient) CreateVersionOperation(name string) *CreateVersionOperation { + override := fmt.Sprintf("/v3/%s", name) + return &CreateVersionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CreateVersionOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*cxpb.Version, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp cxpb.Version + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *CreateVersionOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*cxpb.Version, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp cxpb.Version + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *CreateVersionOperation) Metadata() (*cxpb.CreateVersionOperationMetadata, error) { + var meta cxpb.CreateVersionOperationMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *CreateVersionOperation) Done() bool { + return op.lro.Done() +} + +// 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 *CreateVersionOperation) Name() string { + return op.lro.Name() +} + +// LoadVersionOperation manages a long-running operation from LoadVersion. +type LoadVersionOperation struct { + lro *longrunning.Operation + pollPath string +} + +// LoadVersionOperation returns a new LoadVersionOperation from a given name. +// The name must be that of a previously created LoadVersionOperation, possibly from a different process. +func (c *versionsGRPCClient) LoadVersionOperation(name string) *LoadVersionOperation { + return &LoadVersionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// LoadVersionOperation returns a new LoadVersionOperation from a given name. +// The name must be that of a previously created LoadVersionOperation, possibly from a different process. +func (c *versionsRESTClient) LoadVersionOperation(name string) *LoadVersionOperation { + override := fmt.Sprintf("/v3/%s", name) + return &LoadVersionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, } } @@ -811,6 +1819,7 @@ func (c *versionsGRPCClient) LoadVersionOperation(name string) *LoadVersionOpera // // See documentation of Poll for error-handling information. func (op *LoadVersionOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -824,6 +1833,7 @@ func (op *LoadVersionOperation) Wait(ctx context.Context, opts ...gax.CallOption // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *LoadVersionOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } diff --git a/dialogflow/cx/apiv3/versions_client_example_test.go b/dialogflow/cx/apiv3/versions_client_example_test.go index 03b69f62729c..d5cc97dd8808 100644 --- a/dialogflow/cx/apiv3/versions_client_example_test.go +++ b/dialogflow/cx/apiv3/versions_client_example_test.go @@ -43,6 +43,23 @@ func ExampleNewVersionsClient() { _ = c } +func ExampleNewVersionsRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := cx.NewVersionsRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleVersionsClient_ListVersions() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/dialogflow/cx/apiv3/webhooks_client.go b/dialogflow/cx/apiv3/webhooks_client.go index 1cc7b6e8c965..faa0c70b6237 100644 --- a/dialogflow/cx/apiv3/webhooks_client.go +++ b/dialogflow/cx/apiv3/webhooks_client.go @@ -17,23 +17,29 @@ package cx import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" cxpb "cloud.google.com/go/dialogflow/cx/apiv3/cxpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -130,6 +136,66 @@ func defaultWebhooksCallOptions() *WebhooksCallOptions { } } +func defaultWebhooksRESTCallOptions() *WebhooksCallOptions { + return &WebhooksCallOptions{ + ListWebhooks: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetWebhook: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateWebhook: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UpdateWebhook: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeleteWebhook: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + CancelOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalWebhooksClient is an interface that defines the methods available from Dialogflow API. type internalWebhooksClient interface { Close() error @@ -319,6 +385,74 @@ func (c *webhooksGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type webhooksRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing WebhooksClient + CallOptions **WebhooksCallOptions +} + +// NewWebhooksRESTClient creates a new webhooks rest client. +// +// Service for managing Webhooks. +func NewWebhooksRESTClient(ctx context.Context, opts ...option.ClientOption) (*WebhooksClient, error) { + clientOpts := append(defaultWebhooksRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultWebhooksRESTCallOptions() + c := &webhooksRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &WebhooksClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultWebhooksRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://dialogflow.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://dialogflow.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://dialogflow.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *webhooksRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *webhooksRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *webhooksRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *webhooksGRPCClient) ListWebhooks(ctx context.Context, req *cxpb.ListWebhooksRequest, opts ...gax.CallOption) *WebhookIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -585,6 +719,670 @@ func (c *webhooksGRPCClient) ListOperations(ctx context.Context, req *longrunnin return it } +// ListWebhooks returns the list of all webhooks in the specified agent. +func (c *webhooksRESTClient) ListWebhooks(ctx context.Context, req *cxpb.ListWebhooksRequest, opts ...gax.CallOption) *WebhookIterator { + it := &WebhookIterator{} + req = proto.Clone(req).(*cxpb.ListWebhooksRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*cxpb.Webhook, string, error) { + resp := &cxpb.ListWebhooksResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/webhooks", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetWebhooks(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetWebhook retrieves the specified webhook. +func (c *webhooksRESTClient) GetWebhook(ctx context.Context, req *cxpb.GetWebhookRequest, opts ...gax.CallOption) (*cxpb.Webhook, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetWebhook[0:len((*c.CallOptions).GetWebhook):len((*c.CallOptions).GetWebhook)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cxpb.Webhook{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateWebhook creates a webhook in the specified agent. +func (c *webhooksRESTClient) CreateWebhook(ctx context.Context, req *cxpb.CreateWebhookRequest, opts ...gax.CallOption) (*cxpb.Webhook, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetWebhook() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/webhooks", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateWebhook[0:len((*c.CallOptions).CreateWebhook):len((*c.CallOptions).CreateWebhook)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cxpb.Webhook{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateWebhook updates the specified webhook. +func (c *webhooksRESTClient) UpdateWebhook(ctx context.Context, req *cxpb.UpdateWebhookRequest, opts ...gax.CallOption) (*cxpb.Webhook, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetWebhook() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetWebhook().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "webhook.name", url.QueryEscape(req.GetWebhook().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateWebhook[0:len((*c.CallOptions).UpdateWebhook):len((*c.CallOptions).UpdateWebhook)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &cxpb.Webhook{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteWebhook deletes the specified webhook. +func (c *webhooksRESTClient) DeleteWebhook(ctx context.Context, req *cxpb.DeleteWebhookRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetForce() { + params.Add("force", fmt.Sprintf("%v", req.GetForce())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetLocation gets information about a location. +func (c *webhooksRESTClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *webhooksRESTClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *webhooksRESTClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v3/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *webhooksRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *webhooksRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + // WebhookIterator manages a stream of *cxpb.Webhook. type WebhookIterator struct { items []*cxpb.Webhook diff --git a/dialogflow/cx/apiv3/webhooks_client_example_test.go b/dialogflow/cx/apiv3/webhooks_client_example_test.go index 07f3b0ba5f07..c41d23981165 100644 --- a/dialogflow/cx/apiv3/webhooks_client_example_test.go +++ b/dialogflow/cx/apiv3/webhooks_client_example_test.go @@ -43,6 +43,23 @@ func ExampleNewWebhooksClient() { _ = c } +func ExampleNewWebhooksRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := cx.NewWebhooksRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleWebhooksClient_ListWebhooks() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/dialogflow/cx/apiv3beta1/agents_client.go b/dialogflow/cx/apiv3beta1/agents_client.go index d5059a821186..253fac4eba08 100644 --- a/dialogflow/cx/apiv3beta1/agents_client.go +++ b/dialogflow/cx/apiv3beta1/agents_client.go @@ -1035,6 +1035,7 @@ func (c *agentsRESTClient) ListAgents(ctx context.Context, req *cxpb.ListAgentsR baseUrl.Path += fmt.Sprintf("/v3beta1/%v/agents", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -1108,6 +1109,11 @@ func (c *agentsRESTClient) GetAgent(ctx context.Context, req *cxpb.GetAgentReque } baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1172,6 +1178,11 @@ func (c *agentsRESTClient) CreateAgent(ctx context.Context, req *cxpb.CreateAgen } baseUrl.Path += fmt.Sprintf("/v3beta1/%v/agents", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1237,6 +1248,7 @@ func (c *agentsRESTClient) UpdateAgent(ctx context.Context, req *cxpb.UpdateAgen baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetAgent().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -1300,6 +1312,11 @@ func (c *agentsRESTClient) DeleteAgent(ctx context.Context, req *cxpb.DeleteAgen } baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1350,6 +1367,11 @@ func (c *agentsRESTClient) ExportAgent(ctx context.Context, req *cxpb.ExportAgen } baseUrl.Path += fmt.Sprintf("/v3beta1/%v:export", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1430,6 +1452,11 @@ func (c *agentsRESTClient) RestoreAgent(ctx context.Context, req *cxpb.RestoreAg } baseUrl.Path += fmt.Sprintf("/v3beta1/%v:restore", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1495,6 +1522,11 @@ func (c *agentsRESTClient) ValidateAgent(ctx context.Context, req *cxpb.Validate } baseUrl.Path += fmt.Sprintf("/v3beta1/%v:validate", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1550,6 +1582,7 @@ func (c *agentsRESTClient) GetAgentValidationResult(ctx context.Context, req *cx baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetLanguageCode() != "" { params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) } @@ -1609,6 +1642,11 @@ func (c *agentsRESTClient) GetLocation(ctx context.Context, req *locationpb.GetL } baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1676,6 +1714,7 @@ func (c *agentsRESTClient) ListLocations(ctx context.Context, req *locationpb.Li baseUrl.Path += fmt.Sprintf("/v3beta1/%v/locations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1752,6 +1791,11 @@ func (c *agentsRESTClient) CancelOperation(ctx context.Context, req *longrunning } baseUrl.Path += fmt.Sprintf("/v3beta1/%v:cancel", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1787,6 +1831,11 @@ func (c *agentsRESTClient) GetOperation(ctx context.Context, req *longrunningpb. } baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1854,6 +1903,7 @@ func (c *agentsRESTClient) ListOperations(ctx context.Context, req *longrunningp baseUrl.Path += fmt.Sprintf("/v3beta1/%v/operations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/dialogflow/cx/apiv3beta1/changelogs_client.go b/dialogflow/cx/apiv3beta1/changelogs_client.go index c39b020c2064..98e76f6b5baf 100644 --- a/dialogflow/cx/apiv3beta1/changelogs_client.go +++ b/dialogflow/cx/apiv3beta1/changelogs_client.go @@ -594,6 +594,7 @@ func (c *changelogsRESTClient) ListChangelogs(ctx context.Context, req *cxpb.Lis baseUrl.Path += fmt.Sprintf("/v3beta1/%v/changelogs", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -670,6 +671,11 @@ func (c *changelogsRESTClient) GetChangelog(ctx context.Context, req *cxpb.GetCh } baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -723,6 +729,11 @@ func (c *changelogsRESTClient) GetLocation(ctx context.Context, req *locationpb. } baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -790,6 +801,7 @@ func (c *changelogsRESTClient) ListLocations(ctx context.Context, req *locationp baseUrl.Path += fmt.Sprintf("/v3beta1/%v/locations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -866,6 +878,11 @@ func (c *changelogsRESTClient) CancelOperation(ctx context.Context, req *longrun } baseUrl.Path += fmt.Sprintf("/v3beta1/%v:cancel", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -901,6 +918,11 @@ func (c *changelogsRESTClient) GetOperation(ctx context.Context, req *longrunnin } baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -968,6 +990,7 @@ func (c *changelogsRESTClient) ListOperations(ctx context.Context, req *longrunn baseUrl.Path += fmt.Sprintf("/v3beta1/%v/operations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/dialogflow/cx/apiv3beta1/cxpb/advanced_settings.pb.go b/dialogflow/cx/apiv3beta1/cxpb/advanced_settings.pb.go index 779249b967f0..facc3fdd2bf9 100644 --- a/dialogflow/cx/apiv3beta1/cxpb/advanced_settings.pb.go +++ b/dialogflow/cx/apiv3beta1/cxpb/advanced_settings.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dialogflow/cx/v3beta1/advanced_settings.proto package cxpb diff --git a/dialogflow/cx/apiv3beta1/cxpb/agent.pb.go b/dialogflow/cx/apiv3beta1/cxpb/agent.pb.go index 30628a14b557..b13045fb7b1d 100644 --- a/dialogflow/cx/apiv3beta1/cxpb/agent.pb.go +++ b/dialogflow/cx/apiv3beta1/cxpb/agent.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dialogflow/cx/v3beta1/agent.proto package cxpb @@ -842,7 +842,6 @@ type ExportAgentResponse struct { // The exported agent. // // Types that are assignable to Agent: - // // *ExportAgentResponse_AgentUri // *ExportAgentResponse_AgentContent Agent isExportAgentResponse_Agent `protobuf_oneof:"agent"` @@ -932,7 +931,6 @@ type RestoreAgentRequest struct { // Required. The agent to restore. // // Types that are assignable to Agent: - // // *RestoreAgentRequest_AgentUri // *RestoreAgentRequest_AgentContent Agent isRestoreAgentRequest_Agent `protobuf_oneof:"agent"` @@ -1886,9 +1884,9 @@ type AgentsClient interface { // operation](https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: An empty [Struct - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) - // - `response`: [ExportAgentResponse][google.cloud.dialogflow.cx.v3beta1.ExportAgentResponse] + // - `metadata`: An empty [Struct + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) + // - `response`: [ExportAgentResponse][google.cloud.dialogflow.cx.v3beta1.ExportAgentResponse] ExportAgent(ctx context.Context, in *ExportAgentRequest, opts ...grpc.CallOption) (*longrunning.Operation, error) // Restores the specified agent from a binary file. // @@ -1899,10 +1897,10 @@ type AgentsClient interface { // operation](https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: An empty [Struct - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) - // - `response`: An [Empty - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) + // - `metadata`: An empty [Struct + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) + // - `response`: An [Empty + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) // // Note: You should always train a flow prior to sending it queries. See the // [training @@ -2032,9 +2030,9 @@ type AgentsServer interface { // operation](https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: An empty [Struct - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) - // - `response`: [ExportAgentResponse][google.cloud.dialogflow.cx.v3beta1.ExportAgentResponse] + // - `metadata`: An empty [Struct + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) + // - `response`: [ExportAgentResponse][google.cloud.dialogflow.cx.v3beta1.ExportAgentResponse] ExportAgent(context.Context, *ExportAgentRequest) (*longrunning.Operation, error) // Restores the specified agent from a binary file. // @@ -2045,10 +2043,10 @@ type AgentsServer interface { // operation](https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: An empty [Struct - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) - // - `response`: An [Empty - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) + // - `metadata`: An empty [Struct + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) + // - `response`: An [Empty + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) // // Note: You should always train a flow prior to sending it queries. See the // [training diff --git a/dialogflow/cx/apiv3beta1/cxpb/audio_config.pb.go b/dialogflow/cx/apiv3beta1/cxpb/audio_config.pb.go index ac39974fbdbe..b6095e55ee86 100644 --- a/dialogflow/cx/apiv3beta1/cxpb/audio_config.pb.go +++ b/dialogflow/cx/apiv3beta1/cxpb/audio_config.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dialogflow/cx/v3beta1/audio_config.proto package cxpb @@ -159,18 +159,18 @@ const ( SpeechModelVariant_USE_STANDARD SpeechModelVariant = 2 // Use an enhanced model variant: // - // - If an enhanced variant does not exist for the given - // [model][google.cloud.dialogflow.cx.v3beta1.InputAudioConfig.model] and request language, Dialogflow falls - // back to the standard variant. + // * If an enhanced variant does not exist for the given + // [model][google.cloud.dialogflow.cx.v3beta1.InputAudioConfig.model] and request language, Dialogflow falls + // back to the standard variant. // - // The [Cloud Speech - // documentation](https://cloud.google.com/speech-to-text/docs/enhanced-models) - // describes which models have enhanced variants. + // The [Cloud Speech + // documentation](https://cloud.google.com/speech-to-text/docs/enhanced-models) + // describes which models have enhanced variants. // - // - If the API caller isn't eligible for enhanced models, Dialogflow returns - // an error. Please see the [Dialogflow - // docs](https://cloud.google.com/dialogflow/docs/data-logging) - // for how to make your project eligible. + // * If the API caller isn't eligible for enhanced models, Dialogflow returns + // an error. Please see the [Dialogflow + // docs](https://cloud.google.com/dialogflow/docs/data-logging) + // for how to make your project eligible. SpeechModelVariant_USE_ENHANCED SpeechModelVariant = 3 ) diff --git a/dialogflow/cx/apiv3beta1/cxpb/changelog.pb.go b/dialogflow/cx/apiv3beta1/cxpb/changelog.pb.go index 98c10c52f6eb..661f0e0ace5b 100644 --- a/dialogflow/cx/apiv3beta1/cxpb/changelog.pb.go +++ b/dialogflow/cx/apiv3beta1/cxpb/changelog.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dialogflow/cx/v3beta1/changelog.proto package cxpb @@ -52,24 +52,24 @@ type ListChangelogsRequest struct { Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // The filter string. Supports filter by user_email, resource, type and // create_time. Some examples: - // 1. By user email: - // user_email = "someone@google.com" - // 2. By resource name: - // resource = "projects/123/locations/global/agents/456/flows/789" - // 3. By resource display name: - // display_name = "my agent" - // 4. By action: - // action = "Create" - // 5. By type: - // type = "flows" - // 6. By create time. Currently predicates on `create_time` and - // `create_time_epoch_seconds` are supported: - // create_time_epoch_seconds > 1551790877 AND create_time <= - // 2017-01-15T01:30:15.01Z - // 7. Combination of above filters: - // resource = "projects/123/locations/global/agents/456/flows/789" - // AND user_email = "someone@google.com" - // AND create_time <= 2017-01-15T01:30:15.01Z + // 1. By user email: + // user_email = "someone@google.com" + // 2. By resource name: + // resource = "projects/123/locations/global/agents/456/flows/789" + // 3. By resource display name: + // display_name = "my agent" + // 4. By action: + // action = "Create" + // 5. By type: + // type = "flows" + // 6. By create time. Currently predicates on `create_time` and + // `create_time_epoch_seconds` are supported: + // create_time_epoch_seconds > 1551790877 AND create_time <= + // 2017-01-15T01:30:15.01Z + // 7. Combination of above filters: + // resource = "projects/123/locations/global/agents/456/flows/789" + // AND user_email = "someone@google.com" + // AND create_time <= 2017-01-15T01:30:15.01Z Filter string `protobuf:"bytes,2,opt,name=filter,proto3" json:"filter,omitempty"` // The maximum number of items to return in a single page. By default 100 and // at most 1000. diff --git a/dialogflow/cx/apiv3beta1/cxpb/deployment.pb.go b/dialogflow/cx/apiv3beta1/cxpb/deployment.pb.go index acb38b3c28d3..74573ef129c8 100644 --- a/dialogflow/cx/apiv3beta1/cxpb/deployment.pb.go +++ b/dialogflow/cx/apiv3beta1/cxpb/deployment.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dialogflow/cx/v3beta1/deployment.proto package cxpb diff --git a/dialogflow/cx/apiv3beta1/cxpb/entity_type.pb.go b/dialogflow/cx/apiv3beta1/cxpb/entity_type.pb.go index 6691c34f217a..508c9a97829b 100644 --- a/dialogflow/cx/apiv3beta1/cxpb/entity_type.pb.go +++ b/dialogflow/cx/apiv3beta1/cxpb/entity_type.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dialogflow/cx/v3beta1/entity_type.proto package cxpb @@ -690,13 +690,13 @@ type DeleteEntityTypeRequest struct { // This field has no effect for entity type not being used. // For entity types that are used by intents or pages: // - // - If `force` is set to false, an error will be returned with message - // indicating the referencing resources. - // - If `force` is set to true, Dialogflow will remove the entity type, as - // well as any references to the entity type (i.e. Page - // [parameter][google.cloud.dialogflow.cx.v3beta1.Form.Parameter] of the entity type will be changed to - // '@sys.any' and intent [parameter][google.cloud.dialogflow.cx.v3beta1.Intent.Parameter] of the entity type - // will be removed). + // * If `force` is set to false, an error will be returned with message + // indicating the referencing resources. + // * If `force` is set to true, Dialogflow will remove the entity type, as + // well as any references to the entity type (i.e. Page + // [parameter][google.cloud.dialogflow.cx.v3beta1.Form.Parameter] of the entity type will be changed to + // '@sys.any' and intent [parameter][google.cloud.dialogflow.cx.v3beta1.Intent.Parameter] of the entity type + // will be removed). Force bool `protobuf:"varint,2,opt,name=force,proto3" json:"force,omitempty"` } @@ -762,7 +762,7 @@ type EntityType_Entity struct { // // For `KIND_LIST` entity types: // - // - A string that can contain references to other entity types (with or + // * A string that can contain references to other entity types (with or // without aliases). Value string `protobuf:"bytes,1,opt,name=value,proto3" json:"value,omitempty"` // Required. A collection of value synonyms. For example, if the entity type diff --git a/dialogflow/cx/apiv3beta1/cxpb/environment.pb.go b/dialogflow/cx/apiv3beta1/cxpb/environment.pb.go index 8cd15789b86d..b5a519d822ea 100644 --- a/dialogflow/cx/apiv3beta1/cxpb/environment.pb.go +++ b/dialogflow/cx/apiv3beta1/cxpb/environment.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dialogflow/cx/v3beta1/environment.proto package cxpb @@ -2228,9 +2228,9 @@ type EnvironmentsClient interface { // operation](https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: An empty [Struct - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) - // - `response`: [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] + // - `metadata`: An empty [Struct + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) + // - `response`: [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] CreateEnvironment(ctx context.Context, in *CreateEnvironmentRequest, opts ...grpc.CallOption) (*longrunning.Operation, error) // Updates the specified [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. // @@ -2238,9 +2238,9 @@ type EnvironmentsClient interface { // operation](https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: An empty [Struct - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) - // - `response`: [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] + // - `metadata`: An empty [Struct + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) + // - `response`: [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] UpdateEnvironment(ctx context.Context, in *UpdateEnvironmentRequest, opts ...grpc.CallOption) (*longrunning.Operation, error) // Deletes the specified [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. DeleteEnvironment(ctx context.Context, in *DeleteEnvironmentRequest, opts ...grpc.CallOption) (*emptypb.Empty, error) @@ -2369,9 +2369,9 @@ type EnvironmentsServer interface { // operation](https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: An empty [Struct - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) - // - `response`: [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] + // - `metadata`: An empty [Struct + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) + // - `response`: [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] CreateEnvironment(context.Context, *CreateEnvironmentRequest) (*longrunning.Operation, error) // Updates the specified [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. // @@ -2379,9 +2379,9 @@ type EnvironmentsServer interface { // operation](https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: An empty [Struct - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) - // - `response`: [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] + // - `metadata`: An empty [Struct + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) + // - `response`: [Environment][google.cloud.dialogflow.cx.v3beta1.Environment] UpdateEnvironment(context.Context, *UpdateEnvironmentRequest) (*longrunning.Operation, error) // Deletes the specified [Environment][google.cloud.dialogflow.cx.v3beta1.Environment]. DeleteEnvironment(context.Context, *DeleteEnvironmentRequest) (*emptypb.Empty, error) diff --git a/dialogflow/cx/apiv3beta1/cxpb/experiment.pb.go b/dialogflow/cx/apiv3beta1/cxpb/experiment.pb.go index 1b5b029b1c5f..7d52449a5cbe 100644 --- a/dialogflow/cx/apiv3beta1/cxpb/experiment.pb.go +++ b/dialogflow/cx/apiv3beta1/cxpb/experiment.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dialogflow/cx/v3beta1/experiment.proto package cxpb @@ -617,7 +617,6 @@ type VariantsHistory struct { // experiment. // // Types that are assignable to Variants: - // // *VariantsHistory_VersionVariants Variants isVariantsHistory_Variants `protobuf_oneof:"variants"` // Update time of the variants. @@ -1157,7 +1156,6 @@ type Experiment_Definition struct { // experiment. // // Types that are assignable to Variants: - // // *Experiment_Definition_VersionVariants Variants isExperiment_Definition_Variants `protobuf_oneof:"variants"` } @@ -1380,7 +1378,6 @@ type Experiment_Result_Metric struct { // The actual value of the metric. // // Types that are assignable to Value: - // // *Experiment_Result_Metric_Ratio // *Experiment_Result_Metric_Count Value isExperiment_Result_Metric_Value `protobuf_oneof:"value"` diff --git a/dialogflow/cx/apiv3beta1/cxpb/flow.pb.go b/dialogflow/cx/apiv3beta1/cxpb/flow.pb.go index 113987ef52f1..e51debad23eb 100644 --- a/dialogflow/cx/apiv3beta1/cxpb/flow.pb.go +++ b/dialogflow/cx/apiv3beta1/cxpb/flow.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dialogflow/cx/v3beta1/flow.proto package cxpb @@ -527,13 +527,13 @@ type DeleteFlowRequest struct { // This field has no effect for flows with no incoming transitions. // For flows with incoming transitions: // - // - If `force` is set to false, an error will be returned with message - // indicating the incoming transitions. - // - If `force` is set to true, Dialogflow will remove the flow, as well as - // any transitions to the flow (i.e. [Target - // flow][EventHandler.target_flow] in event handlers or [Target - // flow][TransitionRoute.target_flow] in transition routes that point to - // this flow will be cleared). + // * If `force` is set to false, an error will be returned with message + // indicating the incoming transitions. + // * If `force` is set to true, Dialogflow will remove the flow, as well as + // any transitions to the flow (i.e. [Target + // flow][EventHandler.target_flow] in event handlers or [Target + // flow][TransitionRoute.target_flow] in transition routes that point to + // this flow will be cleared). Force bool `protobuf:"varint,2,opt,name=force,proto3" json:"force,omitempty"` } @@ -1136,7 +1136,6 @@ type ImportFlowRequest struct { // Required. The flow to import. // // Types that are assignable to Flow: - // // *ImportFlowRequest_FlowUri // *ImportFlowRequest_FlowContent Flow isImportFlowRequest_Flow `protobuf_oneof:"flow"` @@ -1375,7 +1374,6 @@ type ExportFlowResponse struct { // The exported flow. // // Types that are assignable to Flow: - // // *ExportFlowResponse_FlowUri // *ExportFlowResponse_FlowContent Flow isExportFlowResponse_Flow `protobuf_oneof:"flow"` @@ -2197,10 +2195,10 @@ type FlowsClient interface { // operation](https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: An empty [Struct - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) - // - `response`: An [Empty - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) + // - `metadata`: An empty [Struct + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) + // - `response`: An [Empty + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) // // Note: You should always train a flow prior to sending it queries. See the // [training @@ -2219,9 +2217,9 @@ type FlowsClient interface { // operation](https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: An empty [Struct - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) - // - `response`: [ImportFlowResponse][google.cloud.dialogflow.cx.v3beta1.ImportFlowResponse] + // - `metadata`: An empty [Struct + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) + // - `response`: [ImportFlowResponse][google.cloud.dialogflow.cx.v3beta1.ImportFlowResponse] // // Note: You should always train a flow prior to sending it queries. See the // [training @@ -2233,9 +2231,9 @@ type FlowsClient interface { // operation](https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: An empty [Struct - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) - // - `response`: [ExportFlowResponse][google.cloud.dialogflow.cx.v3beta1.ExportFlowResponse] + // - `metadata`: An empty [Struct + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) + // - `response`: [ExportFlowResponse][google.cloud.dialogflow.cx.v3beta1.ExportFlowResponse] // // Note that resources (e.g. intents, entities, webhooks) that the flow // references will also be exported. @@ -2367,10 +2365,10 @@ type FlowsServer interface { // operation](https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: An empty [Struct - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) - // - `response`: An [Empty - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) + // - `metadata`: An empty [Struct + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) + // - `response`: An [Empty + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) // // Note: You should always train a flow prior to sending it queries. See the // [training @@ -2389,9 +2387,9 @@ type FlowsServer interface { // operation](https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: An empty [Struct - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) - // - `response`: [ImportFlowResponse][google.cloud.dialogflow.cx.v3beta1.ImportFlowResponse] + // - `metadata`: An empty [Struct + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) + // - `response`: [ImportFlowResponse][google.cloud.dialogflow.cx.v3beta1.ImportFlowResponse] // // Note: You should always train a flow prior to sending it queries. See the // [training @@ -2403,9 +2401,9 @@ type FlowsServer interface { // operation](https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: An empty [Struct - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) - // - `response`: [ExportFlowResponse][google.cloud.dialogflow.cx.v3beta1.ExportFlowResponse] + // - `metadata`: An empty [Struct + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) + // - `response`: [ExportFlowResponse][google.cloud.dialogflow.cx.v3beta1.ExportFlowResponse] // // Note that resources (e.g. intents, entities, webhooks) that the flow // references will also be exported. diff --git a/dialogflow/cx/apiv3beta1/cxpb/fulfillment.pb.go b/dialogflow/cx/apiv3beta1/cxpb/fulfillment.pb.go index f02aff30bf1e..3ac2bccdeba3 100644 --- a/dialogflow/cx/apiv3beta1/cxpb/fulfillment.pb.go +++ b/dialogflow/cx/apiv3beta1/cxpb/fulfillment.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dialogflow/cx/v3beta1/fulfillment.proto package cxpb @@ -338,7 +338,6 @@ type Fulfillment_ConditionalCases_Case_CaseContent struct { // Either a message is returned or additional cases to be evaluated. // // Types that are assignable to CasesOrMessage: - // // *Fulfillment_ConditionalCases_Case_CaseContent_Message // *Fulfillment_ConditionalCases_Case_CaseContent_AdditionalCases CasesOrMessage isFulfillment_ConditionalCases_Case_CaseContent_CasesOrMessage `protobuf_oneof:"cases_or_message"` diff --git a/dialogflow/cx/apiv3beta1/cxpb/intent.pb.go b/dialogflow/cx/apiv3beta1/cxpb/intent.pb.go index 29e9f22371b0..c0337ed53874 100644 --- a/dialogflow/cx/apiv3beta1/cxpb/intent.pb.go +++ b/dialogflow/cx/apiv3beta1/cxpb/intent.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dialogflow/cx/v3beta1/intent.proto package cxpb @@ -123,11 +123,11 @@ type Intent struct { // The priority of this intent. Higher numbers represent higher // priorities. // - // - If the supplied value is unspecified or 0, the service - // translates the value to 500,000, which corresponds to the - // `Normal` priority in the console. - // - If the supplied value is negative, the intent is ignored - // in runtime detect intent requests. + // - If the supplied value is unspecified or 0, the service + // translates the value to 500,000, which corresponds to the + // `Normal` priority in the console. + // - If the supplied value is negative, the intent is ignored + // in runtime detect intent requests. Priority int32 `protobuf:"varint,5,opt,name=priority,proto3" json:"priority,omitempty"` // Indicates whether this is a fallback intent. Currently only default // fallback intent is allowed in the agent, which is added upon agent @@ -693,8 +693,8 @@ type Intent_TrainingPhrase struct { // If you want to annotate the training phrase, you must create multiple // parts, where the fields of each part are populated in one of two ways: // - // - `Part.text` is set to a part of the phrase that has no parameters. - // - `Part.text` is set to a part of the phrase that you want to annotate, + // - `Part.text` is set to a part of the phrase that has no parameters. + // - `Part.text` is set to a part of the phrase that you want to annotate, // and the `parameter_id` field is set. Parts []*Intent_TrainingPhrase_Part `protobuf:"bytes,2,rep,name=parts,proto3" json:"parts,omitempty"` // Indicates how many times this example was added to the intent. diff --git a/dialogflow/cx/apiv3beta1/cxpb/page.pb.go b/dialogflow/cx/apiv3beta1/cxpb/page.pb.go index 861dd994aa0d..b401b77876f0 100644 --- a/dialogflow/cx/apiv3beta1/cxpb/page.pb.go +++ b/dialogflow/cx/apiv3beta1/cxpb/page.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dialogflow/cx/v3beta1/page.proto package cxpb @@ -80,11 +80,11 @@ type Page struct { // Ordered list of [`TransitionRouteGroups`][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup] associated // with the page. Transition route groups must be unique within a page. // - // - If multiple transition routes within a page scope refer to the same + // * If multiple transition routes within a page scope refer to the same // intent, then the precedence order is: page's transition route -> page's // transition route group -> flow's transition routes. // - // - If multiple transition route groups within a page contain the same + // * If multiple transition route groups within a page contain the same // intent, then the first group in the ordered list takes precedence. // // Format:`projects//locations//agents/ [OR name = ] ... + // name = [OR name = ] ... // // For example: // - // - "name = t1 OR name = t2" matches the test case with the exact resource + // * "name = t1 OR name = t2" matches the test case with the exact resource // name "t1" or "t2". Filter string `protobuf:"bytes,4,opt,name=filter,proto3" json:"filter,omitempty"` } @@ -2230,7 +2227,6 @@ type ExportTestCasesResponse struct { // The exported test cases. // // Types that are assignable to Destination: - // // *ExportTestCasesResponse_GcsUri // *ExportTestCasesResponse_Content Destination isExportTestCasesResponse_Destination `protobuf_oneof:"destination"` @@ -2372,8 +2368,8 @@ type ListTestCaseResultsRequest struct { // The expression is case insensitive. Only 'AND' is supported for logical // operators. The supported syntax is listed below in detail: // - // [AND ] ... - // [AND latest] + // [AND ] ... + // [AND latest] // // The supported fields and operators are: // field operator @@ -2384,11 +2380,11 @@ type ListTestCaseResultsRequest struct { // case. // // Examples: - // - "environment=draft AND latest" matches the latest test result for each + // * "environment=draft AND latest" matches the latest test result for each // test case in the draft environment. - // - "environment IN (e1,e2)" matches any test case results with an + // * "environment IN (e1,e2)" matches any test case results with an // environment resource name of either "e1" or "e2". - // - "test_time > 1602540713" matches any test case results with test time + // * "test_time > 1602540713" matches any test case results with test time // later than a unix timestamp in seconds 1602540713. Filter string `protobuf:"bytes,4,opt,name=filter,proto3" json:"filter,omitempty"` } @@ -2762,7 +2758,6 @@ type TransitionCoverage_TransitionNode struct { // A TransitionNode can be either a page or a flow. // // Types that are assignable to Kind: - // // *TransitionCoverage_TransitionNode_Page // *TransitionCoverage_TransitionNode_Flow Kind isTransitionCoverage_TransitionNode_Kind `protobuf_oneof:"kind"` @@ -2859,7 +2854,6 @@ type TransitionCoverage_Transition struct { // The detailed transition. // // Types that are assignable to Detail: - // // *TransitionCoverage_Transition_TransitionRoute // *TransitionCoverage_Transition_EventHandler Detail isTransitionCoverage_Transition_Detail `protobuf_oneof:"detail"` diff --git a/dialogflow/cx/apiv3beta1/cxpb/transition_route_group.pb.go b/dialogflow/cx/apiv3beta1/cxpb/transition_route_group.pb.go index 440c412eb6ee..e404f93b4597 100644 --- a/dialogflow/cx/apiv3beta1/cxpb/transition_route_group.pb.go +++ b/dialogflow/cx/apiv3beta1/cxpb/transition_route_group.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dialogflow/cx/v3beta1/transition_route_group.proto package cxpb @@ -507,10 +507,10 @@ type DeleteTransitionRouteGroupRequest struct { // This field has no effect for transition route group that no page is using. // If the transition route group is referenced by any page: // - // - If `force` is set to false, an error will be returned with message - // indicating pages that reference the transition route group. - // - If `force` is set to true, Dialogflow will remove the transition route - // group, as well as any reference to it. + // * If `force` is set to false, an error will be returned with message + // indicating pages that reference the transition route group. + // * If `force` is set to true, Dialogflow will remove the transition route + // group, as well as any reference to it. Force bool `protobuf:"varint,2,opt,name=force,proto3" json:"force,omitempty"` } diff --git a/dialogflow/cx/apiv3beta1/cxpb/validation_message.pb.go b/dialogflow/cx/apiv3beta1/cxpb/validation_message.pb.go index 3be01430bea3..a0700c5d004e 100644 --- a/dialogflow/cx/apiv3beta1/cxpb/validation_message.pb.go +++ b/dialogflow/cx/apiv3beta1/cxpb/validation_message.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dialogflow/cx/v3beta1/validation_message.proto package cxpb diff --git a/dialogflow/cx/apiv3beta1/cxpb/version.pb.go b/dialogflow/cx/apiv3beta1/cxpb/version.pb.go index 720bf5b74bef..22cb88965b89 100644 --- a/dialogflow/cx/apiv3beta1/cxpb/version.pb.go +++ b/dialogflow/cx/apiv3beta1/cxpb/version.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dialogflow/cx/v3beta1/version.proto package cxpb @@ -1350,10 +1350,10 @@ type VersionsClient interface { // operation](https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: An empty [Struct - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) - // - `response`: An [Empty - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) + // - `metadata`: An empty [Struct + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) + // - `response`: An [Empty + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) LoadVersion(ctx context.Context, in *LoadVersionRequest, opts ...grpc.CallOption) (*longrunning.Operation, error) // Compares the specified base version with target version. CompareVersions(ctx context.Context, in *CompareVersionsRequest, opts ...grpc.CallOption) (*CompareVersionsResponse, error) @@ -1455,10 +1455,10 @@ type VersionsServer interface { // operation](https://cloud.google.com/dialogflow/cx/docs/how/long-running-operation). // The returned `Operation` type has the following method-specific fields: // - // - `metadata`: An empty [Struct - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) - // - `response`: An [Empty - // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) + // - `metadata`: An empty [Struct + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) + // - `response`: An [Empty + // message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) LoadVersion(context.Context, *LoadVersionRequest) (*longrunning.Operation, error) // Compares the specified base version with target version. CompareVersions(context.Context, *CompareVersionsRequest) (*CompareVersionsResponse, error) diff --git a/dialogflow/cx/apiv3beta1/cxpb/webhook.pb.go b/dialogflow/cx/apiv3beta1/cxpb/webhook.pb.go index 089e037c624a..521d122f0d5c 100644 --- a/dialogflow/cx/apiv3beta1/cxpb/webhook.pb.go +++ b/dialogflow/cx/apiv3beta1/cxpb/webhook.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/dialogflow/cx/v3beta1/webhook.proto package cxpb @@ -178,7 +178,6 @@ type Webhook struct { // Required. The webhook configuration. // // Types that are assignable to Webhook: - // // *Webhook_GenericWebService_ // *Webhook_ServiceDirectory Webhook isWebhook_Webhook `protobuf_oneof:"webhook"` @@ -601,12 +600,12 @@ type DeleteWebhookRequest struct { // This field has no effect for webhook not being used. // For webhooks that are used by pages/flows/transition route groups: // - // - If `force` is set to false, an error will be returned with message - // indicating the referenced resources. - // - If `force` is set to true, Dialogflow will remove the webhook, as well - // as any references to the webhook (i.e. [Webhook][google.cloud.dialogflow.cx.v3beta1.Fulfillment.webhook] - // and [tag][google.cloud.dialogflow.cx.v3beta1.Fulfillment.tag]in fulfillments that point to this webhook - // will be removed). + // * If `force` is set to false, an error will be returned with message + // indicating the referenced resources. + // * If `force` is set to true, Dialogflow will remove the webhook, as well + // as any references to the webhook (i.e. [Webhook][google.cloud.dialogflow.cx.v3beta1.Fulfillment.webhook] + // and [tag][google.cloud.dialogflow.cx.v3beta1.Fulfillment.tag]in fulfillments that point to this webhook + // will be removed). Force bool `protobuf:"varint,2,opt,name=force,proto3" json:"force,omitempty"` } @@ -672,7 +671,6 @@ type WebhookRequest struct { // The original conversational query. // // Types that are assignable to Query: - // // *WebhookRequest_Text // *WebhookRequest_TriggerIntent // *WebhookRequest_Transcript @@ -891,7 +889,6 @@ type WebhookResponse struct { // different flow in the same agent. // // Types that are assignable to Transition: - // // *WebhookResponse_TargetPage // *WebhookResponse_TargetFlow Transition isWebhookResponse_Transition `protobuf_oneof:"transition"` @@ -1168,12 +1165,10 @@ type Webhook_GenericWebService struct { // name". For instance a certificate can be self-signed using the following // command, // ``` - // - // openssl x509 -req -days 200 -in example.com.csr \ - // -signkey example.com.key \ - // -out example.com.crt \ - // -extfile <(printf "\nsubjectAltName='DNS:www.example.com'") - // + // openssl x509 -req -days 200 -in example.com.csr \ + // -signkey example.com.key \ + // -out example.com.crt \ + // -extfile <(printf "\nsubjectAltName='DNS:www.example.com'") // ``` AllowedCaCerts [][]byte `protobuf:"bytes,5,rep,name=allowed_ca_certs,json=allowedCaCerts,proto3" json:"allowed_ca_certs,omitempty"` } diff --git a/dialogflow/cx/apiv3beta1/deployments_client.go b/dialogflow/cx/apiv3beta1/deployments_client.go index a50382921b7f..8a8fe1e3c949 100644 --- a/dialogflow/cx/apiv3beta1/deployments_client.go +++ b/dialogflow/cx/apiv3beta1/deployments_client.go @@ -594,6 +594,7 @@ func (c *deploymentsRESTClient) ListDeployments(ctx context.Context, req *cxpb.L baseUrl.Path += fmt.Sprintf("/v3beta1/%v/deployments", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -667,6 +668,11 @@ func (c *deploymentsRESTClient) GetDeployment(ctx context.Context, req *cxpb.Get } baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -720,6 +726,11 @@ func (c *deploymentsRESTClient) GetLocation(ctx context.Context, req *locationpb } baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -787,6 +798,7 @@ func (c *deploymentsRESTClient) ListLocations(ctx context.Context, req *location baseUrl.Path += fmt.Sprintf("/v3beta1/%v/locations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -863,6 +875,11 @@ func (c *deploymentsRESTClient) CancelOperation(ctx context.Context, req *longru } baseUrl.Path += fmt.Sprintf("/v3beta1/%v:cancel", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -898,6 +915,11 @@ func (c *deploymentsRESTClient) GetOperation(ctx context.Context, req *longrunni } baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -965,6 +987,7 @@ func (c *deploymentsRESTClient) ListOperations(ctx context.Context, req *longrun baseUrl.Path += fmt.Sprintf("/v3beta1/%v/operations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/dialogflow/cx/apiv3beta1/entity_types_client.go b/dialogflow/cx/apiv3beta1/entity_types_client.go index 5eb46e69b69b..c3de89451ff7 100644 --- a/dialogflow/cx/apiv3beta1/entity_types_client.go +++ b/dialogflow/cx/apiv3beta1/entity_types_client.go @@ -749,6 +749,7 @@ func (c *entityTypesRESTClient) ListEntityTypes(ctx context.Context, req *cxpb.L baseUrl.Path += fmt.Sprintf("/v3beta1/%v/entityTypes", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetLanguageCode() != "" { params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) } @@ -826,6 +827,7 @@ func (c *entityTypesRESTClient) GetEntityType(ctx context.Context, req *cxpb.Get baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetLanguageCode() != "" { params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) } @@ -893,6 +895,7 @@ func (c *entityTypesRESTClient) CreateEntityType(ctx context.Context, req *cxpb. baseUrl.Path += fmt.Sprintf("/v3beta1/%v/entityTypes", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetLanguageCode() != "" { params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) } @@ -964,6 +967,7 @@ func (c *entityTypesRESTClient) UpdateEntityType(ctx context.Context, req *cxpb. baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetEntityType().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetLanguageCode() != "" { params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) } @@ -1035,6 +1039,7 @@ func (c *entityTypesRESTClient) DeleteEntityType(ctx context.Context, req *cxpb. baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetForce() { params.Add("force", fmt.Sprintf("%v", req.GetForce())) } @@ -1076,6 +1081,11 @@ func (c *entityTypesRESTClient) GetLocation(ctx context.Context, req *locationpb } baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1143,6 +1153,7 @@ func (c *entityTypesRESTClient) ListLocations(ctx context.Context, req *location baseUrl.Path += fmt.Sprintf("/v3beta1/%v/locations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1219,6 +1230,11 @@ func (c *entityTypesRESTClient) CancelOperation(ctx context.Context, req *longru } baseUrl.Path += fmt.Sprintf("/v3beta1/%v:cancel", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1254,6 +1270,11 @@ func (c *entityTypesRESTClient) GetOperation(ctx context.Context, req *longrunni } baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1321,6 +1342,7 @@ func (c *entityTypesRESTClient) ListOperations(ctx context.Context, req *longrun baseUrl.Path += fmt.Sprintf("/v3beta1/%v/operations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/dialogflow/cx/apiv3beta1/environments_client.go b/dialogflow/cx/apiv3beta1/environments_client.go index 127f52493448..c8835f2b4c18 100644 --- a/dialogflow/cx/apiv3beta1/environments_client.go +++ b/dialogflow/cx/apiv3beta1/environments_client.go @@ -1096,6 +1096,7 @@ func (c *environmentsRESTClient) ListEnvironments(ctx context.Context, req *cxpb baseUrl.Path += fmt.Sprintf("/v3beta1/%v/environments", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -1169,6 +1170,11 @@ func (c *environmentsRESTClient) GetEnvironment(ctx context.Context, req *cxpb.G } baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1238,6 +1244,11 @@ func (c *environmentsRESTClient) CreateEnvironment(ctx context.Context, req *cxp } baseUrl.Path += fmt.Sprintf("/v3beta1/%v/environments", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1312,6 +1323,7 @@ func (c *environmentsRESTClient) UpdateEnvironment(ctx context.Context, req *cxp baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetEnvironment().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -1379,6 +1391,11 @@ func (c *environmentsRESTClient) DeleteEnvironment(ctx context.Context, req *cxp } baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1428,6 +1445,7 @@ func (c *environmentsRESTClient) LookupEnvironmentHistory(ctx context.Context, r baseUrl.Path += fmt.Sprintf("/v3beta1/%v:lookupEnvironmentHistory", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -1515,6 +1533,11 @@ func (c *environmentsRESTClient) RunContinuousTest(ctx context.Context, req *cxp } baseUrl.Path += fmt.Sprintf("/v3beta1/%v:runContinuousTest", req.GetEnvironment()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "environment", url.QueryEscape(req.GetEnvironment()))) @@ -1586,6 +1609,7 @@ func (c *environmentsRESTClient) ListContinuousTestResults(ctx context.Context, baseUrl.Path += fmt.Sprintf("/v3beta1/%v/continuousTestResults", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -1673,6 +1697,11 @@ func (c *environmentsRESTClient) DeployFlow(ctx context.Context, req *cxpb.Deplo } baseUrl.Path += fmt.Sprintf("/v3beta1/%v:deployFlow", req.GetEnvironment()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "environment", url.QueryEscape(req.GetEnvironment()))) @@ -1730,6 +1759,11 @@ func (c *environmentsRESTClient) GetLocation(ctx context.Context, req *locationp } baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1797,6 +1831,7 @@ func (c *environmentsRESTClient) ListLocations(ctx context.Context, req *locatio baseUrl.Path += fmt.Sprintf("/v3beta1/%v/locations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1873,6 +1908,11 @@ func (c *environmentsRESTClient) CancelOperation(ctx context.Context, req *longr } baseUrl.Path += fmt.Sprintf("/v3beta1/%v:cancel", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1908,6 +1948,11 @@ func (c *environmentsRESTClient) GetOperation(ctx context.Context, req *longrunn } baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1975,6 +2020,7 @@ func (c *environmentsRESTClient) ListOperations(ctx context.Context, req *longru baseUrl.Path += fmt.Sprintf("/v3beta1/%v/operations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/dialogflow/cx/apiv3beta1/experiments_client.go b/dialogflow/cx/apiv3beta1/experiments_client.go index f921b2b92701..c5ef9f63206c 100644 --- a/dialogflow/cx/apiv3beta1/experiments_client.go +++ b/dialogflow/cx/apiv3beta1/experiments_client.go @@ -843,6 +843,7 @@ func (c *experimentsRESTClient) ListExperiments(ctx context.Context, req *cxpb.L baseUrl.Path += fmt.Sprintf("/v3beta1/%v/experiments", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -916,6 +917,11 @@ func (c *experimentsRESTClient) GetExperiment(ctx context.Context, req *cxpb.Get } baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -976,6 +982,11 @@ func (c *experimentsRESTClient) CreateExperiment(ctx context.Context, req *cxpb. } baseUrl.Path += fmt.Sprintf("/v3beta1/%v/experiments", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1037,6 +1048,7 @@ func (c *experimentsRESTClient) UpdateExperiment(ctx context.Context, req *cxpb. baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetExperiment().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -1100,6 +1112,11 @@ func (c *experimentsRESTClient) DeleteExperiment(ctx context.Context, req *cxpb. } baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1142,6 +1159,11 @@ func (c *experimentsRESTClient) StartExperiment(ctx context.Context, req *cxpb.S } baseUrl.Path += fmt.Sprintf("/v3beta1/%v:start", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1202,6 +1224,11 @@ func (c *experimentsRESTClient) StopExperiment(ctx context.Context, req *cxpb.St } baseUrl.Path += fmt.Sprintf("/v3beta1/%v:stop", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1255,6 +1282,11 @@ func (c *experimentsRESTClient) GetLocation(ctx context.Context, req *locationpb } baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1322,6 +1354,7 @@ func (c *experimentsRESTClient) ListLocations(ctx context.Context, req *location baseUrl.Path += fmt.Sprintf("/v3beta1/%v/locations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1398,6 +1431,11 @@ func (c *experimentsRESTClient) CancelOperation(ctx context.Context, req *longru } baseUrl.Path += fmt.Sprintf("/v3beta1/%v:cancel", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1433,6 +1471,11 @@ func (c *experimentsRESTClient) GetOperation(ctx context.Context, req *longrunni } baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1500,6 +1543,7 @@ func (c *experimentsRESTClient) ListOperations(ctx context.Context, req *longrun baseUrl.Path += fmt.Sprintf("/v3beta1/%v/operations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/dialogflow/cx/apiv3beta1/flows_client.go b/dialogflow/cx/apiv3beta1/flows_client.go index ce3a3c54cf7f..534290af33e1 100644 --- a/dialogflow/cx/apiv3beta1/flows_client.go +++ b/dialogflow/cx/apiv3beta1/flows_client.go @@ -1106,6 +1106,7 @@ func (c *flowsRESTClient) CreateFlow(ctx context.Context, req *cxpb.CreateFlowRe baseUrl.Path += fmt.Sprintf("/v3beta1/%v/flows", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetLanguageCode() != "" { params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) } @@ -1166,6 +1167,7 @@ func (c *flowsRESTClient) DeleteFlow(ctx context.Context, req *cxpb.DeleteFlowRe baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetForce() { params.Add("force", fmt.Sprintf("%v", req.GetForce())) } @@ -1221,6 +1223,7 @@ func (c *flowsRESTClient) ListFlows(ctx context.Context, req *cxpb.ListFlowsRequ baseUrl.Path += fmt.Sprintf("/v3beta1/%v/flows", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetLanguageCode() != "" { params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) } @@ -1298,6 +1301,7 @@ func (c *flowsRESTClient) GetFlow(ctx context.Context, req *cxpb.GetFlowRequest, baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetLanguageCode() != "" { params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) } @@ -1369,6 +1373,7 @@ func (c *flowsRESTClient) UpdateFlow(ctx context.Context, req *cxpb.UpdateFlowRe baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetFlow().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetLanguageCode() != "" { params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) } @@ -1456,6 +1461,11 @@ func (c *flowsRESTClient) TrainFlow(ctx context.Context, req *cxpb.TrainFlowRequ } baseUrl.Path += fmt.Sprintf("/v3beta1/%v:train", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1521,6 +1531,11 @@ func (c *flowsRESTClient) ValidateFlow(ctx context.Context, req *cxpb.ValidateFl } baseUrl.Path += fmt.Sprintf("/v3beta1/%v:validate", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1576,6 +1591,7 @@ func (c *flowsRESTClient) GetFlowValidationResult(ctx context.Context, req *cxpb baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetLanguageCode() != "" { params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) } @@ -1654,6 +1670,11 @@ func (c *flowsRESTClient) ImportFlow(ctx context.Context, req *cxpb.ImportFlowRe } baseUrl.Path += fmt.Sprintf("/v3beta1/%v/flows:import", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1729,6 +1750,11 @@ func (c *flowsRESTClient) ExportFlow(ctx context.Context, req *cxpb.ExportFlowRe } baseUrl.Path += fmt.Sprintf("/v3beta1/%v:export", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1786,6 +1812,11 @@ func (c *flowsRESTClient) GetLocation(ctx context.Context, req *locationpb.GetLo } baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1853,6 +1884,7 @@ func (c *flowsRESTClient) ListLocations(ctx context.Context, req *locationpb.Lis baseUrl.Path += fmt.Sprintf("/v3beta1/%v/locations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1929,6 +1961,11 @@ func (c *flowsRESTClient) CancelOperation(ctx context.Context, req *longrunningp } baseUrl.Path += fmt.Sprintf("/v3beta1/%v:cancel", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1964,6 +2001,11 @@ func (c *flowsRESTClient) GetOperation(ctx context.Context, req *longrunningpb.G } baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2031,6 +2073,7 @@ func (c *flowsRESTClient) ListOperations(ctx context.Context, req *longrunningpb baseUrl.Path += fmt.Sprintf("/v3beta1/%v/operations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/dialogflow/cx/apiv3beta1/intents_client.go b/dialogflow/cx/apiv3beta1/intents_client.go index 9ea719e9577f..69f29b41bee4 100644 --- a/dialogflow/cx/apiv3beta1/intents_client.go +++ b/dialogflow/cx/apiv3beta1/intents_client.go @@ -753,6 +753,7 @@ func (c *intentsRESTClient) ListIntents(ctx context.Context, req *cxpb.ListInten baseUrl.Path += fmt.Sprintf("/v3beta1/%v/intents", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetIntentView() != 0 { params.Add("intentView", fmt.Sprintf("%v", req.GetIntentView())) } @@ -833,6 +834,7 @@ func (c *intentsRESTClient) GetIntent(ctx context.Context, req *cxpb.GetIntentRe baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetLanguageCode() != "" { params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) } @@ -904,6 +906,7 @@ func (c *intentsRESTClient) CreateIntent(ctx context.Context, req *cxpb.CreateIn baseUrl.Path += fmt.Sprintf("/v3beta1/%v/intents", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetLanguageCode() != "" { params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) } @@ -975,6 +978,7 @@ func (c *intentsRESTClient) UpdateIntent(ctx context.Context, req *cxpb.UpdateIn baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetIntent().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetLanguageCode() != "" { params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) } @@ -1045,6 +1049,11 @@ func (c *intentsRESTClient) DeleteIntent(ctx context.Context, req *cxpb.DeleteIn } baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1080,6 +1089,11 @@ func (c *intentsRESTClient) GetLocation(ctx context.Context, req *locationpb.Get } baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1147,6 +1161,7 @@ func (c *intentsRESTClient) ListLocations(ctx context.Context, req *locationpb.L baseUrl.Path += fmt.Sprintf("/v3beta1/%v/locations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1223,6 +1238,11 @@ func (c *intentsRESTClient) CancelOperation(ctx context.Context, req *longrunnin } baseUrl.Path += fmt.Sprintf("/v3beta1/%v:cancel", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1258,6 +1278,11 @@ func (c *intentsRESTClient) GetOperation(ctx context.Context, req *longrunningpb } baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1325,6 +1350,7 @@ func (c *intentsRESTClient) ListOperations(ctx context.Context, req *longrunning baseUrl.Path += fmt.Sprintf("/v3beta1/%v/operations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/dialogflow/cx/apiv3beta1/pages_client.go b/dialogflow/cx/apiv3beta1/pages_client.go index 347146cba32c..fff99a620103 100644 --- a/dialogflow/cx/apiv3beta1/pages_client.go +++ b/dialogflow/cx/apiv3beta1/pages_client.go @@ -741,6 +741,7 @@ func (c *pagesRESTClient) ListPages(ctx context.Context, req *cxpb.ListPagesRequ baseUrl.Path += fmt.Sprintf("/v3beta1/%v/pages", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetLanguageCode() != "" { params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) } @@ -818,6 +819,7 @@ func (c *pagesRESTClient) GetPage(ctx context.Context, req *cxpb.GetPageRequest, baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetLanguageCode() != "" { params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) } @@ -885,6 +887,7 @@ func (c *pagesRESTClient) CreatePage(ctx context.Context, req *cxpb.CreatePageRe baseUrl.Path += fmt.Sprintf("/v3beta1/%v/pages", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetLanguageCode() != "" { params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) } @@ -952,6 +955,7 @@ func (c *pagesRESTClient) UpdatePage(ctx context.Context, req *cxpb.UpdatePageRe baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetPage().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetLanguageCode() != "" { params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) } @@ -1019,6 +1023,7 @@ func (c *pagesRESTClient) DeletePage(ctx context.Context, req *cxpb.DeletePageRe baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetForce() { params.Add("force", fmt.Sprintf("%v", req.GetForce())) } @@ -1060,6 +1065,11 @@ func (c *pagesRESTClient) GetLocation(ctx context.Context, req *locationpb.GetLo } baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1127,6 +1137,7 @@ func (c *pagesRESTClient) ListLocations(ctx context.Context, req *locationpb.Lis baseUrl.Path += fmt.Sprintf("/v3beta1/%v/locations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1203,6 +1214,11 @@ func (c *pagesRESTClient) CancelOperation(ctx context.Context, req *longrunningp } baseUrl.Path += fmt.Sprintf("/v3beta1/%v:cancel", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1238,6 +1254,11 @@ func (c *pagesRESTClient) GetOperation(ctx context.Context, req *longrunningpb.G } baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1305,6 +1326,7 @@ func (c *pagesRESTClient) ListOperations(ctx context.Context, req *longrunningpb baseUrl.Path += fmt.Sprintf("/v3beta1/%v/operations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/dialogflow/cx/apiv3beta1/security_settings_client.go b/dialogflow/cx/apiv3beta1/security_settings_client.go index 3c7020142ccd..8123b65f2f27 100644 --- a/dialogflow/cx/apiv3beta1/security_settings_client.go +++ b/dialogflow/cx/apiv3beta1/security_settings_client.go @@ -735,6 +735,11 @@ func (c *securitySettingsRESTClient) CreateSecuritySettings(ctx context.Context, } baseUrl.Path += fmt.Sprintf("/v3beta1/%v/securitySettings", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -789,6 +794,11 @@ func (c *securitySettingsRESTClient) GetSecuritySettings(ctx context.Context, re } baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -850,6 +860,7 @@ func (c *securitySettingsRESTClient) UpdateSecuritySettings(ctx context.Context, baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetSecuritySettings().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -927,6 +938,7 @@ func (c *securitySettingsRESTClient) ListSecuritySettings(ctx context.Context, r baseUrl.Path += fmt.Sprintf("/v3beta1/%v/securitySettings", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -1000,6 +1012,11 @@ func (c *securitySettingsRESTClient) DeleteSecuritySettings(ctx context.Context, } baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1035,6 +1052,11 @@ func (c *securitySettingsRESTClient) GetLocation(ctx context.Context, req *locat } baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1102,6 +1124,7 @@ func (c *securitySettingsRESTClient) ListLocations(ctx context.Context, req *loc baseUrl.Path += fmt.Sprintf("/v3beta1/%v/locations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1178,6 +1201,11 @@ func (c *securitySettingsRESTClient) CancelOperation(ctx context.Context, req *l } baseUrl.Path += fmt.Sprintf("/v3beta1/%v:cancel", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1213,6 +1241,11 @@ func (c *securitySettingsRESTClient) GetOperation(ctx context.Context, req *long } baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1280,6 +1313,7 @@ func (c *securitySettingsRESTClient) ListOperations(ctx context.Context, req *lo baseUrl.Path += fmt.Sprintf("/v3beta1/%v/operations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/dialogflow/cx/apiv3beta1/session_entity_types_client.go b/dialogflow/cx/apiv3beta1/session_entity_types_client.go index 112397df3833..1bef513068eb 100644 --- a/dialogflow/cx/apiv3beta1/session_entity_types_client.go +++ b/dialogflow/cx/apiv3beta1/session_entity_types_client.go @@ -741,6 +741,7 @@ func (c *sessionEntityTypesRESTClient) ListSessionEntityTypes(ctx context.Contex baseUrl.Path += fmt.Sprintf("/v3beta1/%v/entityTypes", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -814,6 +815,11 @@ func (c *sessionEntityTypesRESTClient) GetSessionEntityType(ctx context.Context, } baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -874,6 +880,11 @@ func (c *sessionEntityTypesRESTClient) CreateSessionEntityType(ctx context.Conte } baseUrl.Path += fmt.Sprintf("/v3beta1/%v/entityTypes", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -935,6 +946,7 @@ func (c *sessionEntityTypesRESTClient) UpdateSessionEntityType(ctx context.Conte baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetSessionEntityType().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -998,6 +1010,11 @@ func (c *sessionEntityTypesRESTClient) DeleteSessionEntityType(ctx context.Conte } baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1033,6 +1050,11 @@ func (c *sessionEntityTypesRESTClient) GetLocation(ctx context.Context, req *loc } baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1100,6 +1122,7 @@ func (c *sessionEntityTypesRESTClient) ListLocations(ctx context.Context, req *l baseUrl.Path += fmt.Sprintf("/v3beta1/%v/locations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1176,6 +1199,11 @@ func (c *sessionEntityTypesRESTClient) CancelOperation(ctx context.Context, req } baseUrl.Path += fmt.Sprintf("/v3beta1/%v:cancel", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1211,6 +1239,11 @@ func (c *sessionEntityTypesRESTClient) GetOperation(ctx context.Context, req *lo } baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1278,6 +1311,7 @@ func (c *sessionEntityTypesRESTClient) ListOperations(ctx context.Context, req * baseUrl.Path += fmt.Sprintf("/v3beta1/%v/operations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/dialogflow/cx/apiv3beta1/sessions_client.go b/dialogflow/cx/apiv3beta1/sessions_client.go index 3ee2956f6b69..d3d8f0dfffa6 100644 --- a/dialogflow/cx/apiv3beta1/sessions_client.go +++ b/dialogflow/cx/apiv3beta1/sessions_client.go @@ -227,6 +227,8 @@ func (c *SessionsClient) DetectIntent(ctx context.Context, req *cxpb.DetectInten // Note: Always use agent versions for production traffic. // See Versions and // environments (at https://cloud.google.com/dialogflow/cx/docs/concept/version). +// +// This method is not supported for the REST transport. func (c *SessionsClient) StreamingDetectIntent(ctx context.Context, opts ...gax.CallOption) (cxpb.Sessions_StreamingDetectIntentClient, error) { return c.internalClient.StreamingDetectIntent(ctx, opts...) } @@ -667,6 +669,11 @@ func (c *sessionsRESTClient) DetectIntent(ctx context.Context, req *cxpb.DetectI } baseUrl.Path += fmt.Sprintf("/v3beta1/%v:detectIntent", req.GetSession()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "session", url.QueryEscape(req.GetSession()))) @@ -719,6 +726,8 @@ func (c *sessionsRESTClient) DetectIntent(ctx context.Context, req *cxpb.DetectI // Note: Always use agent versions for production traffic. // See Versions and // environments (at https://cloud.google.com/dialogflow/cx/docs/concept/version). +// +// This method is not supported for the REST transport. func (c *sessionsRESTClient) StreamingDetectIntent(ctx context.Context, opts ...gax.CallOption) (cxpb.Sessions_StreamingDetectIntentClient, error) { return nil, fmt.Errorf("StreamingDetectIntent not yet supported for REST clients") } @@ -738,6 +747,11 @@ func (c *sessionsRESTClient) MatchIntent(ctx context.Context, req *cxpb.MatchInt } baseUrl.Path += fmt.Sprintf("/v3beta1/%v:matchIntent", req.GetSession()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "session", url.QueryEscape(req.GetSession()))) @@ -799,6 +813,11 @@ func (c *sessionsRESTClient) FulfillIntent(ctx context.Context, req *cxpb.Fulfil } baseUrl.Path += fmt.Sprintf("/v3beta1/%v:fulfillIntent", req.GetMatchIntentRequest().GetSession()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "match_intent_request.session", url.QueryEscape(req.GetMatchIntentRequest().GetSession()))) @@ -852,6 +871,11 @@ func (c *sessionsRESTClient) GetLocation(ctx context.Context, req *locationpb.Ge } baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -919,6 +943,7 @@ func (c *sessionsRESTClient) ListLocations(ctx context.Context, req *locationpb. baseUrl.Path += fmt.Sprintf("/v3beta1/%v/locations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -995,6 +1020,11 @@ func (c *sessionsRESTClient) CancelOperation(ctx context.Context, req *longrunni } baseUrl.Path += fmt.Sprintf("/v3beta1/%v:cancel", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1030,6 +1060,11 @@ func (c *sessionsRESTClient) GetOperation(ctx context.Context, req *longrunningp } baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1097,6 +1132,7 @@ func (c *sessionsRESTClient) ListOperations(ctx context.Context, req *longrunnin baseUrl.Path += fmt.Sprintf("/v3beta1/%v/operations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/dialogflow/cx/apiv3beta1/test_cases_client.go b/dialogflow/cx/apiv3beta1/test_cases_client.go index f5f7dfa62786..632bfeb295e1 100644 --- a/dialogflow/cx/apiv3beta1/test_cases_client.go +++ b/dialogflow/cx/apiv3beta1/test_cases_client.go @@ -1226,6 +1226,7 @@ func (c *testCasesRESTClient) ListTestCases(ctx context.Context, req *cxpb.ListT baseUrl.Path += fmt.Sprintf("/v3beta1/%v/testCases", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -1308,6 +1309,11 @@ func (c *testCasesRESTClient) BatchDeleteTestCases(ctx context.Context, req *cxp } baseUrl.Path += fmt.Sprintf("/v3beta1/%v/testCases:batchDelete", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1343,6 +1349,11 @@ func (c *testCasesRESTClient) GetTestCase(ctx context.Context, req *cxpb.GetTest } baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1403,6 +1414,11 @@ func (c *testCasesRESTClient) CreateTestCase(ctx context.Context, req *cxpb.Crea } baseUrl.Path += fmt.Sprintf("/v3beta1/%v/testCases", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1464,6 +1480,7 @@ func (c *testCasesRESTClient) UpdateTestCase(ctx context.Context, req *cxpb.Upda baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetTestCase().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -1541,6 +1558,11 @@ func (c *testCasesRESTClient) RunTestCase(ctx context.Context, req *cxpb.RunTest } baseUrl.Path += fmt.Sprintf("/v3beta1/%v:run", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1612,6 +1634,11 @@ func (c *testCasesRESTClient) BatchRunTestCases(ctx context.Context, req *cxpb.B } baseUrl.Path += fmt.Sprintf("/v3beta1/%v/testCases:batchRun", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1670,6 +1697,7 @@ func (c *testCasesRESTClient) CalculateCoverage(ctx context.Context, req *cxpb.C baseUrl.Path += fmt.Sprintf("/v3beta1/%v/testCases:calculateCoverage", req.GetAgent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("type", fmt.Sprintf("%v", req.GetType())) baseUrl.RawQuery = params.Encode() @@ -1743,6 +1771,11 @@ func (c *testCasesRESTClient) ImportTestCases(ctx context.Context, req *cxpb.Imp } baseUrl.Path += fmt.Sprintf("/v3beta1/%v/testCases:import", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1815,6 +1848,11 @@ func (c *testCasesRESTClient) ExportTestCases(ctx context.Context, req *cxpb.Exp } baseUrl.Path += fmt.Sprintf("/v3beta1/%v/testCases:export", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1886,6 +1924,7 @@ func (c *testCasesRESTClient) ListTestCaseResults(ctx context.Context, req *cxpb baseUrl.Path += fmt.Sprintf("/v3beta1/%v/results", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1962,6 +2001,11 @@ func (c *testCasesRESTClient) GetTestCaseResult(ctx context.Context, req *cxpb.G } baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2015,6 +2059,11 @@ func (c *testCasesRESTClient) GetLocation(ctx context.Context, req *locationpb.G } baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2082,6 +2131,7 @@ func (c *testCasesRESTClient) ListLocations(ctx context.Context, req *locationpb baseUrl.Path += fmt.Sprintf("/v3beta1/%v/locations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -2158,6 +2208,11 @@ func (c *testCasesRESTClient) CancelOperation(ctx context.Context, req *longrunn } baseUrl.Path += fmt.Sprintf("/v3beta1/%v:cancel", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2193,6 +2248,11 @@ func (c *testCasesRESTClient) GetOperation(ctx context.Context, req *longrunning } baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2260,6 +2320,7 @@ func (c *testCasesRESTClient) ListOperations(ctx context.Context, req *longrunni baseUrl.Path += fmt.Sprintf("/v3beta1/%v/operations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/dialogflow/cx/apiv3beta1/transition_route_groups_client.go b/dialogflow/cx/apiv3beta1/transition_route_groups_client.go index def032aa2cb5..96190a6bd7f6 100644 --- a/dialogflow/cx/apiv3beta1/transition_route_groups_client.go +++ b/dialogflow/cx/apiv3beta1/transition_route_groups_client.go @@ -753,6 +753,7 @@ func (c *transitionRouteGroupsRESTClient) ListTransitionRouteGroups(ctx context. baseUrl.Path += fmt.Sprintf("/v3beta1/%v/transitionRouteGroups", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetLanguageCode() != "" { params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) } @@ -830,6 +831,7 @@ func (c *transitionRouteGroupsRESTClient) GetTransitionRouteGroup(ctx context.Co baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetLanguageCode() != "" { params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) } @@ -901,6 +903,7 @@ func (c *transitionRouteGroupsRESTClient) CreateTransitionRouteGroup(ctx context baseUrl.Path += fmt.Sprintf("/v3beta1/%v/transitionRouteGroups", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetLanguageCode() != "" { params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) } @@ -972,6 +975,7 @@ func (c *transitionRouteGroupsRESTClient) UpdateTransitionRouteGroup(ctx context baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetTransitionRouteGroup().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetLanguageCode() != "" { params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) } @@ -1043,6 +1047,7 @@ func (c *transitionRouteGroupsRESTClient) DeleteTransitionRouteGroup(ctx context baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetForce() { params.Add("force", fmt.Sprintf("%v", req.GetForce())) } @@ -1084,6 +1089,11 @@ func (c *transitionRouteGroupsRESTClient) GetLocation(ctx context.Context, req * } baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1151,6 +1161,7 @@ func (c *transitionRouteGroupsRESTClient) ListLocations(ctx context.Context, req baseUrl.Path += fmt.Sprintf("/v3beta1/%v/locations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1227,6 +1238,11 @@ func (c *transitionRouteGroupsRESTClient) CancelOperation(ctx context.Context, r } baseUrl.Path += fmt.Sprintf("/v3beta1/%v:cancel", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1262,6 +1278,11 @@ func (c *transitionRouteGroupsRESTClient) GetOperation(ctx context.Context, req } baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1329,6 +1350,7 @@ func (c *transitionRouteGroupsRESTClient) ListOperations(ctx context.Context, re baseUrl.Path += fmt.Sprintf("/v3beta1/%v/operations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/dialogflow/cx/apiv3beta1/versions_client.go b/dialogflow/cx/apiv3beta1/versions_client.go index 723fd6cef032..11d0455799dc 100644 --- a/dialogflow/cx/apiv3beta1/versions_client.go +++ b/dialogflow/cx/apiv3beta1/versions_client.go @@ -916,6 +916,7 @@ func (c *versionsRESTClient) ListVersions(ctx context.Context, req *cxpb.ListVer baseUrl.Path += fmt.Sprintf("/v3beta1/%v/versions", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -989,6 +990,11 @@ func (c *versionsRESTClient) GetVersion(ctx context.Context, req *cxpb.GetVersio } baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1057,6 +1063,11 @@ func (c *versionsRESTClient) CreateVersion(ctx context.Context, req *cxpb.Create } baseUrl.Path += fmt.Sprintf("/v3beta1/%v/versions", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1122,6 +1133,7 @@ func (c *versionsRESTClient) UpdateVersion(ctx context.Context, req *cxpb.Update baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetVersion().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -1185,6 +1197,11 @@ func (c *versionsRESTClient) DeleteVersion(ctx context.Context, req *cxpb.Delete } baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1236,6 +1253,11 @@ func (c *versionsRESTClient) LoadVersion(ctx context.Context, req *cxpb.LoadVers } baseUrl.Path += fmt.Sprintf("/v3beta1/%v:load", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1299,6 +1321,11 @@ func (c *versionsRESTClient) CompareVersions(ctx context.Context, req *cxpb.Comp } baseUrl.Path += fmt.Sprintf("/v3beta1/%v:compareVersions", req.GetBaseVersion()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "base_version", url.QueryEscape(req.GetBaseVersion()))) @@ -1352,6 +1379,11 @@ func (c *versionsRESTClient) GetLocation(ctx context.Context, req *locationpb.Ge } baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1419,6 +1451,7 @@ func (c *versionsRESTClient) ListLocations(ctx context.Context, req *locationpb. baseUrl.Path += fmt.Sprintf("/v3beta1/%v/locations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1495,6 +1528,11 @@ func (c *versionsRESTClient) CancelOperation(ctx context.Context, req *longrunni } baseUrl.Path += fmt.Sprintf("/v3beta1/%v:cancel", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1530,6 +1568,11 @@ func (c *versionsRESTClient) GetOperation(ctx context.Context, req *longrunningp } baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1597,6 +1640,7 @@ func (c *versionsRESTClient) ListOperations(ctx context.Context, req *longrunnin baseUrl.Path += fmt.Sprintf("/v3beta1/%v/operations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/dialogflow/cx/apiv3beta1/webhooks_client.go b/dialogflow/cx/apiv3beta1/webhooks_client.go index 8146a0ec76a8..4dfdcb04ef7c 100644 --- a/dialogflow/cx/apiv3beta1/webhooks_client.go +++ b/dialogflow/cx/apiv3beta1/webhooks_client.go @@ -741,6 +741,7 @@ func (c *webhooksRESTClient) ListWebhooks(ctx context.Context, req *cxpb.ListWeb baseUrl.Path += fmt.Sprintf("/v3beta1/%v/webhooks", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -814,6 +815,11 @@ func (c *webhooksRESTClient) GetWebhook(ctx context.Context, req *cxpb.GetWebhoo } baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -874,6 +880,11 @@ func (c *webhooksRESTClient) CreateWebhook(ctx context.Context, req *cxpb.Create } baseUrl.Path += fmt.Sprintf("/v3beta1/%v/webhooks", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -935,6 +946,7 @@ func (c *webhooksRESTClient) UpdateWebhook(ctx context.Context, req *cxpb.Update baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetWebhook().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -999,6 +1011,7 @@ func (c *webhooksRESTClient) DeleteWebhook(ctx context.Context, req *cxpb.Delete baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetForce() { params.Add("force", fmt.Sprintf("%v", req.GetForce())) } @@ -1040,6 +1053,11 @@ func (c *webhooksRESTClient) GetLocation(ctx context.Context, req *locationpb.Ge } baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1107,6 +1125,7 @@ func (c *webhooksRESTClient) ListLocations(ctx context.Context, req *locationpb. baseUrl.Path += fmt.Sprintf("/v3beta1/%v/locations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1183,6 +1202,11 @@ func (c *webhooksRESTClient) CancelOperation(ctx context.Context, req *longrunni } baseUrl.Path += fmt.Sprintf("/v3beta1/%v:cancel", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1218,6 +1242,11 @@ func (c *webhooksRESTClient) GetOperation(ctx context.Context, req *longrunningp } baseUrl.Path += fmt.Sprintf("/v3beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1285,6 +1314,7 @@ func (c *webhooksRESTClient) ListOperations(ctx context.Context, req *longrunnin baseUrl.Path += fmt.Sprintf("/v3beta1/%v/operations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/dlp/apiv2/dlp_client.go b/dlp/apiv2/dlp_client.go index 20edfd672f4e..37061fba4cdb 100644 --- a/dlp/apiv2/dlp_client.go +++ b/dlp/apiv2/dlp_client.go @@ -17,21 +17,27 @@ package dlp import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" dlppb "cloud.google.com/go/dlp/apiv2/dlppb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -346,6 +352,245 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + InspectContent: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + RedactImage: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + DeidentifyContent: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + ReidentifyContent: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + ListInfoTypes: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + CreateInspectTemplate: []gax.CallOption{}, + UpdateInspectTemplate: []gax.CallOption{}, + GetInspectTemplate: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + ListInspectTemplates: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + DeleteInspectTemplate: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + CreateDeidentifyTemplate: []gax.CallOption{}, + UpdateDeidentifyTemplate: []gax.CallOption{}, + GetDeidentifyTemplate: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + ListDeidentifyTemplates: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + DeleteDeidentifyTemplate: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + CreateJobTrigger: []gax.CallOption{}, + UpdateJobTrigger: []gax.CallOption{}, + HybridInspectJobTrigger: []gax.CallOption{}, + GetJobTrigger: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + ListJobTriggers: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + DeleteJobTrigger: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + ActivateJobTrigger: []gax.CallOption{}, + CreateDlpJob: []gax.CallOption{}, + ListDlpJobs: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + GetDlpJob: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + DeleteDlpJob: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + CancelDlpJob: []gax.CallOption{}, + CreateStoredInfoType: []gax.CallOption{}, + UpdateStoredInfoType: []gax.CallOption{}, + GetStoredInfoType: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + ListStoredInfoTypes: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + DeleteStoredInfoType: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + HybridInspectDlpJob: []gax.CallOption{}, + FinishDlpJob: []gax.CallOption{}, + } +} + // internalClient is an interface that defines the methods available from Cloud Data Loss Prevention (DLP) API. type internalClient interface { Close() error @@ -774,6 +1019,82 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new dlp service rest client. +// +// The Cloud Data Loss Prevention (DLP) API is a service that allows clients +// to detect the presence of Personally Identifiable Information (PII) and other +// privacy-sensitive data in user-supplied, unstructured data streams, like text +// blocks or images. +// The service also includes methods for sensitive data redaction and +// scheduling of data scans on Google Cloud Platform based data sets. +// +// To learn more about concepts and find how-to guides see +// https://cloud.google.com/dlp/docs/ (at https://cloud.google.com/dlp/docs/). +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://dlp.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://dlp.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://dlp.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) InspectContent(ctx context.Context, req *dlppb.InspectContentRequest, opts ...gax.CallOption) (*dlppb.InspectContentResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 300000*time.Millisecond) @@ -1609,6 +1930,2249 @@ func (c *gRPCClient) FinishDlpJob(ctx context.Context, req *dlppb.FinishDlpJobRe return err } +// InspectContent finds potentially sensitive info in content. +// This method has limits on input size, processing time, and output size. +// +// When no InfoTypes or CustomInfoTypes are specified in this request, the +// system will automatically choose what detectors to run. By default this may +// be all types, but may change over time as detectors are updated. +// +// For how to guides, see https://cloud.google.com/dlp/docs/inspecting-images (at https://cloud.google.com/dlp/docs/inspecting-images) +// and https://cloud.google.com/dlp/docs/inspecting-text (at https://cloud.google.com/dlp/docs/inspecting-text), +func (c *restClient) InspectContent(ctx context.Context, req *dlppb.InspectContentRequest, opts ...gax.CallOption) (*dlppb.InspectContentResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/content:inspect", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).InspectContent[0:len((*c.CallOptions).InspectContent):len((*c.CallOptions).InspectContent)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dlppb.InspectContentResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// RedactImage redacts potentially sensitive info from an image. +// This method has limits on input size, processing time, and output size. +// See https://cloud.google.com/dlp/docs/redacting-sensitive-data-images (at https://cloud.google.com/dlp/docs/redacting-sensitive-data-images) to +// learn more. +// +// When no InfoTypes or CustomInfoTypes are specified in this request, the +// system will automatically choose what detectors to run. By default this may +// be all types, but may change over time as detectors are updated. +func (c *restClient) RedactImage(ctx context.Context, req *dlppb.RedactImageRequest, opts ...gax.CallOption) (*dlppb.RedactImageResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/image:redact", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).RedactImage[0:len((*c.CallOptions).RedactImage):len((*c.CallOptions).RedactImage)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dlppb.RedactImageResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeidentifyContent de-identifies potentially sensitive info from a ContentItem. +// This method has limits on input size and output size. +// See https://cloud.google.com/dlp/docs/deidentify-sensitive-data (at https://cloud.google.com/dlp/docs/deidentify-sensitive-data) to +// learn more. +// +// When no InfoTypes or CustomInfoTypes are specified in this request, the +// system will automatically choose what detectors to run. By default this may +// be all types, but may change over time as detectors are updated. +func (c *restClient) DeidentifyContent(ctx context.Context, req *dlppb.DeidentifyContentRequest, opts ...gax.CallOption) (*dlppb.DeidentifyContentResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/content:deidentify", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).DeidentifyContent[0:len((*c.CallOptions).DeidentifyContent):len((*c.CallOptions).DeidentifyContent)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dlppb.DeidentifyContentResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ReidentifyContent re-identifies content that has been de-identified. +// See +// https://cloud.google.com/dlp/docs/pseudonymization#re-identification_in_free_text_code_example (at https://cloud.google.com/dlp/docs/pseudonymization#re-identification_in_free_text_code_example) +// to learn more. +func (c *restClient) ReidentifyContent(ctx context.Context, req *dlppb.ReidentifyContentRequest, opts ...gax.CallOption) (*dlppb.ReidentifyContentResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/content:reidentify", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).ReidentifyContent[0:len((*c.CallOptions).ReidentifyContent):len((*c.CallOptions).ReidentifyContent)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dlppb.ReidentifyContentResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListInfoTypes returns a list of the sensitive information types that DLP API +// supports. See https://cloud.google.com/dlp/docs/infotypes-reference (at https://cloud.google.com/dlp/docs/infotypes-reference) to +// learn more. +func (c *restClient) ListInfoTypes(ctx context.Context, req *dlppb.ListInfoTypesRequest, opts ...gax.CallOption) (*dlppb.ListInfoTypesResponse, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/infoTypes") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetLanguageCode() != "" { + params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) + } + if req.GetLocationId() != "" { + params.Add("locationId", fmt.Sprintf("%v", req.GetLocationId())) + } + if req.GetParent() != "" { + params.Add("parent", fmt.Sprintf("%v", req.GetParent())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).ListInfoTypes[0:len((*c.CallOptions).ListInfoTypes):len((*c.CallOptions).ListInfoTypes)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dlppb.ListInfoTypesResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateInspectTemplate creates an InspectTemplate for reusing frequently used configuration +// for inspecting content, images, and storage. +// See https://cloud.google.com/dlp/docs/creating-templates (at https://cloud.google.com/dlp/docs/creating-templates) to learn more. +func (c *restClient) CreateInspectTemplate(ctx context.Context, req *dlppb.CreateInspectTemplateRequest, opts ...gax.CallOption) (*dlppb.InspectTemplate, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/inspectTemplates", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateInspectTemplate[0:len((*c.CallOptions).CreateInspectTemplate):len((*c.CallOptions).CreateInspectTemplate)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dlppb.InspectTemplate{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateInspectTemplate updates the InspectTemplate. +// See https://cloud.google.com/dlp/docs/creating-templates (at https://cloud.google.com/dlp/docs/creating-templates) to learn more. +func (c *restClient) UpdateInspectTemplate(ctx context.Context, req *dlppb.UpdateInspectTemplateRequest, opts ...gax.CallOption) (*dlppb.InspectTemplate, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateInspectTemplate[0:len((*c.CallOptions).UpdateInspectTemplate):len((*c.CallOptions).UpdateInspectTemplate)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dlppb.InspectTemplate{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetInspectTemplate gets an InspectTemplate. +// See https://cloud.google.com/dlp/docs/creating-templates (at https://cloud.google.com/dlp/docs/creating-templates) to learn more. +func (c *restClient) GetInspectTemplate(ctx context.Context, req *dlppb.GetInspectTemplateRequest, opts ...gax.CallOption) (*dlppb.InspectTemplate, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetInspectTemplate[0:len((*c.CallOptions).GetInspectTemplate):len((*c.CallOptions).GetInspectTemplate)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dlppb.InspectTemplate{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListInspectTemplates lists InspectTemplates. +// See https://cloud.google.com/dlp/docs/creating-templates (at https://cloud.google.com/dlp/docs/creating-templates) to learn more. +func (c *restClient) ListInspectTemplates(ctx context.Context, req *dlppb.ListInspectTemplatesRequest, opts ...gax.CallOption) *InspectTemplateIterator { + it := &InspectTemplateIterator{} + req = proto.Clone(req).(*dlppb.ListInspectTemplatesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*dlppb.InspectTemplate, string, error) { + resp := &dlppb.ListInspectTemplatesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/inspectTemplates", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetLocationId() != "" { + params.Add("locationId", fmt.Sprintf("%v", req.GetLocationId())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetInspectTemplates(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// DeleteInspectTemplate deletes an InspectTemplate. +// See https://cloud.google.com/dlp/docs/creating-templates (at https://cloud.google.com/dlp/docs/creating-templates) to learn more. +func (c *restClient) DeleteInspectTemplate(ctx context.Context, req *dlppb.DeleteInspectTemplateRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// CreateDeidentifyTemplate creates a DeidentifyTemplate for reusing frequently used configuration +// for de-identifying content, images, and storage. +// See https://cloud.google.com/dlp/docs/creating-templates-deid (at https://cloud.google.com/dlp/docs/creating-templates-deid) to learn +// more. +func (c *restClient) CreateDeidentifyTemplate(ctx context.Context, req *dlppb.CreateDeidentifyTemplateRequest, opts ...gax.CallOption) (*dlppb.DeidentifyTemplate, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/deidentifyTemplates", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateDeidentifyTemplate[0:len((*c.CallOptions).CreateDeidentifyTemplate):len((*c.CallOptions).CreateDeidentifyTemplate)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dlppb.DeidentifyTemplate{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateDeidentifyTemplate updates the DeidentifyTemplate. +// See https://cloud.google.com/dlp/docs/creating-templates-deid (at https://cloud.google.com/dlp/docs/creating-templates-deid) to learn +// more. +func (c *restClient) UpdateDeidentifyTemplate(ctx context.Context, req *dlppb.UpdateDeidentifyTemplateRequest, opts ...gax.CallOption) (*dlppb.DeidentifyTemplate, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateDeidentifyTemplate[0:len((*c.CallOptions).UpdateDeidentifyTemplate):len((*c.CallOptions).UpdateDeidentifyTemplate)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dlppb.DeidentifyTemplate{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetDeidentifyTemplate gets a DeidentifyTemplate. +// See https://cloud.google.com/dlp/docs/creating-templates-deid (at https://cloud.google.com/dlp/docs/creating-templates-deid) to learn +// more. +func (c *restClient) GetDeidentifyTemplate(ctx context.Context, req *dlppb.GetDeidentifyTemplateRequest, opts ...gax.CallOption) (*dlppb.DeidentifyTemplate, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetDeidentifyTemplate[0:len((*c.CallOptions).GetDeidentifyTemplate):len((*c.CallOptions).GetDeidentifyTemplate)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dlppb.DeidentifyTemplate{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListDeidentifyTemplates lists DeidentifyTemplates. +// See https://cloud.google.com/dlp/docs/creating-templates-deid (at https://cloud.google.com/dlp/docs/creating-templates-deid) to learn +// more. +func (c *restClient) ListDeidentifyTemplates(ctx context.Context, req *dlppb.ListDeidentifyTemplatesRequest, opts ...gax.CallOption) *DeidentifyTemplateIterator { + it := &DeidentifyTemplateIterator{} + req = proto.Clone(req).(*dlppb.ListDeidentifyTemplatesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*dlppb.DeidentifyTemplate, string, error) { + resp := &dlppb.ListDeidentifyTemplatesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/deidentifyTemplates", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetLocationId() != "" { + params.Add("locationId", fmt.Sprintf("%v", req.GetLocationId())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetDeidentifyTemplates(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// DeleteDeidentifyTemplate deletes a DeidentifyTemplate. +// See https://cloud.google.com/dlp/docs/creating-templates-deid (at https://cloud.google.com/dlp/docs/creating-templates-deid) to learn +// more. +func (c *restClient) DeleteDeidentifyTemplate(ctx context.Context, req *dlppb.DeleteDeidentifyTemplateRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// CreateJobTrigger creates a job trigger to run DLP actions such as scanning storage for +// sensitive information on a set schedule. +// See https://cloud.google.com/dlp/docs/creating-job-triggers (at https://cloud.google.com/dlp/docs/creating-job-triggers) to learn more. +func (c *restClient) CreateJobTrigger(ctx context.Context, req *dlppb.CreateJobTriggerRequest, opts ...gax.CallOption) (*dlppb.JobTrigger, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/jobTriggers", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateJobTrigger[0:len((*c.CallOptions).CreateJobTrigger):len((*c.CallOptions).CreateJobTrigger)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dlppb.JobTrigger{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateJobTrigger updates a job trigger. +// See https://cloud.google.com/dlp/docs/creating-job-triggers (at https://cloud.google.com/dlp/docs/creating-job-triggers) to learn more. +func (c *restClient) UpdateJobTrigger(ctx context.Context, req *dlppb.UpdateJobTriggerRequest, opts ...gax.CallOption) (*dlppb.JobTrigger, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateJobTrigger[0:len((*c.CallOptions).UpdateJobTrigger):len((*c.CallOptions).UpdateJobTrigger)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dlppb.JobTrigger{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// HybridInspectJobTrigger inspect hybrid content and store findings to a trigger. The inspection +// will be processed asynchronously. To review the findings monitor the +// jobs within the trigger. +func (c *restClient) HybridInspectJobTrigger(ctx context.Context, req *dlppb.HybridInspectJobTriggerRequest, opts ...gax.CallOption) (*dlppb.HybridInspectResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:hybridInspect", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).HybridInspectJobTrigger[0:len((*c.CallOptions).HybridInspectJobTrigger):len((*c.CallOptions).HybridInspectJobTrigger)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dlppb.HybridInspectResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetJobTrigger gets a job trigger. +// See https://cloud.google.com/dlp/docs/creating-job-triggers (at https://cloud.google.com/dlp/docs/creating-job-triggers) to learn more. +func (c *restClient) GetJobTrigger(ctx context.Context, req *dlppb.GetJobTriggerRequest, opts ...gax.CallOption) (*dlppb.JobTrigger, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetJobTrigger[0:len((*c.CallOptions).GetJobTrigger):len((*c.CallOptions).GetJobTrigger)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dlppb.JobTrigger{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListJobTriggers lists job triggers. +// See https://cloud.google.com/dlp/docs/creating-job-triggers (at https://cloud.google.com/dlp/docs/creating-job-triggers) to learn more. +func (c *restClient) ListJobTriggers(ctx context.Context, req *dlppb.ListJobTriggersRequest, opts ...gax.CallOption) *JobTriggerIterator { + it := &JobTriggerIterator{} + req = proto.Clone(req).(*dlppb.ListJobTriggersRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*dlppb.JobTrigger, string, error) { + resp := &dlppb.ListJobTriggersResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/jobTriggers", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetLocationId() != "" { + params.Add("locationId", fmt.Sprintf("%v", req.GetLocationId())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + if req.GetType() != 0 { + params.Add("type", fmt.Sprintf("%v", req.GetType())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetJobTriggers(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// DeleteJobTrigger deletes a job trigger. +// See https://cloud.google.com/dlp/docs/creating-job-triggers (at https://cloud.google.com/dlp/docs/creating-job-triggers) to learn more. +func (c *restClient) DeleteJobTrigger(ctx context.Context, req *dlppb.DeleteJobTriggerRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// ActivateJobTrigger activate a job trigger. Causes the immediate execute of a trigger +// instead of waiting on the trigger event to occur. +func (c *restClient) ActivateJobTrigger(ctx context.Context, req *dlppb.ActivateJobTriggerRequest, opts ...gax.CallOption) (*dlppb.DlpJob, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:activate", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).ActivateJobTrigger[0:len((*c.CallOptions).ActivateJobTrigger):len((*c.CallOptions).ActivateJobTrigger)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dlppb.DlpJob{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateDlpJob creates a new job to inspect storage or calculate risk metrics. +// See https://cloud.google.com/dlp/docs/inspecting-storage (at https://cloud.google.com/dlp/docs/inspecting-storage) and +// https://cloud.google.com/dlp/docs/compute-risk-analysis (at https://cloud.google.com/dlp/docs/compute-risk-analysis) to learn more. +// +// When no InfoTypes or CustomInfoTypes are specified in inspect jobs, the +// system will automatically choose what detectors to run. By default this may +// be all types, but may change over time as detectors are updated. +func (c *restClient) CreateDlpJob(ctx context.Context, req *dlppb.CreateDlpJobRequest, opts ...gax.CallOption) (*dlppb.DlpJob, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/dlpJobs", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateDlpJob[0:len((*c.CallOptions).CreateDlpJob):len((*c.CallOptions).CreateDlpJob)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dlppb.DlpJob{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListDlpJobs lists DlpJobs that match the specified filter in the request. +// See https://cloud.google.com/dlp/docs/inspecting-storage (at https://cloud.google.com/dlp/docs/inspecting-storage) and +// https://cloud.google.com/dlp/docs/compute-risk-analysis (at https://cloud.google.com/dlp/docs/compute-risk-analysis) to learn more. +func (c *restClient) ListDlpJobs(ctx context.Context, req *dlppb.ListDlpJobsRequest, opts ...gax.CallOption) *DlpJobIterator { + it := &DlpJobIterator{} + req = proto.Clone(req).(*dlppb.ListDlpJobsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*dlppb.DlpJob, string, error) { + resp := &dlppb.ListDlpJobsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/dlpJobs", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetLocationId() != "" { + params.Add("locationId", fmt.Sprintf("%v", req.GetLocationId())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + if req.GetType() != 0 { + params.Add("type", fmt.Sprintf("%v", req.GetType())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetJobs(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetDlpJob gets the latest state of a long-running DlpJob. +// See https://cloud.google.com/dlp/docs/inspecting-storage (at https://cloud.google.com/dlp/docs/inspecting-storage) and +// https://cloud.google.com/dlp/docs/compute-risk-analysis (at https://cloud.google.com/dlp/docs/compute-risk-analysis) to learn more. +func (c *restClient) GetDlpJob(ctx context.Context, req *dlppb.GetDlpJobRequest, opts ...gax.CallOption) (*dlppb.DlpJob, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetDlpJob[0:len((*c.CallOptions).GetDlpJob):len((*c.CallOptions).GetDlpJob)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dlppb.DlpJob{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteDlpJob deletes a long-running DlpJob. This method indicates that the client is +// no longer interested in the DlpJob result. The job will be canceled if +// possible. +// See https://cloud.google.com/dlp/docs/inspecting-storage (at https://cloud.google.com/dlp/docs/inspecting-storage) and +// https://cloud.google.com/dlp/docs/compute-risk-analysis (at https://cloud.google.com/dlp/docs/compute-risk-analysis) to learn more. +func (c *restClient) DeleteDlpJob(ctx context.Context, req *dlppb.DeleteDlpJobRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// CancelDlpJob starts asynchronous cancellation on a long-running DlpJob. The server +// makes a best effort to cancel the DlpJob, but success is not +// guaranteed. +// See https://cloud.google.com/dlp/docs/inspecting-storage (at https://cloud.google.com/dlp/docs/inspecting-storage) and +// https://cloud.google.com/dlp/docs/compute-risk-analysis (at https://cloud.google.com/dlp/docs/compute-risk-analysis) to learn more. +func (c *restClient) CancelDlpJob(ctx context.Context, req *dlppb.CancelDlpJobRequest, opts ...gax.CallOption) error { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// CreateStoredInfoType creates a pre-built stored infoType to be used for inspection. +// See https://cloud.google.com/dlp/docs/creating-stored-infotypes (at https://cloud.google.com/dlp/docs/creating-stored-infotypes) to +// learn more. +func (c *restClient) CreateStoredInfoType(ctx context.Context, req *dlppb.CreateStoredInfoTypeRequest, opts ...gax.CallOption) (*dlppb.StoredInfoType, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/storedInfoTypes", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateStoredInfoType[0:len((*c.CallOptions).CreateStoredInfoType):len((*c.CallOptions).CreateStoredInfoType)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dlppb.StoredInfoType{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateStoredInfoType updates the stored infoType by creating a new version. The existing version +// will continue to be used until the new version is ready. +// See https://cloud.google.com/dlp/docs/creating-stored-infotypes (at https://cloud.google.com/dlp/docs/creating-stored-infotypes) to +// learn more. +func (c *restClient) UpdateStoredInfoType(ctx context.Context, req *dlppb.UpdateStoredInfoTypeRequest, opts ...gax.CallOption) (*dlppb.StoredInfoType, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateStoredInfoType[0:len((*c.CallOptions).UpdateStoredInfoType):len((*c.CallOptions).UpdateStoredInfoType)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dlppb.StoredInfoType{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetStoredInfoType gets a stored infoType. +// See https://cloud.google.com/dlp/docs/creating-stored-infotypes (at https://cloud.google.com/dlp/docs/creating-stored-infotypes) to +// learn more. +func (c *restClient) GetStoredInfoType(ctx context.Context, req *dlppb.GetStoredInfoTypeRequest, opts ...gax.CallOption) (*dlppb.StoredInfoType, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetStoredInfoType[0:len((*c.CallOptions).GetStoredInfoType):len((*c.CallOptions).GetStoredInfoType)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dlppb.StoredInfoType{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListStoredInfoTypes lists stored infoTypes. +// See https://cloud.google.com/dlp/docs/creating-stored-infotypes (at https://cloud.google.com/dlp/docs/creating-stored-infotypes) to +// learn more. +func (c *restClient) ListStoredInfoTypes(ctx context.Context, req *dlppb.ListStoredInfoTypesRequest, opts ...gax.CallOption) *StoredInfoTypeIterator { + it := &StoredInfoTypeIterator{} + req = proto.Clone(req).(*dlppb.ListStoredInfoTypesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*dlppb.StoredInfoType, string, error) { + resp := &dlppb.ListStoredInfoTypesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/storedInfoTypes", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetLocationId() != "" { + params.Add("locationId", fmt.Sprintf("%v", req.GetLocationId())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetStoredInfoTypes(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// DeleteStoredInfoType deletes a stored infoType. +// See https://cloud.google.com/dlp/docs/creating-stored-infotypes (at https://cloud.google.com/dlp/docs/creating-stored-infotypes) to +// learn more. +func (c *restClient) DeleteStoredInfoType(ctx context.Context, req *dlppb.DeleteStoredInfoTypeRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// HybridInspectDlpJob inspect hybrid content and store findings to a job. +// To review the findings, inspect the job. Inspection will occur +// asynchronously. +func (c *restClient) HybridInspectDlpJob(ctx context.Context, req *dlppb.HybridInspectDlpJobRequest, opts ...gax.CallOption) (*dlppb.HybridInspectResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:hybridInspect", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).HybridInspectDlpJob[0:len((*c.CallOptions).HybridInspectDlpJob):len((*c.CallOptions).HybridInspectDlpJob)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dlppb.HybridInspectResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// FinishDlpJob finish a running hybrid DlpJob. Triggers the finalization steps and running +// of any enabled actions that have not yet run. +func (c *restClient) FinishDlpJob(ctx context.Context, req *dlppb.FinishDlpJobRequest, opts ...gax.CallOption) error { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:finish", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + // DeidentifyTemplateIterator manages a stream of *dlppb.DeidentifyTemplate. type DeidentifyTemplateIterator struct { items []*dlppb.DeidentifyTemplate diff --git a/dlp/apiv2/dlp_client_example_test.go b/dlp/apiv2/dlp_client_example_test.go index eceb6de8f1f7..5c6a7d8f04d6 100644 --- a/dlp/apiv2/dlp_client_example_test.go +++ b/dlp/apiv2/dlp_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := dlp.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_InspectContent() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/dlp/apiv2/dlppb/dlp.pb.go b/dlp/apiv2/dlppb/dlp.pb.go index 02e52dc86433..1147afa383b5 100644 --- a/dlp/apiv2/dlppb/dlp.pb.go +++ b/dlp/apiv2/dlppb/dlp.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/privacy/dlp/v2/dlp.proto package dlppb @@ -2213,7 +2213,6 @@ type ExclusionRule struct { // Exclusion rule types. // // Types that are assignable to Type: - // // *ExclusionRule_Dictionary // *ExclusionRule_Regex // *ExclusionRule_ExcludeInfoTypes @@ -2340,7 +2339,6 @@ type InspectionRule struct { // Inspection rule types. // // Types that are assignable to Type: - // // *InspectionRule_HotwordRule // *InspectionRule_ExclusionRule Type isInspectionRule_Type `protobuf_oneof:"type"` @@ -2681,7 +2679,6 @@ type ContentItem struct { // Data of the item either in the byte array or UTF-8 string form, or table. // // Types that are assignable to DataItem: - // // *ContentItem_Value // *ContentItem_Table // *ContentItem_ByteItem @@ -3180,7 +3177,6 @@ type ContentLocation struct { // Type of the container within the file with location of the finding. // // Types that are assignable to Location: - // // *ContentLocation_RecordLocation // *ContentLocation_ImageLocation // *ContentLocation_DocumentLocation @@ -3328,7 +3324,6 @@ type MetadataLocation struct { // latitude, author, caption. // // Types that are assignable to Label: - // // *MetadataLocation_StorageLabel Label isMetadataLocation_Label `protobuf_oneof:"label"` } @@ -3636,18 +3631,18 @@ type Container struct { // The root of the container. // Examples: // - // - For BigQuery table `project_id:dataset_id.table_id`, the root is - // `dataset_id` - // - For Cloud Storage file `gs://bucket/folder/filename.txt`, the root - // is `gs://bucket` + // - For BigQuery table `project_id:dataset_id.table_id`, the root is + // `dataset_id` + // - For Cloud Storage file `gs://bucket/folder/filename.txt`, the root + // is `gs://bucket` RootPath string `protobuf:"bytes,4,opt,name=root_path,json=rootPath,proto3" json:"root_path,omitempty"` // The rest of the path after the root. // Examples: // - // - For BigQuery table `project_id:dataset_id.table_id`, the relative path is - // `table_id` - // - For Cloud Storage file `gs://bucket/folder/filename.txt`, the relative - // path is `folder/filename.txt` + // - For BigQuery table `project_id:dataset_id.table_id`, the relative path is + // `table_id` + // - For Cloud Storage file `gs://bucket/folder/filename.txt`, the relative + // path is `folder/filename.txt` RelativePath string `protobuf:"bytes,5,opt,name=relative_path,json=relativePath,proto3" json:"relative_path,omitempty"` // Findings container modification timestamp, if applicable. For Cloud // Storage, this field contains the last file modification timestamp. For a @@ -3936,16 +3931,16 @@ type RedactImageRequest struct { // processing // location](https://cloud.google.com/dlp/docs/specifying-location): // - // - Projects scope, location specified:
- // `projects/`PROJECT_ID`/locations/`LOCATION_ID - // - Projects scope, no location specified (defaults to global):
- // `projects/`PROJECT_ID + // + Projects scope, location specified:
+ // `projects/`PROJECT_ID`/locations/`LOCATION_ID + // + Projects scope, no location specified (defaults to global):
+ // `projects/`PROJECT_ID // // The following example `parent` string specifies a parent project with the // identifier `example-project`, and specifies the `europe-west3` location // for processing data: // - // parent=projects/example-project/locations/europe-west3 + // parent=projects/example-project/locations/europe-west3 Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // Deprecated. This field has no effect. LocationId string `protobuf:"bytes,8,opt,name=location_id,json=locationId,proto3" json:"location_id,omitempty"` @@ -4182,16 +4177,16 @@ type DeidentifyContentRequest struct { // processing // location](https://cloud.google.com/dlp/docs/specifying-location): // - // - Projects scope, location specified:
- // `projects/`PROJECT_ID`/locations/`LOCATION_ID - // - Projects scope, no location specified (defaults to global):
- // `projects/`PROJECT_ID + // + Projects scope, location specified:
+ // `projects/`PROJECT_ID`/locations/`LOCATION_ID + // + Projects scope, no location specified (defaults to global):
+ // `projects/`PROJECT_ID // // The following example `parent` string specifies a parent project with the // identifier `example-project`, and specifies the `europe-west3` location // for processing data: // - // parent=projects/example-project/locations/europe-west3 + // parent=projects/example-project/locations/europe-west3 Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // Configuration for the de-identification of the content item. // Items specified here will override the template referenced by the @@ -4377,16 +4372,16 @@ type ReidentifyContentRequest struct { // processing // location](https://cloud.google.com/dlp/docs/specifying-location): // - // - Projects scope, location specified:
- // `projects/`PROJECT_ID`/locations/`LOCATION_ID - // - Projects scope, no location specified (defaults to global):
- // `projects/`PROJECT_ID + // + Projects scope, location specified:
+ // `projects/`PROJECT_ID`/locations/`LOCATION_ID + // + Projects scope, no location specified (defaults to global):
+ // `projects/`PROJECT_ID // // The following example `parent` string specifies a parent project with the // identifier `example-project`, and specifies the `europe-west3` location // for processing data: // - // parent=projects/example-project/locations/europe-west3 + // parent=projects/example-project/locations/europe-west3 Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // Configuration for the re-identification of the content item. // This field shares the same proto message type that is used for @@ -4396,8 +4391,8 @@ type ReidentifyContentRequest struct { // reverse. This requires that only reversible transformations // be provided here. The reversible transformations are: // - // - `CryptoDeterministicConfig` - // - `CryptoReplaceFfxFpeConfig` + // - `CryptoDeterministicConfig` + // - `CryptoReplaceFfxFpeConfig` ReidentifyConfig *DeidentifyConfig `protobuf:"bytes,2,opt,name=reidentify_config,json=reidentifyConfig,proto3" json:"reidentify_config,omitempty"` // Configuration for the inspector. InspectConfig *InspectConfig `protobuf:"bytes,3,opt,name=inspect_config,json=inspectConfig,proto3" json:"inspect_config,omitempty"` @@ -4572,16 +4567,16 @@ type InspectContentRequest struct { // processing // location](https://cloud.google.com/dlp/docs/specifying-location): // - // - Projects scope, location specified:
- // `projects/`PROJECT_ID`/locations/`LOCATION_ID - // - Projects scope, no location specified (defaults to global):
- // `projects/`PROJECT_ID + // + Projects scope, location specified:
+ // `projects/`PROJECT_ID`/locations/`LOCATION_ID + // + Projects scope, no location specified (defaults to global):
+ // `projects/`PROJECT_ID // // The following example `parent` string specifies a parent project with the // identifier `example-project`, and specifies the `europe-west3` location // for processing data: // - // parent=projects/example-project/locations/europe-west3 + // parent=projects/example-project/locations/europe-west3 Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // Configuration for the inspector. What specified here will override // the template referenced by the inspect_template_name argument. @@ -4723,7 +4718,6 @@ type OutputStorageConfig struct { // Output storage types. // // Types that are assignable to Type: - // // *OutputStorageConfig_Table Type isOutputStorageConfig_Type `protobuf_oneof:"type"` // Schema used for writing the findings for Inspect jobs. This field is only @@ -5107,7 +5101,6 @@ type InfoTypeCategory struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Category: - // // *InfoTypeCategory_LocationCategory_ // *InfoTypeCategory_IndustryCategory_ // *InfoTypeCategory_TypeCategory_ @@ -5268,7 +5261,7 @@ type ListInfoTypesRequest struct { // // The format of this value is as follows: // - // locations/LOCATION_ID + // locations/LOCATION_ID Parent string `protobuf:"bytes,4,opt,name=parent,proto3" json:"parent,omitempty"` // BCP-47 language code for localized infoType friendly // names. If omitted, or if localized strings are not available, @@ -5472,7 +5465,6 @@ type QuasiId struct { // value. [required] // // Types that are assignable to Tag: - // // *QuasiId_InfoType // *QuasiId_CustomTag // *QuasiId_Inferred @@ -5661,7 +5653,6 @@ type PrivacyMetric struct { // Types of analysis. // // Types that are assignable to Type: - // // *PrivacyMetric_NumericalStatsConfig_ // *PrivacyMetric_CategoricalStatsConfig_ // *PrivacyMetric_KAnonymityConfig_ @@ -5811,7 +5802,6 @@ type AnalyzeDataSourceRiskDetails struct { // Values associated with this metric. // // Types that are assignable to Result: - // // *AnalyzeDataSourceRiskDetails_NumericalStatsResult_ // *AnalyzeDataSourceRiskDetails_CategoricalStatsResult_ // *AnalyzeDataSourceRiskDetails_KAnonymityResult_ @@ -6045,7 +6035,6 @@ type Value struct { // Value types // // Types that are assignable to Type: - // // *Value_IntegerValue // *Value_FloatValue // *Value_StringValue @@ -6149,7 +6138,7 @@ func (x *Value) GetDayOfWeekValue() dayofweek.DayOfWeek { if x, ok := x.GetType().(*Value_DayOfWeekValue); ok { return x.DayOfWeekValue } - return dayofweek.DayOfWeek_DAY_OF_WEEK_UNSPECIFIED + return dayofweek.DayOfWeek(0) } type isValue_Type interface { @@ -6221,7 +6210,6 @@ type QuoteInfo struct { // Object representation of the quote. // // Types that are assignable to ParsedQuote: - // // *QuoteInfo_DateTime ParsedQuote isQuoteInfo_ParsedQuote `protobuf_oneof:"parsed_quote"` } @@ -6344,7 +6332,7 @@ func (x *DateTime) GetDayOfWeek() dayofweek.DayOfWeek { if x != nil { return x.DayOfWeek } - return dayofweek.DayOfWeek_DAY_OF_WEEK_UNSPECIFIED + return dayofweek.DayOfWeek(0) } func (x *DateTime) GetTime() *timeofday.TimeOfDay { @@ -6368,7 +6356,6 @@ type DeidentifyConfig struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Transformation: - // // *DeidentifyConfig_InfoTypeTransformations // *DeidentifyConfig_RecordTransformations // *DeidentifyConfig_ImageTransformations @@ -6537,7 +6524,6 @@ type TransformationErrorHandling struct { // How transformation errors should be handled. // // Types that are assignable to Mode: - // // *TransformationErrorHandling_ThrowError_ // *TransformationErrorHandling_LeaveUntransformed_ Mode isTransformationErrorHandling_Mode `protobuf_oneof:"mode"` @@ -6621,7 +6607,6 @@ type PrimitiveTransformation struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Transformation: - // // *PrimitiveTransformation_ReplaceConfig // *PrimitiveTransformation_RedactConfig // *PrimitiveTransformation_CharacterMaskConfig @@ -7131,7 +7116,6 @@ type ReplaceDictionaryConfig struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Type: - // // *ReplaceDictionaryConfig_WordList Type isReplaceDictionaryConfig_Type `protobuf_oneof:"type"` } @@ -7283,7 +7267,6 @@ type CharsToIgnore struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Characters: - // // *CharsToIgnore_CharactersToSkip // *CharsToIgnore_CommonCharactersToIgnore Characters isCharsToIgnore_Characters `protobuf_oneof:"characters"` @@ -7658,7 +7641,6 @@ type CryptoReplaceFfxFpeConfig struct { // Choose an alphabet which the data being transformed will be made up of. // // Types that are assignable to Alphabet: - // // *CryptoReplaceFfxFpeConfig_CommonAlphabet // *CryptoReplaceFfxFpeConfig_CustomAlphabet // *CryptoReplaceFfxFpeConfig_Radix @@ -7820,7 +7802,6 @@ type CryptoKey struct { // Sources of crypto keys. // // Types that are assignable to Source: - // // *CryptoKey_Transient // *CryptoKey_Unwrapped // *CryptoKey_KmsWrapped @@ -8109,7 +8090,6 @@ type DateShiftConfig struct { // set, must also set context. Can only be applied to table items. // // Types that are assignable to Method: - // // *DateShiftConfig_CryptoKey Method isDateShiftConfig_Method `protobuf_oneof:"method"` } @@ -8271,7 +8251,6 @@ type FieldTransformation struct { // Transformation to apply. [required] // // Types that are assignable to Transformation: - // // *FieldTransformation_PrimitiveTransformation // *FieldTransformation_InfoTypeTransformations Transformation isFieldTransformation_Transformation `protobuf_oneof:"transformation"` @@ -8708,11 +8687,11 @@ type TransformationDescription struct { // to determine whether or not to apply this transformation. // // Examples: - // - (age_field > 85) - // - (age_field <= 18) - // - (zip_field exists) - // - (zip_field == 01234) && (city_field != "Springville") - // - (zip_field == 01234) && (age_field <= 18) && (city_field exists) + // * (age_field > 85) + // * (age_field <= 18) + // * (zip_field exists) + // * (zip_field == 01234) && (city_field != "Springville") + // * (zip_field == 01234) && (age_field <= 18) && (city_field exists) Condition string `protobuf:"bytes,3,opt,name=condition,proto3" json:"condition,omitempty"` // Set if the transformation was limited to a specific `InfoType`. InfoType *InfoType `protobuf:"bytes,4,opt,name=info_type,json=infoType,proto3" json:"info_type,omitempty"` @@ -8891,7 +8870,6 @@ type TransformationLocation struct { unknownFields protoimpl.UnknownFields // Types that are assignable to LocationType: - // // *TransformationLocation_FindingId // *TransformationLocation_RecordTransformation LocationType isTransformationLocation_LocationType `protobuf_oneof:"location_type"` @@ -9115,7 +9093,6 @@ type TransformationDetailsStorageConfig struct { // Location to store the transformation summary. // // Types that are assignable to Type: - // // *TransformationDetailsStorageConfig_Table Type isTransformationDetailsStorageConfig_Type `protobuf_oneof:"type"` } @@ -9189,7 +9166,6 @@ type Schedule struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Option: - // // *Schedule_RecurrencePeriodDuration Option isSchedule_Option `protobuf_oneof:"option"` } @@ -9575,7 +9551,6 @@ type JobTrigger struct { // The configuration details for the specific type of job to run. // // Types that are assignable to Job: - // // *JobTrigger_InspectJob Job isJobTrigger_Job `protobuf_oneof:"job"` // A list of triggers which will be OR'ed together. Only one in the list @@ -9725,7 +9700,6 @@ type Action struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Action: - // // *Action_SaveFindings_ // *Action_PubSub // *Action_PublishSummaryToCscc_ @@ -9974,20 +9948,20 @@ type CreateInspectTemplateRequest struct { // (project or organization) and whether you have [specified a processing // location](https://cloud.google.com/dlp/docs/specifying-location): // - // - Projects scope, location specified:
- // `projects/`PROJECT_ID`/locations/`LOCATION_ID - // - Projects scope, no location specified (defaults to global):
- // `projects/`PROJECT_ID - // - Organizations scope, location specified:
- // `organizations/`ORG_ID`/locations/`LOCATION_ID - // - Organizations scope, no location specified (defaults to global):
- // `organizations/`ORG_ID + // + Projects scope, location specified:
+ // `projects/`PROJECT_ID`/locations/`LOCATION_ID + // + Projects scope, no location specified (defaults to global):
+ // `projects/`PROJECT_ID + // + Organizations scope, location specified:
+ // `organizations/`ORG_ID`/locations/`LOCATION_ID + // + Organizations scope, no location specified (defaults to global):
+ // `organizations/`ORG_ID // // The following example `parent` string specifies a parent project with the // identifier `example-project`, and specifies the `europe-west3` location // for processing data: // - // parent=projects/example-project/locations/europe-west3 + // parent=projects/example-project/locations/europe-west3 Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // Required. The InspectTemplate to create. InspectTemplate *InspectTemplate `protobuf:"bytes,2,opt,name=inspect_template,json=inspectTemplate,proto3" json:"inspect_template,omitempty"` @@ -10192,20 +10166,20 @@ type ListInspectTemplatesRequest struct { // (project or organization) and whether you have [specified a processing // location](https://cloud.google.com/dlp/docs/specifying-location): // - // - Projects scope, location specified:
- // `projects/`PROJECT_ID`/locations/`LOCATION_ID - // - Projects scope, no location specified (defaults to global):
- // `projects/`PROJECT_ID - // - Organizations scope, location specified:
- // `organizations/`ORG_ID`/locations/`LOCATION_ID - // - Organizations scope, no location specified (defaults to global):
- // `organizations/`ORG_ID + // + Projects scope, location specified:
+ // `projects/`PROJECT_ID`/locations/`LOCATION_ID + // + Projects scope, no location specified (defaults to global):
+ // `projects/`PROJECT_ID + // + Organizations scope, location specified:
+ // `organizations/`ORG_ID`/locations/`LOCATION_ID + // + Organizations scope, no location specified (defaults to global):
+ // `organizations/`ORG_ID // // The following example `parent` string specifies a parent project with the // identifier `example-project`, and specifies the `europe-west3` location // for processing data: // - // parent=projects/example-project/locations/europe-west3 + // parent=projects/example-project/locations/europe-west3 Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // Page token to continue retrieval. Comes from previous call // to `ListInspectTemplates`. @@ -10420,16 +10394,16 @@ type CreateJobTriggerRequest struct { // processing // location](https://cloud.google.com/dlp/docs/specifying-location): // - // - Projects scope, location specified:
- // `projects/`PROJECT_ID`/locations/`LOCATION_ID - // - Projects scope, no location specified (defaults to global):
- // `projects/`PROJECT_ID + // + Projects scope, location specified:
+ // `projects/`PROJECT_ID`/locations/`LOCATION_ID + // + Projects scope, no location specified (defaults to global):
+ // `projects/`PROJECT_ID // // The following example `parent` string specifies a parent project with the // identifier `example-project`, and specifies the `europe-west3` location // for processing data: // - // parent=projects/example-project/locations/europe-west3 + // parent=projects/example-project/locations/europe-west3 Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // Required. The JobTrigger to create. JobTrigger *JobTrigger `protobuf:"bytes,2,opt,name=job_trigger,json=jobTrigger,proto3" json:"job_trigger,omitempty"` @@ -10684,21 +10658,20 @@ type CreateDlpJobRequest struct { // processing // location](https://cloud.google.com/dlp/docs/specifying-location): // - // - Projects scope, location specified:
- // `projects/`PROJECT_ID`/locations/`LOCATION_ID - // - Projects scope, no location specified (defaults to global):
- // `projects/`PROJECT_ID + // + Projects scope, location specified:
+ // `projects/`PROJECT_ID`/locations/`LOCATION_ID + // + Projects scope, no location specified (defaults to global):
+ // `projects/`PROJECT_ID // // The following example `parent` string specifies a parent project with the // identifier `example-project`, and specifies the `europe-west3` location // for processing data: // - // parent=projects/example-project/locations/europe-west3 + // parent=projects/example-project/locations/europe-west3 Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // The configuration details for the specific type of job to run. // // Types that are assignable to Job: - // // *CreateDlpJobRequest_InspectJob // *CreateDlpJobRequest_RiskJob Job isCreateDlpJobRequest_Job `protobuf_oneof:"job"` @@ -10816,16 +10789,16 @@ type ListJobTriggersRequest struct { // processing // location](https://cloud.google.com/dlp/docs/specifying-location): // - // - Projects scope, location specified:
- // `projects/`PROJECT_ID`/locations/`LOCATION_ID - // - Projects scope, no location specified (defaults to global):
- // `projects/`PROJECT_ID + // + Projects scope, location specified:
+ // `projects/`PROJECT_ID`/locations/`LOCATION_ID + // + Projects scope, no location specified (defaults to global):
+ // `projects/`PROJECT_ID // // The following example `parent` string specifies a parent project with the // identifier `example-project`, and specifies the `europe-west3` location // for processing data: // - // parent=projects/example-project/locations/europe-west3 + // parent=projects/example-project/locations/europe-west3 Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // Page token to continue retrieval. Comes from previous call // to ListJobTriggers. `order_by` field must not @@ -10858,12 +10831,11 @@ type ListJobTriggersRequest struct { // sequence of restrictions implicitly uses `AND`. // * A restriction has the form of `{field} {operator} {value}`. // * Supported fields/values for inspect triggers: - // - `status` - HEALTHY|PAUSED|CANCELLED - // - `inspected_storage` - DATASTORE|CLOUD_STORAGE|BIGQUERY - // - 'last_run_time` - RFC 3339 formatted timestamp, surrounded by + // - `status` - HEALTHY|PAUSED|CANCELLED + // - `inspected_storage` - DATASTORE|CLOUD_STORAGE|BIGQUERY + // - 'last_run_time` - RFC 3339 formatted timestamp, surrounded by // quotation marks. Nanoseconds are ignored. - // - 'error_count' - Number of errors that have occurred while running. - // + // - 'error_count' - Number of errors that have occurred while running. // * The operator must be `=` or `!=` for status and inspected_storage. // // Examples: @@ -11156,7 +11128,6 @@ type DataProfileAction struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Action: - // // *DataProfileAction_ExportData // *DataProfileAction_PubSubNotification_ Action isDataProfileAction_Action `protobuf_oneof:"action"` @@ -11341,7 +11312,6 @@ type DataProfileLocation struct { // The location to be scanned. // // Types that are assignable to Location: - // // *DataProfileLocation_OrganizationId // *DataProfileLocation_FolderId Location isDataProfileLocation_Location `protobuf_oneof:"location"` @@ -11431,7 +11401,6 @@ type DlpJob struct { // State of a job. State DlpJob_JobState `protobuf:"varint,3,opt,name=state,proto3,enum=google.privacy.dlp.v2.DlpJob_JobState" json:"state,omitempty"` // Types that are assignable to Details: - // // *DlpJob_RiskDetails // *DlpJob_InspectDetails Details isDlpJob_Details `protobuf_oneof:"details"` @@ -11636,16 +11605,16 @@ type ListDlpJobsRequest struct { // processing // location](https://cloud.google.com/dlp/docs/specifying-location): // - // - Projects scope, location specified:
- // `projects/`PROJECT_ID`/locations/`LOCATION_ID - // - Projects scope, no location specified (defaults to global):
- // `projects/`PROJECT_ID + // + Projects scope, location specified:
+ // `projects/`PROJECT_ID`/locations/`LOCATION_ID + // + Projects scope, no location specified (defaults to global):
+ // `projects/`PROJECT_ID // // The following example `parent` string specifies a parent project with the // identifier `example-project`, and specifies the `europe-west3` location // for processing data: // - // parent=projects/example-project/locations/europe-west3 + // parent=projects/example-project/locations/europe-west3 Parent string `protobuf:"bytes,4,opt,name=parent,proto3" json:"parent,omitempty"` // Allows filtering. // @@ -11656,17 +11625,15 @@ type ListDlpJobsRequest struct { // sequence of restrictions implicitly uses `AND`. // * A restriction has the form of `{field} {operator} {value}`. // * Supported fields/values for inspect jobs: - // - `state` - PENDING|RUNNING|CANCELED|FINISHED|FAILED - // - `inspected_storage` - DATASTORE|CLOUD_STORAGE|BIGQUERY - // - `trigger_name` - The name of the trigger that created the job. - // - 'end_time` - Corresponds to the time the job finished. - // - 'start_time` - Corresponds to the time the job finished. - // + // - `state` - PENDING|RUNNING|CANCELED|FINISHED|FAILED + // - `inspected_storage` - DATASTORE|CLOUD_STORAGE|BIGQUERY + // - `trigger_name` - The name of the trigger that created the job. + // - 'end_time` - Corresponds to the time the job finished. + // - 'start_time` - Corresponds to the time the job finished. // * Supported fields for risk analysis jobs: - // - `state` - RUNNING|CANCELED|FINISHED|FAILED - // - 'end_time` - Corresponds to the time the job finished. - // - 'start_time` - Corresponds to the time the job finished. - // + // - `state` - RUNNING|CANCELED|FINISHED|FAILED + // - 'end_time` - Corresponds to the time the job finished. + // - 'start_time` - Corresponds to the time the job finished. // * The operator must be `=` or `!=`. // // Examples: @@ -12000,20 +11967,20 @@ type CreateDeidentifyTemplateRequest struct { // (project or organization) and whether you have [specified a processing // location](https://cloud.google.com/dlp/docs/specifying-location): // - // - Projects scope, location specified:
- // `projects/`PROJECT_ID`/locations/`LOCATION_ID - // - Projects scope, no location specified (defaults to global):
- // `projects/`PROJECT_ID - // - Organizations scope, location specified:
- // `organizations/`ORG_ID`/locations/`LOCATION_ID - // - Organizations scope, no location specified (defaults to global):
- // `organizations/`ORG_ID + // + Projects scope, location specified:
+ // `projects/`PROJECT_ID`/locations/`LOCATION_ID + // + Projects scope, no location specified (defaults to global):
+ // `projects/`PROJECT_ID + // + Organizations scope, location specified:
+ // `organizations/`ORG_ID`/locations/`LOCATION_ID + // + Organizations scope, no location specified (defaults to global):
+ // `organizations/`ORG_ID // // The following example `parent` string specifies a parent project with the // identifier `example-project`, and specifies the `europe-west3` location // for processing data: // - // parent=projects/example-project/locations/europe-west3 + // parent=projects/example-project/locations/europe-west3 Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // Required. The DeidentifyTemplate to create. DeidentifyTemplate *DeidentifyTemplate `protobuf:"bytes,2,opt,name=deidentify_template,json=deidentifyTemplate,proto3" json:"deidentify_template,omitempty"` @@ -12218,20 +12185,20 @@ type ListDeidentifyTemplatesRequest struct { // (project or organization) and whether you have [specified a processing // location](https://cloud.google.com/dlp/docs/specifying-location): // - // - Projects scope, location specified:
- // `projects/`PROJECT_ID`/locations/`LOCATION_ID - // - Projects scope, no location specified (defaults to global):
- // `projects/`PROJECT_ID - // - Organizations scope, location specified:
- // `organizations/`ORG_ID`/locations/`LOCATION_ID - // - Organizations scope, no location specified (defaults to global):
- // `organizations/`ORG_ID + // + Projects scope, location specified:
+ // `projects/`PROJECT_ID`/locations/`LOCATION_ID + // + Projects scope, no location specified (defaults to global):
+ // `projects/`PROJECT_ID + // + Organizations scope, location specified:
+ // `organizations/`ORG_ID`/locations/`LOCATION_ID + // + Organizations scope, no location specified (defaults to global):
+ // `organizations/`ORG_ID // // The following example `parent` string specifies a parent project with the // identifier `example-project`, and specifies the `europe-west3` location // for processing data: // - // parent=projects/example-project/locations/europe-west3 + // parent=projects/example-project/locations/europe-west3 Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // Page token to continue retrieval. Comes from previous call // to `ListDeidentifyTemplates`. @@ -12452,7 +12419,6 @@ type LargeCustomDictionaryConfig struct { // longer be used. OutputPath *CloudStoragePath `protobuf:"bytes,1,opt,name=output_path,json=outputPath,proto3" json:"output_path,omitempty"` // Types that are assignable to Source: - // // *LargeCustomDictionaryConfig_CloudStorageFileSet // *LargeCustomDictionaryConfig_BigQueryField Source isLargeCustomDictionaryConfig_Source `protobuf_oneof:"source"` @@ -12600,7 +12566,6 @@ type StoredInfoTypeConfig struct { // Stored infotype types. // // Types that are assignable to Type: - // // *StoredInfoTypeConfig_LargeCustomDictionary // *StoredInfoTypeConfig_Dictionary // *StoredInfoTypeConfig_Regex @@ -12715,7 +12680,6 @@ type StoredInfoTypeStats struct { // Stat types // // Types that are assignable to Type: - // // *StoredInfoTypeStats_LargeCustomDictionary Type isStoredInfoTypeStats_Type `protobuf_oneof:"type"` } @@ -12958,20 +12922,20 @@ type CreateStoredInfoTypeRequest struct { // (project or organization) and whether you have [specified a processing // location](https://cloud.google.com/dlp/docs/specifying-location): // - // - Projects scope, location specified:
- // `projects/`PROJECT_ID`/locations/`LOCATION_ID - // - Projects scope, no location specified (defaults to global):
- // `projects/`PROJECT_ID - // - Organizations scope, location specified:
- // `organizations/`ORG_ID`/locations/`LOCATION_ID - // - Organizations scope, no location specified (defaults to global):
- // `organizations/`ORG_ID + // + Projects scope, location specified:
+ // `projects/`PROJECT_ID`/locations/`LOCATION_ID + // + Projects scope, no location specified (defaults to global):
+ // `projects/`PROJECT_ID + // + Organizations scope, location specified:
+ // `organizations/`ORG_ID`/locations/`LOCATION_ID + // + Organizations scope, no location specified (defaults to global):
+ // `organizations/`ORG_ID // // The following example `parent` string specifies a parent project with the // identifier `example-project`, and specifies the `europe-west3` location // for processing data: // - // parent=projects/example-project/locations/europe-west3 + // parent=projects/example-project/locations/europe-west3 Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // Required. Configuration of the storedInfoType to create. Config *StoredInfoTypeConfig `protobuf:"bytes,2,opt,name=config,proto3" json:"config,omitempty"` @@ -13178,16 +13142,16 @@ type ListStoredInfoTypesRequest struct { // (project or organization) and whether you have [specified a processing // location](https://cloud.google.com/dlp/docs/specifying-location): // - // - Projects scope, location specified:
- // `projects/`PROJECT_ID`/locations/`LOCATION_ID - // - Projects scope, no location specified (defaults to global):
- // `projects/`PROJECT_ID + // + Projects scope, location specified:
+ // `projects/`PROJECT_ID`/locations/`LOCATION_ID + // + Projects scope, no location specified (defaults to global):
+ // `projects/`PROJECT_ID // // The following example `parent` string specifies a parent project with the // identifier `example-project`, and specifies the `europe-west3` location // for processing data: // - // parent=projects/example-project/locations/europe-west3 + // parent=projects/example-project/locations/europe-west3 Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // Page token to continue retrieval. Comes from previous call // to `ListStoredInfoTypes`. @@ -14582,7 +14546,6 @@ type RedactImageRequest_ImageRedactionConfig struct { // Type of information to redact from images. // // Types that are assignable to Target: - // // *RedactImageRequest_ImageRedactionConfig_InfoType // *RedactImageRequest_ImageRedactionConfig_RedactAllText Target isRedactImageRequest_ImageRedactionConfig_Target `protobuf_oneof:"target"` @@ -15272,7 +15235,6 @@ type PrivacyMetric_KMapEstimationConfig_TaggedField struct { // value. [required] // // Types that are assignable to Tag: - // // *PrivacyMetric_KMapEstimationConfig_TaggedField_InfoType // *PrivacyMetric_KMapEstimationConfig_TaggedField_CustomTag // *PrivacyMetric_KMapEstimationConfig_TaggedField_Inferred @@ -15739,11 +15701,9 @@ type AnalyzeDataSourceRiskDetails_KMapEstimationResult struct { // The intervals [min_anonymity, max_anonymity] do not overlap. If a value // doesn't correspond to any such interval, the associated frequency is // zero. For example, the following records: - // - // {min_anonymity: 1, max_anonymity: 1, frequency: 17} - // {min_anonymity: 2, max_anonymity: 3, frequency: 42} - // {min_anonymity: 5, max_anonymity: 10, frequency: 99} - // + // {min_anonymity: 1, max_anonymity: 1, frequency: 17} + // {min_anonymity: 2, max_anonymity: 3, frequency: 42} + // {min_anonymity: 5, max_anonymity: 10, frequency: 99} // mean that there are no record with an estimated anonymity of 4, 5, or // larger than 10. KMapEstimationHistogram []*AnalyzeDataSourceRiskDetails_KMapEstimationResult_KMapEstimationHistogramBucket `protobuf:"bytes,1,rep,name=k_map_estimation_histogram,json=kMapEstimationHistogram,proto3" json:"k_map_estimation_histogram,omitempty"` @@ -15798,11 +15758,9 @@ type AnalyzeDataSourceRiskDetails_DeltaPresenceEstimationResult struct { // The intervals [min_probability, max_probability) do not overlap. If a // value doesn't correspond to any such interval, the associated frequency // is zero. For example, the following records: - // - // {min_probability: 0, max_probability: 0.1, frequency: 17} - // {min_probability: 0.2, max_probability: 0.3, frequency: 42} - // {min_probability: 0.3, max_probability: 0.4, frequency: 99} - // + // {min_probability: 0, max_probability: 0.1, frequency: 17} + // {min_probability: 0.2, max_probability: 0.3, frequency: 42} + // {min_probability: 0.3, max_probability: 0.4, frequency: 99} // mean that there are no record with an estimated probability in [0.1, 0.2) // nor larger or equal to 0.4. DeltaPresenceEstimationHistogram []*AnalyzeDataSourceRiskDetails_DeltaPresenceEstimationResult_DeltaPresenceEstimationHistogramBucket `protobuf:"bytes,1,rep,name=delta_presence_estimation_histogram,json=deltaPresenceEstimationHistogram,proto3" json:"delta_presence_estimation_histogram,omitempty"` @@ -16670,7 +16628,6 @@ type ImageTransformations_ImageTransformation struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Target: - // // *ImageTransformations_ImageTransformation_SelectedInfoTypes_ // *ImageTransformations_ImageTransformation_AllInfoTypes_ // *ImageTransformations_ImageTransformation_AllText_ @@ -17262,7 +17219,6 @@ type RecordCondition_Expressions struct { // Expression types. // // Types that are assignable to Type: - // // *RecordCondition_Expressions_Conditions Type isRecordCondition_Expressions_Type `protobuf_oneof:"type"` } @@ -17407,7 +17363,6 @@ type JobTrigger_Trigger struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Trigger: - // // *JobTrigger_Trigger_Schedule // *JobTrigger_Trigger_Manual Trigger isJobTrigger_Trigger_Trigger `protobuf_oneof:"trigger"` @@ -17727,7 +17682,6 @@ type Action_Deidentify struct { // message for more information about what is noted). TransformationDetailsStorageConfig *TransformationDetailsStorageConfig `protobuf:"bytes,3,opt,name=transformation_details_storage_config,json=transformationDetailsStorageConfig,proto3" json:"transformation_details_storage_config,omitempty"` // Types that are assignable to Output: - // // *Action_Deidentify_CloudStorageOutput Output isAction_Deidentify_Output `protobuf_oneof:"output"` // List of user-specified file type groups to transform. If specified, only @@ -18050,7 +18004,6 @@ type DataProfilePubSubCondition_PubSubCondition struct { // The value for the condition to trigger. // // Types that are assignable to Value: - // // *DataProfilePubSubCondition_PubSubCondition_MinimumRiskScore // *DataProfilePubSubCondition_PubSubCondition_MinimumSensitivityScore Value isDataProfilePubSubCondition_PubSubCondition_Value `protobuf_oneof:"value"` diff --git a/dlp/apiv2/dlppb/storage.pb.go b/dlp/apiv2/dlppb/storage.pb.go index 59207c4dd678..18bd758b2f01 100644 --- a/dlp/apiv2/dlppb/storage.pb.go +++ b/dlp/apiv2/dlppb/storage.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/privacy/dlp/v2/storage.proto package dlppb @@ -115,52 +115,42 @@ const ( // FileType's in your storage scan. FileType_BINARY_FILE FileType = 1 // Included file extensions: - // - // asc,asp, aspx, brf, c, cc,cfm, cgi, cpp, csv, cxx, c++, cs, css, dart, - // dat, dot, eml,, epbub, ged, go, h, hh, hpp, hxx, h++, hs, html, htm, - // mkd, markdown, m, ml, mli, perl, pl, plist, pm, php, phtml, pht, - // properties, py, pyw, rb, rbw, rs, rss, rc, scala, sh, sql, swift, tex, - // shtml, shtm, xhtml, lhs, ics, ini, java, js, json, kix, kml, ocaml, md, - // txt, text, tsv, vb, vcard, vcs, wml, xcodeproj, xml, xsl, xsd, yml, yaml. + // asc,asp, aspx, brf, c, cc,cfm, cgi, cpp, csv, cxx, c++, cs, css, dart, + // dat, dot, eml,, epbub, ged, go, h, hh, hpp, hxx, h++, hs, html, htm, + // mkd, markdown, m, ml, mli, perl, pl, plist, pm, php, phtml, pht, + // properties, py, pyw, rb, rbw, rs, rss, rc, scala, sh, sql, swift, tex, + // shtml, shtm, xhtml, lhs, ics, ini, java, js, json, kix, kml, ocaml, md, + // txt, text, tsv, vb, vcard, vcs, wml, xcodeproj, xml, xsl, xsd, yml, yaml. FileType_TEXT_FILE FileType = 2 // Included file extensions: - // - // bmp, gif, jpg, jpeg, jpe, png. - // + // bmp, gif, jpg, jpeg, jpe, png. // bytes_limit_per_file has no effect on image files. // Image inspection is restricted to 'global', 'us', 'asia', and 'europe'. FileType_IMAGE FileType = 3 // Word files >30 MB will be scanned as binary files. // Included file extensions: - // - // docx, dotx, docm, dotm + // docx, dotx, docm, dotm FileType_WORD FileType = 5 // PDF files >30 MB will be scanned as binary files. // Included file extensions: - // - // pdf + // pdf FileType_PDF FileType = 6 // Included file extensions: - // - // avro + // avro FileType_AVRO FileType = 7 // Included file extensions: - // - // csv + // csv FileType_CSV FileType = 8 // Included file extensions: - // - // tsv + // tsv FileType_TSV FileType = 9 // Powerpoint files >30 MB will be scanned as binary files. // Included file extensions: - // - // pptx, pptm, potx, potm, pot + // pptx, pptm, potx, potm, pot FileType_POWERPOINT FileType = 11 // Excel files >30 MB will be scanned as binary files. // Included file extensions: - // - // xlsx, xlsm, xltx, xltm + // xlsx, xlsm, xltx, xltm FileType_EXCEL FileType = 12 ) @@ -634,7 +624,6 @@ type CustomInfoType struct { // the rule. Defaults to `VERY_LIKELY` if not specified. Likelihood Likelihood `protobuf:"varint,6,opt,name=likelihood,proto3,enum=google.privacy.dlp.v2.Likelihood" json:"likelihood,omitempty"` // Types that are assignable to Type: - // // *CustomInfoType_Dictionary_ // *CustomInfoType_Regex_ // *CustomInfoType_SurrogateType_ @@ -1440,7 +1429,6 @@ type StorageConfig struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Type: - // // *StorageConfig_DatastoreOptions // *StorageConfig_CloudStorageOptions // *StorageConfig_BigQueryOptions @@ -1842,7 +1830,6 @@ type RecordKey struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Type: - // // *RecordKey_DatastoreKey // *RecordKey_BigQueryKey Type isRecordKey_Type `protobuf_oneof:"type"` @@ -2191,7 +2178,6 @@ type CustomInfoType_Dictionary struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Source: - // // *CustomInfoType_Dictionary_WordList_ // *CustomInfoType_Dictionary_CloudStoragePath Source isCustomInfoType_Dictionary_Source `protobuf_oneof:"source"` @@ -2386,7 +2372,6 @@ type CustomInfoType_DetectionRule struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Type: - // // *CustomInfoType_DetectionRule_HotwordRule_ Type isCustomInfoType_DetectionRule_Type `protobuf_oneof:"type"` } @@ -2570,7 +2555,6 @@ type CustomInfoType_DetectionRule_LikelihoodAdjustment struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Adjustment: - // // *CustomInfoType_DetectionRule_LikelihoodAdjustment_FixedLikelihood // *CustomInfoType_DetectionRule_LikelihoodAdjustment_RelativeLikelihood Adjustment isCustomInfoType_DetectionRule_LikelihoodAdjustment_Adjustment `protobuf_oneof:"adjustment"` @@ -2937,7 +2921,6 @@ type Key_PathElement struct { // The type of ID. // // Types that are assignable to IdType: - // // *Key_PathElement_Id // *Key_PathElement_Name IdType isKey_PathElement_IdType `protobuf_oneof:"id_type"` diff --git a/dlp/apiv2/doc.go b/dlp/apiv2/doc.go index e30513e1235f..cc69abd93979 100644 --- a/dlp/apiv2/doc.go +++ b/dlp/apiv2/doc.go @@ -82,6 +82,8 @@ package dlp // import "cloud.google.com/go/dlp/apiv2" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -170,3 +172,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/dlp/apiv2/gapic_metadata.json b/dlp/apiv2/gapic_metadata.json index fa53d4da4be2..05a44520ff53 100644 --- a/dlp/apiv2/gapic_metadata.json +++ b/dlp/apiv2/gapic_metadata.json @@ -181,6 +181,181 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "ActivateJobTrigger": { + "methods": [ + "ActivateJobTrigger" + ] + }, + "CancelDlpJob": { + "methods": [ + "CancelDlpJob" + ] + }, + "CreateDeidentifyTemplate": { + "methods": [ + "CreateDeidentifyTemplate" + ] + }, + "CreateDlpJob": { + "methods": [ + "CreateDlpJob" + ] + }, + "CreateInspectTemplate": { + "methods": [ + "CreateInspectTemplate" + ] + }, + "CreateJobTrigger": { + "methods": [ + "CreateJobTrigger" + ] + }, + "CreateStoredInfoType": { + "methods": [ + "CreateStoredInfoType" + ] + }, + "DeidentifyContent": { + "methods": [ + "DeidentifyContent" + ] + }, + "DeleteDeidentifyTemplate": { + "methods": [ + "DeleteDeidentifyTemplate" + ] + }, + "DeleteDlpJob": { + "methods": [ + "DeleteDlpJob" + ] + }, + "DeleteInspectTemplate": { + "methods": [ + "DeleteInspectTemplate" + ] + }, + "DeleteJobTrigger": { + "methods": [ + "DeleteJobTrigger" + ] + }, + "DeleteStoredInfoType": { + "methods": [ + "DeleteStoredInfoType" + ] + }, + "FinishDlpJob": { + "methods": [ + "FinishDlpJob" + ] + }, + "GetDeidentifyTemplate": { + "methods": [ + "GetDeidentifyTemplate" + ] + }, + "GetDlpJob": { + "methods": [ + "GetDlpJob" + ] + }, + "GetInspectTemplate": { + "methods": [ + "GetInspectTemplate" + ] + }, + "GetJobTrigger": { + "methods": [ + "GetJobTrigger" + ] + }, + "GetStoredInfoType": { + "methods": [ + "GetStoredInfoType" + ] + }, + "HybridInspectDlpJob": { + "methods": [ + "HybridInspectDlpJob" + ] + }, + "HybridInspectJobTrigger": { + "methods": [ + "HybridInspectJobTrigger" + ] + }, + "InspectContent": { + "methods": [ + "InspectContent" + ] + }, + "ListDeidentifyTemplates": { + "methods": [ + "ListDeidentifyTemplates" + ] + }, + "ListDlpJobs": { + "methods": [ + "ListDlpJobs" + ] + }, + "ListInfoTypes": { + "methods": [ + "ListInfoTypes" + ] + }, + "ListInspectTemplates": { + "methods": [ + "ListInspectTemplates" + ] + }, + "ListJobTriggers": { + "methods": [ + "ListJobTriggers" + ] + }, + "ListStoredInfoTypes": { + "methods": [ + "ListStoredInfoTypes" + ] + }, + "RedactImage": { + "methods": [ + "RedactImage" + ] + }, + "ReidentifyContent": { + "methods": [ + "ReidentifyContent" + ] + }, + "UpdateDeidentifyTemplate": { + "methods": [ + "UpdateDeidentifyTemplate" + ] + }, + "UpdateInspectTemplate": { + "methods": [ + "UpdateInspectTemplate" + ] + }, + "UpdateJobTrigger": { + "methods": [ + "UpdateJobTrigger" + ] + }, + "UpdateStoredInfoType": { + "methods": [ + "UpdateStoredInfoType" + ] + } + } } } } diff --git a/documentai/apiv1/doc.go b/documentai/apiv1/doc.go index c0d908fb3242..ef0569992358 100644 --- a/documentai/apiv1/doc.go +++ b/documentai/apiv1/doc.go @@ -82,6 +82,8 @@ package documentai // import "cloud.google.com/go/documentai/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -170,3 +172,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/documentai/apiv1/document_processor_client.go b/documentai/apiv1/document_processor_client.go index cfb36799774c..ad1631421baf 100644 --- a/documentai/apiv1/document_processor_client.go +++ b/documentai/apiv1/document_processor_client.go @@ -17,9 +17,12 @@ package documentai import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,15 +30,18 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -139,6 +145,63 @@ func defaultDocumentProcessorCallOptions() *DocumentProcessorCallOptions { } } +func defaultDocumentProcessorRESTCallOptions() *DocumentProcessorCallOptions { + return &DocumentProcessorCallOptions{ + ProcessDocument: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + BatchProcessDocuments: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + FetchProcessorTypes: []gax.CallOption{}, + ListProcessorTypes: []gax.CallOption{}, + ListProcessors: []gax.CallOption{}, + GetProcessor: []gax.CallOption{}, + GetProcessorVersion: []gax.CallOption{}, + ListProcessorVersions: []gax.CallOption{}, + DeleteProcessorVersion: []gax.CallOption{}, + DeployProcessorVersion: []gax.CallOption{}, + UndeployProcessorVersion: []gax.CallOption{}, + CreateProcessor: []gax.CallOption{}, + DeleteProcessor: []gax.CallOption{}, + EnableProcessor: []gax.CallOption{}, + DisableProcessor: []gax.CallOption{}, + SetDefaultProcessorVersion: []gax.CallOption{}, + ReviewDocument: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + CancelOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalDocumentProcessorClient is an interface that defines the methods available from Cloud Document AI API. type internalDocumentProcessorClient interface { Close() error @@ -498,6 +561,92 @@ func (c *documentProcessorGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type documentProcessorRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing DocumentProcessorClient + CallOptions **DocumentProcessorCallOptions +} + +// NewDocumentProcessorRESTClient creates a new document processor service rest client. +// +// Service to call Cloud DocumentAI to process documents according to the +// processor’s definition. Processors are built using state-of-the-art Google +// AI such as natural language, computer vision, and translation to extract +// structured information from unstructured or semi-structured documents. +func NewDocumentProcessorRESTClient(ctx context.Context, opts ...option.ClientOption) (*DocumentProcessorClient, error) { + clientOpts := append(defaultDocumentProcessorRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultDocumentProcessorRESTCallOptions() + c := &documentProcessorRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &DocumentProcessorClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultDocumentProcessorRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://documentai.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://documentai.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://documentai.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *documentProcessorRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *documentProcessorRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *documentProcessorRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *documentProcessorGRPCClient) ProcessDocument(ctx context.Context, req *documentaipb.ProcessRequest, opts ...gax.CallOption) (*documentaipb.ProcessResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 120000*time.Millisecond) @@ -1041,136 +1190,1676 @@ func (c *documentProcessorGRPCClient) ListOperations(ctx context.Context, req *l return it } -// BatchProcessDocumentsOperation manages a long-running operation from BatchProcessDocuments. -type BatchProcessDocumentsOperation struct { - lro *longrunning.Operation -} - -// BatchProcessDocumentsOperation returns a new BatchProcessDocumentsOperation from a given name. -// The name must be that of a previously created BatchProcessDocumentsOperation, possibly from a different process. -func (c *documentProcessorGRPCClient) BatchProcessDocumentsOperation(name string) *BatchProcessDocumentsOperation { - return &BatchProcessDocumentsOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), +// ProcessDocument processes a single document. +func (c *documentProcessorRESTClient) ProcessDocument(ctx context.Context, req *documentaipb.ProcessRequest, opts ...gax.CallOption) (*documentaipb.ProcessResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err } -} -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *BatchProcessDocumentsOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*documentaipb.BatchProcessResponse, error) { - var resp documentaipb.BatchProcessResponse - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - return &resp, nil + baseUrl.Path += fmt.Sprintf("/v1/%v:process", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).ProcessDocument[0:len((*c.CallOptions).ProcessDocument):len((*c.CallOptions).ProcessDocument)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &documentaipb.ProcessResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil } -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *BatchProcessDocumentsOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*documentaipb.BatchProcessResponse, error) { - var resp documentaipb.BatchProcessResponse - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { +// BatchProcessDocuments lRO endpoint to batch process many documents. The output is written +// to Cloud Storage as JSON in the [Document] format. +func (c *documentProcessorRESTClient) BatchProcessDocuments(ctx context.Context, req *documentaipb.BatchProcessRequest, opts ...gax.CallOption) (*BatchProcessDocumentsOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { return nil, err } - if !op.Done() { - return nil, nil - } - return &resp, nil -} -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *BatchProcessDocumentsOperation) Metadata() (*documentaipb.BatchProcessMetadata, error) { - var meta documentaipb.BatchProcessMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - return &meta, nil -} + baseUrl.Path += fmt.Sprintf("/v1/%v:batchProcess", req.GetName()) -// Done reports whether the long-running operation has completed. -func (op *BatchProcessDocumentsOperation) Done() bool { - return op.lro.Done() -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") -// 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 *BatchProcessDocumentsOperation) Name() string { - return op.lro.Name() -} + baseUrl.RawQuery = params.Encode() -// DeleteProcessorOperation manages a long-running operation from DeleteProcessor. -type DeleteProcessorOperation struct { - lro *longrunning.Operation -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) -// DeleteProcessorOperation returns a new DeleteProcessorOperation from a given name. -// The name must be that of a previously created DeleteProcessorOperation, possibly from a different process. -func (c *documentProcessorGRPCClient) DeleteProcessorOperation(name string) *DeleteProcessorOperation { - return &DeleteProcessorOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *DeleteProcessorOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { - return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) -} + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *DeleteProcessorOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { - return op.lro.Poll(ctx, nil, opts...) + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &BatchProcessDocumentsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil } -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *DeleteProcessorOperation) Metadata() (*documentaipb.DeleteProcessorMetadata, error) { - var meta documentaipb.DeleteProcessorMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { +// FetchProcessorTypes fetches processor types. Note that we do not use ListProcessorTypes here +// because it is not paginated. +func (c *documentProcessorRESTClient) FetchProcessorTypes(ctx context.Context, req *documentaipb.FetchProcessorTypesRequest, opts ...gax.CallOption) (*documentaipb.FetchProcessorTypesResponse, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - return &meta, nil -} + baseUrl.Path += fmt.Sprintf("/v1/%v:fetchProcessorTypes", req.GetParent()) -// Done reports whether the long-running operation has completed. -func (op *DeleteProcessorOperation) Done() bool { - return op.lro.Done() -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") -// 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. + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).FetchProcessorTypes[0:len((*c.CallOptions).FetchProcessorTypes):len((*c.CallOptions).FetchProcessorTypes)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &documentaipb.FetchProcessorTypesResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListProcessorTypes lists the processor types that exist. +func (c *documentProcessorRESTClient) ListProcessorTypes(ctx context.Context, req *documentaipb.ListProcessorTypesRequest, opts ...gax.CallOption) *ProcessorTypeIterator { + it := &ProcessorTypeIterator{} + req = proto.Clone(req).(*documentaipb.ListProcessorTypesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*documentaipb.ProcessorType, string, error) { + resp := &documentaipb.ListProcessorTypesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/processorTypes", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetProcessorTypes(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// ListProcessors lists all processors which belong to this project. +func (c *documentProcessorRESTClient) ListProcessors(ctx context.Context, req *documentaipb.ListProcessorsRequest, opts ...gax.CallOption) *ProcessorIterator { + it := &ProcessorIterator{} + req = proto.Clone(req).(*documentaipb.ListProcessorsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*documentaipb.Processor, string, error) { + resp := &documentaipb.ListProcessorsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/processors", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetProcessors(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetProcessor gets a processor detail. +func (c *documentProcessorRESTClient) GetProcessor(ctx context.Context, req *documentaipb.GetProcessorRequest, opts ...gax.CallOption) (*documentaipb.Processor, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetProcessor[0:len((*c.CallOptions).GetProcessor):len((*c.CallOptions).GetProcessor)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &documentaipb.Processor{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetProcessorVersion gets a processor version detail. +func (c *documentProcessorRESTClient) GetProcessorVersion(ctx context.Context, req *documentaipb.GetProcessorVersionRequest, opts ...gax.CallOption) (*documentaipb.ProcessorVersion, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetProcessorVersion[0:len((*c.CallOptions).GetProcessorVersion):len((*c.CallOptions).GetProcessorVersion)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &documentaipb.ProcessorVersion{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListProcessorVersions lists all versions of a processor. +func (c *documentProcessorRESTClient) ListProcessorVersions(ctx context.Context, req *documentaipb.ListProcessorVersionsRequest, opts ...gax.CallOption) *ProcessorVersionIterator { + it := &ProcessorVersionIterator{} + req = proto.Clone(req).(*documentaipb.ListProcessorVersionsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*documentaipb.ProcessorVersion, string, error) { + resp := &documentaipb.ListProcessorVersionsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/processorVersions", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetProcessorVersions(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// DeleteProcessorVersion deletes the processor version, all artifacts under the processor version +// will be deleted. +func (c *documentProcessorRESTClient) DeleteProcessorVersion(ctx context.Context, req *documentaipb.DeleteProcessorVersionRequest, opts ...gax.CallOption) (*DeleteProcessorVersionOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteProcessorVersionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeployProcessorVersion deploys the processor version. +func (c *documentProcessorRESTClient) DeployProcessorVersion(ctx context.Context, req *documentaipb.DeployProcessorVersionRequest, opts ...gax.CallOption) (*DeployProcessorVersionOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:deploy", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeployProcessorVersionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UndeployProcessorVersion undeploys the processor version. +func (c *documentProcessorRESTClient) UndeployProcessorVersion(ctx context.Context, req *documentaipb.UndeployProcessorVersionRequest, opts ...gax.CallOption) (*UndeployProcessorVersionOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:undeploy", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UndeployProcessorVersionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// CreateProcessor creates a processor from the type processor that the user chose. +// The processor will be at “ENABLED” state by default after its creation. +func (c *documentProcessorRESTClient) CreateProcessor(ctx context.Context, req *documentaipb.CreateProcessorRequest, opts ...gax.CallOption) (*documentaipb.Processor, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetProcessor() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/processors", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateProcessor[0:len((*c.CallOptions).CreateProcessor):len((*c.CallOptions).CreateProcessor)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &documentaipb.Processor{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteProcessor deletes the processor, unloads all deployed model artifacts if it was +// enabled and then deletes all artifacts associated with this processor. +func (c *documentProcessorRESTClient) DeleteProcessor(ctx context.Context, req *documentaipb.DeleteProcessorRequest, opts ...gax.CallOption) (*DeleteProcessorOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteProcessorOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// EnableProcessor enables a processor +func (c *documentProcessorRESTClient) EnableProcessor(ctx context.Context, req *documentaipb.EnableProcessorRequest, opts ...gax.CallOption) (*EnableProcessorOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:enable", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &EnableProcessorOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DisableProcessor disables a processor +func (c *documentProcessorRESTClient) DisableProcessor(ctx context.Context, req *documentaipb.DisableProcessorRequest, opts ...gax.CallOption) (*DisableProcessorOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:disable", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DisableProcessorOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// SetDefaultProcessorVersion set the default (active) version of a Processor that will be used in +// ProcessDocument and +// BatchProcessDocuments. +func (c *documentProcessorRESTClient) SetDefaultProcessorVersion(ctx context.Context, req *documentaipb.SetDefaultProcessorVersionRequest, opts ...gax.CallOption) (*SetDefaultProcessorVersionOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:setDefaultProcessorVersion", req.GetProcessor()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "processor", url.QueryEscape(req.GetProcessor()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &SetDefaultProcessorVersionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ReviewDocument send a document for Human Review. The input document should be processed by +// the specified processor. +func (c *documentProcessorRESTClient) ReviewDocument(ctx context.Context, req *documentaipb.ReviewDocumentRequest, opts ...gax.CallOption) (*ReviewDocumentOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:reviewDocument", req.GetHumanReviewConfig()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "human_review_config", url.QueryEscape(req.GetHumanReviewConfig()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &ReviewDocumentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetLocation gets information about a location. +func (c *documentProcessorRESTClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *documentProcessorRESTClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *documentProcessorRESTClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *documentProcessorRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *documentProcessorRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// BatchProcessDocumentsOperation manages a long-running operation from BatchProcessDocuments. +type BatchProcessDocumentsOperation struct { + lro *longrunning.Operation + pollPath string +} + +// BatchProcessDocumentsOperation returns a new BatchProcessDocumentsOperation from a given name. +// The name must be that of a previously created BatchProcessDocumentsOperation, possibly from a different process. +func (c *documentProcessorGRPCClient) BatchProcessDocumentsOperation(name string) *BatchProcessDocumentsOperation { + return &BatchProcessDocumentsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// BatchProcessDocumentsOperation returns a new BatchProcessDocumentsOperation from a given name. +// The name must be that of a previously created BatchProcessDocumentsOperation, possibly from a different process. +func (c *documentProcessorRESTClient) BatchProcessDocumentsOperation(name string) *BatchProcessDocumentsOperation { + override := fmt.Sprintf("/v1/%s", name) + return &BatchProcessDocumentsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *BatchProcessDocumentsOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*documentaipb.BatchProcessResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp documentaipb.BatchProcessResponse + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *BatchProcessDocumentsOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*documentaipb.BatchProcessResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp documentaipb.BatchProcessResponse + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *BatchProcessDocumentsOperation) Metadata() (*documentaipb.BatchProcessMetadata, error) { + var meta documentaipb.BatchProcessMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *BatchProcessDocumentsOperation) Done() bool { + return op.lro.Done() +} + +// 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 *BatchProcessDocumentsOperation) Name() string { + return op.lro.Name() +} + +// DeleteProcessorOperation manages a long-running operation from DeleteProcessor. +type DeleteProcessorOperation struct { + lro *longrunning.Operation + pollPath string +} + +// DeleteProcessorOperation returns a new DeleteProcessorOperation from a given name. +// The name must be that of a previously created DeleteProcessorOperation, possibly from a different process. +func (c *documentProcessorGRPCClient) DeleteProcessorOperation(name string) *DeleteProcessorOperation { + return &DeleteProcessorOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// DeleteProcessorOperation returns a new DeleteProcessorOperation from a given name. +// The name must be that of a previously created DeleteProcessorOperation, possibly from a different process. +func (c *documentProcessorRESTClient) DeleteProcessorOperation(name string) *DeleteProcessorOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteProcessorOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *DeleteProcessorOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *DeleteProcessorOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + return op.lro.Poll(ctx, nil, opts...) +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *DeleteProcessorOperation) Metadata() (*documentaipb.DeleteProcessorMetadata, error) { + var meta documentaipb.DeleteProcessorMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *DeleteProcessorOperation) Done() bool { + return op.lro.Done() +} + +// 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 *DeleteProcessorOperation) Name() string { return op.lro.Name() } // DeleteProcessorVersionOperation manages a long-running operation from DeleteProcessorVersion. type DeleteProcessorVersionOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteProcessorVersionOperation returns a new DeleteProcessorVersionOperation from a given name. @@ -1181,10 +2870,21 @@ func (c *documentProcessorGRPCClient) DeleteProcessorVersionOperation(name strin } } +// DeleteProcessorVersionOperation returns a new DeleteProcessorVersionOperation from a given name. +// The name must be that of a previously created DeleteProcessorVersionOperation, possibly from a different process. +func (c *documentProcessorRESTClient) DeleteProcessorVersionOperation(name string) *DeleteProcessorVersionOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteProcessorVersionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteProcessorVersionOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -1198,6 +2898,7 @@ func (op *DeleteProcessorVersionOperation) Wait(ctx context.Context, opts ...gax // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteProcessorVersionOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -1228,7 +2929,8 @@ func (op *DeleteProcessorVersionOperation) Name() string { // DeployProcessorVersionOperation manages a long-running operation from DeployProcessorVersion. type DeployProcessorVersionOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeployProcessorVersionOperation returns a new DeployProcessorVersionOperation from a given name. @@ -1239,10 +2941,21 @@ func (c *documentProcessorGRPCClient) DeployProcessorVersionOperation(name strin } } +// DeployProcessorVersionOperation returns a new DeployProcessorVersionOperation from a given name. +// The name must be that of a previously created DeployProcessorVersionOperation, possibly from a different process. +func (c *documentProcessorRESTClient) DeployProcessorVersionOperation(name string) *DeployProcessorVersionOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeployProcessorVersionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeployProcessorVersionOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*documentaipb.DeployProcessorVersionResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp documentaipb.DeployProcessorVersionResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1260,6 +2973,7 @@ func (op *DeployProcessorVersionOperation) Wait(ctx context.Context, opts ...gax // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeployProcessorVersionOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*documentaipb.DeployProcessorVersionResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp documentaipb.DeployProcessorVersionResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1297,7 +3011,8 @@ func (op *DeployProcessorVersionOperation) Name() string { // DisableProcessorOperation manages a long-running operation from DisableProcessor. type DisableProcessorOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DisableProcessorOperation returns a new DisableProcessorOperation from a given name. @@ -1308,10 +3023,21 @@ func (c *documentProcessorGRPCClient) DisableProcessorOperation(name string) *Di } } +// DisableProcessorOperation returns a new DisableProcessorOperation from a given name. +// The name must be that of a previously created DisableProcessorOperation, possibly from a different process. +func (c *documentProcessorRESTClient) DisableProcessorOperation(name string) *DisableProcessorOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DisableProcessorOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DisableProcessorOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*documentaipb.DisableProcessorResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp documentaipb.DisableProcessorResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1329,6 +3055,7 @@ func (op *DisableProcessorOperation) Wait(ctx context.Context, opts ...gax.CallO // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DisableProcessorOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*documentaipb.DisableProcessorResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp documentaipb.DisableProcessorResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1366,7 +3093,8 @@ func (op *DisableProcessorOperation) Name() string { // EnableProcessorOperation manages a long-running operation from EnableProcessor. type EnableProcessorOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // EnableProcessorOperation returns a new EnableProcessorOperation from a given name. @@ -1377,10 +3105,21 @@ func (c *documentProcessorGRPCClient) EnableProcessorOperation(name string) *Ena } } +// EnableProcessorOperation returns a new EnableProcessorOperation from a given name. +// The name must be that of a previously created EnableProcessorOperation, possibly from a different process. +func (c *documentProcessorRESTClient) EnableProcessorOperation(name string) *EnableProcessorOperation { + override := fmt.Sprintf("/v1/%s", name) + return &EnableProcessorOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *EnableProcessorOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*documentaipb.EnableProcessorResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp documentaipb.EnableProcessorResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1398,6 +3137,7 @@ func (op *EnableProcessorOperation) Wait(ctx context.Context, opts ...gax.CallOp // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *EnableProcessorOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*documentaipb.EnableProcessorResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp documentaipb.EnableProcessorResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1435,7 +3175,8 @@ func (op *EnableProcessorOperation) Name() string { // ReviewDocumentOperation manages a long-running operation from ReviewDocument. type ReviewDocumentOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // ReviewDocumentOperation returns a new ReviewDocumentOperation from a given name. @@ -1446,10 +3187,21 @@ func (c *documentProcessorGRPCClient) ReviewDocumentOperation(name string) *Revi } } +// ReviewDocumentOperation returns a new ReviewDocumentOperation from a given name. +// The name must be that of a previously created ReviewDocumentOperation, possibly from a different process. +func (c *documentProcessorRESTClient) ReviewDocumentOperation(name string) *ReviewDocumentOperation { + override := fmt.Sprintf("/v1/%s", name) + return &ReviewDocumentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *ReviewDocumentOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*documentaipb.ReviewDocumentResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp documentaipb.ReviewDocumentResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1467,6 +3219,7 @@ func (op *ReviewDocumentOperation) Wait(ctx context.Context, opts ...gax.CallOpt // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *ReviewDocumentOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*documentaipb.ReviewDocumentResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp documentaipb.ReviewDocumentResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1504,7 +3257,8 @@ func (op *ReviewDocumentOperation) Name() string { // SetDefaultProcessorVersionOperation manages a long-running operation from SetDefaultProcessorVersion. type SetDefaultProcessorVersionOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // SetDefaultProcessorVersionOperation returns a new SetDefaultProcessorVersionOperation from a given name. @@ -1515,10 +3269,21 @@ func (c *documentProcessorGRPCClient) SetDefaultProcessorVersionOperation(name s } } +// SetDefaultProcessorVersionOperation returns a new SetDefaultProcessorVersionOperation from a given name. +// The name must be that of a previously created SetDefaultProcessorVersionOperation, possibly from a different process. +func (c *documentProcessorRESTClient) SetDefaultProcessorVersionOperation(name string) *SetDefaultProcessorVersionOperation { + override := fmt.Sprintf("/v1/%s", name) + return &SetDefaultProcessorVersionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *SetDefaultProcessorVersionOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*documentaipb.SetDefaultProcessorVersionResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp documentaipb.SetDefaultProcessorVersionResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1536,6 +3301,7 @@ func (op *SetDefaultProcessorVersionOperation) Wait(ctx context.Context, opts .. // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *SetDefaultProcessorVersionOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*documentaipb.SetDefaultProcessorVersionResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp documentaipb.SetDefaultProcessorVersionResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1573,7 +3339,8 @@ func (op *SetDefaultProcessorVersionOperation) Name() string { // UndeployProcessorVersionOperation manages a long-running operation from UndeployProcessorVersion. type UndeployProcessorVersionOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UndeployProcessorVersionOperation returns a new UndeployProcessorVersionOperation from a given name. @@ -1584,10 +3351,21 @@ func (c *documentProcessorGRPCClient) UndeployProcessorVersionOperation(name str } } +// UndeployProcessorVersionOperation returns a new UndeployProcessorVersionOperation from a given name. +// The name must be that of a previously created UndeployProcessorVersionOperation, possibly from a different process. +func (c *documentProcessorRESTClient) UndeployProcessorVersionOperation(name string) *UndeployProcessorVersionOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UndeployProcessorVersionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UndeployProcessorVersionOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*documentaipb.UndeployProcessorVersionResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp documentaipb.UndeployProcessorVersionResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1605,6 +3383,7 @@ func (op *UndeployProcessorVersionOperation) Wait(ctx context.Context, opts ...g // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UndeployProcessorVersionOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*documentaipb.UndeployProcessorVersionResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp documentaipb.UndeployProcessorVersionResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/documentai/apiv1/document_processor_client_example_test.go b/documentai/apiv1/document_processor_client_example_test.go index 7c81f7a4fba8..864b74d89aae 100644 --- a/documentai/apiv1/document_processor_client_example_test.go +++ b/documentai/apiv1/document_processor_client_example_test.go @@ -43,6 +43,23 @@ func ExampleNewDocumentProcessorClient() { _ = c } +func ExampleNewDocumentProcessorRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := documentai.NewDocumentProcessorRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleDocumentProcessorClient_ProcessDocument() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/documentai/apiv1/documentaipb/barcode.pb.go b/documentai/apiv1/documentaipb/barcode.pb.go index 4f646ba56856..24b3201bab62 100644 --- a/documentai/apiv1/documentaipb/barcode.pb.go +++ b/documentai/apiv1/documentaipb/barcode.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/documentai/v1/barcode.proto package documentaipb diff --git a/documentai/apiv1/documentaipb/document.pb.go b/documentai/apiv1/documentaipb/document.pb.go index aa7194b317d3..379ed8a47826 100644 --- a/documentai/apiv1/documentaipb/document.pb.go +++ b/documentai/apiv1/documentaipb/document.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/documentai/v1/document.proto package documentaipb @@ -320,7 +320,6 @@ type Document struct { // Original source document from the user. // // Types that are assignable to Source: - // // *Document_Uri // *Document_Content Source isDocument_Source `protobuf_oneof:"source"` @@ -481,11 +480,10 @@ type isDocument_Source interface { type Document_Uri struct { // Optional. Currently supports Google Cloud Storage URI of the form - // - // `gs://bucket_name/object_name`. Object versioning is not supported. - // See [Google Cloud Storage Request - // URIs](https://cloud.google.com/storage/docs/reference-uris) for more - // info. + // `gs://bucket_name/object_name`. Object versioning is not supported. + // See [Google Cloud Storage Request + // URIs](https://cloud.google.com/storage/docs/reference-uris) for more + // info. Uri string `protobuf:"bytes,1,opt,name=uri,proto3,oneof"` } @@ -1310,7 +1308,6 @@ type Document_Revision struct { // Who/what made the change // // Types that are assignable to Source: - // // *Document_Revision_Agent // *Document_Revision_Processor Source isDocument_Revision_Source `protobuf_oneof:"source"` @@ -2927,7 +2924,6 @@ type Document_Entity_NormalizedValue struct { // populated. // // Types that are assignable to StructuredValue: - // // *Document_Entity_NormalizedValue_MoneyValue // *Document_Entity_NormalizedValue_DateValue // *Document_Entity_NormalizedValue_DatetimeValue diff --git a/documentai/apiv1/documentaipb/document_io.pb.go b/documentai/apiv1/documentaipb/document_io.pb.go index b711d3f59d40..2817712f9cf2 100644 --- a/documentai/apiv1/documentaipb/document_io.pb.go +++ b/documentai/apiv1/documentaipb/document_io.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/documentai/v1/document_io.proto package documentaipb @@ -260,7 +260,6 @@ type BatchDocumentsInputConfig struct { // The source. // // Types that are assignable to Source: - // // *BatchDocumentsInputConfig_GcsPrefix // *BatchDocumentsInputConfig_GcsDocuments Source isBatchDocumentsInputConfig_Source `protobuf_oneof:"source"` @@ -347,7 +346,6 @@ type DocumentOutputConfig struct { // The destination of the results. // // Types that are assignable to Destination: - // // *DocumentOutputConfig_GcsOutputConfig_ Destination isDocumentOutputConfig_Destination `protobuf_oneof:"destination"` } diff --git a/documentai/apiv1/documentaipb/document_processor_service.pb.go b/documentai/apiv1/documentaipb/document_processor_service.pb.go index 9ac482046499..ae75dee2fe76 100644 --- a/documentai/apiv1/documentaipb/document_processor_service.pb.go +++ b/documentai/apiv1/documentaipb/document_processor_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/documentai/v1/document_processor_service.proto package documentaipb @@ -289,7 +289,6 @@ type ProcessRequest struct { // The document payload. // // Types that are assignable to Source: - // // *ProcessRequest_InlineDocument // *ProcessRequest_RawDocument Source isProcessRequest_Source `protobuf_oneof:"source"` @@ -2288,7 +2287,6 @@ type ReviewDocumentRequest struct { // The document payload. // // Types that are assignable to Source: - // // *ReviewDocumentRequest_InlineDocument Source isReviewDocumentRequest_Source `protobuf_oneof:"source"` // Required. The resource name of the HumanReviewConfig that the document will be diff --git a/documentai/apiv1/documentaipb/document_schema.pb.go b/documentai/apiv1/documentaipb/document_schema.pb.go index 38a095a0da84..22fc2142c9ba 100644 --- a/documentai/apiv1/documentaipb/document_schema.pb.go +++ b/documentai/apiv1/documentaipb/document_schema.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/documentai/v1/document_schema.proto package documentaipb @@ -183,7 +183,6 @@ type DocumentSchema_EntityType struct { unknownFields protoimpl.UnknownFields // Types that are assignable to ValueSource: - // // *DocumentSchema_EntityType_EnumValues_ ValueSource isDocumentSchema_EntityType_ValueSource `protobuf_oneof:"value_source"` // User defined name for the type. @@ -192,16 +191,16 @@ type DocumentSchema_EntityType struct { // cannot be a 'Common Type'. Besides that we use the following naming // conventions: // - // - *use `snake_casing`* - // - name matching is case-insensitive - // - Maximum 64 characters. - // - Must start with a letter. - // - Allowed characters: ASCII letters `[a-z0-9_-]`. (For backward - // compatibility internal infrastructure and tooling can handle any ascii - // character) - // - The `/` is sometimes used to denote a property of a type. For example - // `line_item/amount`. This convention is deprecated, but will still be - // honored for backward compatibility. + // - *use `snake_casing`* + // - name matching is case-insensitive + // - Maximum 64 characters. + // - Must start with a letter. + // - Allowed characters: ASCII letters `[a-z0-9_-]`. (For backward + // compatibility internal infrastructure and tooling can handle any ascii + // character) + // - The `/` is sometimes used to denote a property of a type. For example + // `line_item/amount`. This convention is deprecated, but will still be + // honored for backward compatibility. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // The entity type that this type is derived from. For now, one and only // one should be set. diff --git a/documentai/apiv1/documentaipb/geometry.pb.go b/documentai/apiv1/documentaipb/geometry.pb.go index 8116cc957982..018b1da69f76 100644 --- a/documentai/apiv1/documentaipb/geometry.pb.go +++ b/documentai/apiv1/documentaipb/geometry.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/documentai/v1/geometry.proto package documentaipb diff --git a/documentai/apiv1/documentaipb/operation_metadata.pb.go b/documentai/apiv1/documentaipb/operation_metadata.pb.go index acd19184f726..b0fac664aee8 100644 --- a/documentai/apiv1/documentaipb/operation_metadata.pb.go +++ b/documentai/apiv1/documentaipb/operation_metadata.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/documentai/v1/operation_metadata.proto package documentaipb diff --git a/documentai/apiv1/documentaipb/processor.pb.go b/documentai/apiv1/documentaipb/processor.pb.go index 9618ef2ec6ec..c0065b04684f 100644 --- a/documentai/apiv1/documentaipb/processor.pb.go +++ b/documentai/apiv1/documentaipb/processor.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/documentai/v1/processor.proto package documentaipb diff --git a/documentai/apiv1/documentaipb/processor_type.pb.go b/documentai/apiv1/documentaipb/processor_type.pb.go index a91bb9cd76fe..1c8287b8d92e 100644 --- a/documentai/apiv1/documentaipb/processor_type.pb.go +++ b/documentai/apiv1/documentaipb/processor_type.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/documentai/v1/processor_type.proto package documentaipb @@ -131,7 +131,7 @@ func (x *ProcessorType) GetLaunchStage() api.LaunchStage { if x != nil { return x.LaunchStage } - return api.LaunchStage_LAUNCH_STAGE_UNSPECIFIED + return api.LaunchStage(0) } // The location information about where the processor is available. diff --git a/documentai/apiv1/gapic_metadata.json b/documentai/apiv1/gapic_metadata.json index 9749290d36f6..53c5003d9abb 100644 --- a/documentai/apiv1/gapic_metadata.json +++ b/documentai/apiv1/gapic_metadata.json @@ -121,6 +121,121 @@ ] } } + }, + "rest": { + "libraryClient": "DocumentProcessorClient", + "rpcs": { + "BatchProcessDocuments": { + "methods": [ + "BatchProcessDocuments" + ] + }, + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "CreateProcessor": { + "methods": [ + "CreateProcessor" + ] + }, + "DeleteProcessor": { + "methods": [ + "DeleteProcessor" + ] + }, + "DeleteProcessorVersion": { + "methods": [ + "DeleteProcessorVersion" + ] + }, + "DeployProcessorVersion": { + "methods": [ + "DeployProcessorVersion" + ] + }, + "DisableProcessor": { + "methods": [ + "DisableProcessor" + ] + }, + "EnableProcessor": { + "methods": [ + "EnableProcessor" + ] + }, + "FetchProcessorTypes": { + "methods": [ + "FetchProcessorTypes" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "GetProcessor": { + "methods": [ + "GetProcessor" + ] + }, + "GetProcessorVersion": { + "methods": [ + "GetProcessorVersion" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "ListProcessorTypes": { + "methods": [ + "ListProcessorTypes" + ] + }, + "ListProcessorVersions": { + "methods": [ + "ListProcessorVersions" + ] + }, + "ListProcessors": { + "methods": [ + "ListProcessors" + ] + }, + "ProcessDocument": { + "methods": [ + "ProcessDocument" + ] + }, + "ReviewDocument": { + "methods": [ + "ReviewDocument" + ] + }, + "SetDefaultProcessorVersion": { + "methods": [ + "SetDefaultProcessorVersion" + ] + }, + "UndeployProcessorVersion": { + "methods": [ + "UndeployProcessorVersion" + ] + } + } } } } diff --git a/documentai/apiv1beta3/document_processor_client.go b/documentai/apiv1beta3/document_processor_client.go index 7a9f3fa80039..e6d71fe07ff2 100644 --- a/documentai/apiv1beta3/document_processor_client.go +++ b/documentai/apiv1beta3/document_processor_client.go @@ -1357,6 +1357,11 @@ func (c *documentProcessorRESTClient) ProcessDocument(ctx context.Context, req * } baseUrl.Path += fmt.Sprintf("/v1beta3/%v:process", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1417,6 +1422,11 @@ func (c *documentProcessorRESTClient) BatchProcessDocuments(ctx context.Context, } baseUrl.Path += fmt.Sprintf("/v1beta3/%v:batchProcess", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1475,6 +1485,11 @@ func (c *documentProcessorRESTClient) FetchProcessorTypes(ctx context.Context, r } baseUrl.Path += fmt.Sprintf("/v1beta3/%v:fetchProcessorTypes", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1542,6 +1557,7 @@ func (c *documentProcessorRESTClient) ListProcessorTypes(ctx context.Context, re baseUrl.Path += fmt.Sprintf("/v1beta3/%v/processorTypes", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -1629,6 +1645,7 @@ func (c *documentProcessorRESTClient) ListProcessors(ctx context.Context, req *d baseUrl.Path += fmt.Sprintf("/v1beta3/%v/processors", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -1702,6 +1719,11 @@ func (c *documentProcessorRESTClient) GetProcessor(ctx context.Context, req *doc } baseUrl.Path += fmt.Sprintf("/v1beta3/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1763,6 +1785,11 @@ func (c *documentProcessorRESTClient) TrainProcessorVersion(ctx context.Context, } baseUrl.Path += fmt.Sprintf("/v1beta3/%v/processorVersions:train", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1820,6 +1847,11 @@ func (c *documentProcessorRESTClient) GetProcessorVersion(ctx context.Context, r } baseUrl.Path += fmt.Sprintf("/v1beta3/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1887,6 +1919,7 @@ func (c *documentProcessorRESTClient) ListProcessorVersions(ctx context.Context, baseUrl.Path += fmt.Sprintf("/v1beta3/%v/processorVersions", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -1961,6 +1994,11 @@ func (c *documentProcessorRESTClient) DeleteProcessorVersion(ctx context.Context } baseUrl.Path += fmt.Sprintf("/v1beta3/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2024,6 +2062,11 @@ func (c *documentProcessorRESTClient) DeployProcessorVersion(ctx context.Context } baseUrl.Path += fmt.Sprintf("/v1beta3/%v:deploy", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2087,6 +2130,11 @@ func (c *documentProcessorRESTClient) UndeployProcessorVersion(ctx context.Conte } baseUrl.Path += fmt.Sprintf("/v1beta3/%v:undeploy", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2152,6 +2200,11 @@ func (c *documentProcessorRESTClient) CreateProcessor(ctx context.Context, req * } baseUrl.Path += fmt.Sprintf("/v1beta3/%v/processors", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -2206,6 +2259,11 @@ func (c *documentProcessorRESTClient) DeleteProcessor(ctx context.Context, req * } baseUrl.Path += fmt.Sprintf("/v1beta3/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2269,6 +2327,11 @@ func (c *documentProcessorRESTClient) EnableProcessor(ctx context.Context, req * } baseUrl.Path += fmt.Sprintf("/v1beta3/%v:enable", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2332,6 +2395,11 @@ func (c *documentProcessorRESTClient) DisableProcessor(ctx context.Context, req } baseUrl.Path += fmt.Sprintf("/v1beta3/%v:disable", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2397,6 +2465,11 @@ func (c *documentProcessorRESTClient) SetDefaultProcessorVersion(ctx context.Con } baseUrl.Path += fmt.Sprintf("/v1beta3/%v:setDefaultProcessorVersion", req.GetProcessor()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "processor", url.QueryEscape(req.GetProcessor()))) @@ -2461,6 +2534,11 @@ func (c *documentProcessorRESTClient) ReviewDocument(ctx context.Context, req *d } baseUrl.Path += fmt.Sprintf("/v1beta3/%v:reviewDocument", req.GetHumanReviewConfig()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "human_review_config", url.QueryEscape(req.GetHumanReviewConfig()))) @@ -2525,6 +2603,11 @@ func (c *documentProcessorRESTClient) EvaluateProcessorVersion(ctx context.Conte } baseUrl.Path += fmt.Sprintf("/v1beta3/%v:evaluateProcessorVersion", req.GetProcessorVersion()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "processor_version", url.QueryEscape(req.GetProcessorVersion()))) @@ -2582,6 +2665,11 @@ func (c *documentProcessorRESTClient) GetEvaluation(ctx context.Context, req *do } baseUrl.Path += fmt.Sprintf("/v1beta3/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2649,6 +2737,7 @@ func (c *documentProcessorRESTClient) ListEvaluations(ctx context.Context, req * baseUrl.Path += fmt.Sprintf("/v1beta3/%v/evaluations", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -2722,6 +2811,11 @@ func (c *documentProcessorRESTClient) GetLocation(ctx context.Context, req *loca } baseUrl.Path += fmt.Sprintf("/v1beta3/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2789,6 +2883,7 @@ func (c *documentProcessorRESTClient) ListLocations(ctx context.Context, req *lo baseUrl.Path += fmt.Sprintf("/v1beta3/%v/locations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -2865,6 +2960,11 @@ func (c *documentProcessorRESTClient) CancelOperation(ctx context.Context, req * } baseUrl.Path += fmt.Sprintf("/v1beta3/%v:cancel", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2900,6 +3000,11 @@ func (c *documentProcessorRESTClient) GetOperation(ctx context.Context, req *lon } baseUrl.Path += fmt.Sprintf("/v1beta3/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2967,6 +3072,7 @@ func (c *documentProcessorRESTClient) ListOperations(ctx context.Context, req *l baseUrl.Path += fmt.Sprintf("/v1beta3/%v", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/documentai/apiv1beta3/documentaipb/barcode.pb.go b/documentai/apiv1beta3/documentaipb/barcode.pb.go index dbd7d135e84d..09811b8d0f43 100644 --- a/documentai/apiv1beta3/documentaipb/barcode.pb.go +++ b/documentai/apiv1beta3/documentaipb/barcode.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/documentai/v1beta3/barcode.proto package documentaipb diff --git a/documentai/apiv1beta3/documentaipb/document.pb.go b/documentai/apiv1beta3/documentaipb/document.pb.go index 06a5f17e01ae..521eeb85d549 100644 --- a/documentai/apiv1beta3/documentaipb/document.pb.go +++ b/documentai/apiv1beta3/documentaipb/document.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/documentai/v1beta3/document.proto package documentaipb @@ -320,7 +320,6 @@ type Document struct { // Original source document from the user. // // Types that are assignable to Source: - // // *Document_Uri // *Document_Content Source isDocument_Source `protobuf_oneof:"source"` @@ -481,11 +480,10 @@ type isDocument_Source interface { type Document_Uri struct { // Optional. Currently supports Google Cloud Storage URI of the form - // - // `gs://bucket_name/object_name`. Object versioning is not supported. - // See [Google Cloud Storage Request - // URIs](https://cloud.google.com/storage/docs/reference-uris) for more - // info. + // `gs://bucket_name/object_name`. Object versioning is not supported. + // See [Google Cloud Storage Request + // URIs](https://cloud.google.com/storage/docs/reference-uris) for more + // info. Uri string `protobuf:"bytes,1,opt,name=uri,proto3,oneof"` } @@ -1310,7 +1308,6 @@ type Document_Revision struct { // Who/what made the change // // Types that are assignable to Source: - // // *Document_Revision_Agent // *Document_Revision_Processor Source isDocument_Revision_Source `protobuf_oneof:"source"` @@ -2927,7 +2924,6 @@ type Document_Entity_NormalizedValue struct { // populated. // // Types that are assignable to StructuredValue: - // // *Document_Entity_NormalizedValue_MoneyValue // *Document_Entity_NormalizedValue_DateValue // *Document_Entity_NormalizedValue_DatetimeValue diff --git a/documentai/apiv1beta3/documentaipb/document_io.pb.go b/documentai/apiv1beta3/documentaipb/document_io.pb.go index 04885affce4e..b88cd3f7bf68 100644 --- a/documentai/apiv1beta3/documentaipb/document_io.pb.go +++ b/documentai/apiv1beta3/documentaipb/document_io.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/documentai/v1beta3/document_io.proto package documentaipb @@ -260,7 +260,6 @@ type BatchDocumentsInputConfig struct { // The source. // // Types that are assignable to Source: - // // *BatchDocumentsInputConfig_GcsPrefix // *BatchDocumentsInputConfig_GcsDocuments Source isBatchDocumentsInputConfig_Source `protobuf_oneof:"source"` @@ -347,7 +346,6 @@ type DocumentOutputConfig struct { // The destination of the results. // // Types that are assignable to Destination: - // // *DocumentOutputConfig_GcsOutputConfig_ Destination isDocumentOutputConfig_Destination `protobuf_oneof:"destination"` } diff --git a/documentai/apiv1beta3/documentaipb/document_processor_service.pb.go b/documentai/apiv1beta3/documentaipb/document_processor_service.pb.go index b14827d059f3..d113ccaaeade 100644 --- a/documentai/apiv1beta3/documentaipb/document_processor_service.pb.go +++ b/documentai/apiv1beta3/documentaipb/document_processor_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/documentai/v1beta3/document_processor_service.proto package documentaipb @@ -354,7 +354,6 @@ type ProcessRequest struct { // The document payload. // // Types that are assignable to Source: - // // *ProcessRequest_InlineDocument // *ProcessRequest_RawDocument Source isProcessRequest_Source `protobuf_oneof:"source"` @@ -2608,7 +2607,6 @@ type ReviewDocumentRequest struct { // The document payload. // // Types that are assignable to Source: - // // *ReviewDocumentRequest_InlineDocument Source isReviewDocumentRequest_Source `protobuf_oneof:"source"` // Required. The resource name of the HumanReviewConfig that the document will be diff --git a/documentai/apiv1beta3/documentaipb/document_schema.pb.go b/documentai/apiv1beta3/documentaipb/document_schema.pb.go index c9964fc6694f..071396169c0e 100644 --- a/documentai/apiv1beta3/documentaipb/document_schema.pb.go +++ b/documentai/apiv1beta3/documentaipb/document_schema.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/documentai/v1beta3/document_schema.proto package documentaipb @@ -183,7 +183,6 @@ type DocumentSchema_EntityType struct { unknownFields protoimpl.UnknownFields // Types that are assignable to ValueSource: - // // *DocumentSchema_EntityType_EnumValues_ ValueSource isDocumentSchema_EntityType_ValueSource `protobuf_oneof:"value_source"` // User defined name for the type. @@ -192,16 +191,16 @@ type DocumentSchema_EntityType struct { // cannot be a 'Common Type'. Besides that we use the following naming // conventions: // - // - *use `snake_casing`* - // - name matching is case-insensitive - // - Maximum 64 characters. - // - Must start with a letter. - // - Allowed characters: ASCII letters `[a-z0-9_-]`. (For backward - // compatibility internal infrastructure and tooling can handle any ascii - // character) - // - The `/` is sometimes used to denote a property of a type. For example - // `line_item/amount`. This convention is deprecated, but will still be - // honored for backward compatibility. + // - *use `snake_casing`* + // - name matching is case-insensitive + // - Maximum 64 characters. + // - Must start with a letter. + // - Allowed characters: ASCII letters `[a-z0-9_-]`. (For backward + // compatibility internal infrastructure and tooling can handle any ascii + // character) + // - The `/` is sometimes used to denote a property of a type. For example + // `line_item/amount`. This convention is deprecated, but will still be + // honored for backward compatibility. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // The entity type that this type is derived from. For now, one and only // one should be set. diff --git a/documentai/apiv1beta3/documentaipb/evaluation.pb.go b/documentai/apiv1beta3/documentaipb/evaluation.pb.go index 09069fb311cb..41348a7987aa 100644 --- a/documentai/apiv1beta3/documentaipb/evaluation.pb.go +++ b/documentai/apiv1beta3/documentaipb/evaluation.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/documentai/v1beta3/evaluation.proto package documentaipb diff --git a/documentai/apiv1beta3/documentaipb/geometry.pb.go b/documentai/apiv1beta3/documentaipb/geometry.pb.go index 6fb8073035b9..4b461201100e 100644 --- a/documentai/apiv1beta3/documentaipb/geometry.pb.go +++ b/documentai/apiv1beta3/documentaipb/geometry.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/documentai/v1beta3/geometry.proto package documentaipb diff --git a/documentai/apiv1beta3/documentaipb/operation_metadata.pb.go b/documentai/apiv1beta3/documentaipb/operation_metadata.pb.go index 90b9c5fd3318..eb7c60e3a055 100644 --- a/documentai/apiv1beta3/documentaipb/operation_metadata.pb.go +++ b/documentai/apiv1beta3/documentaipb/operation_metadata.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/documentai/v1beta3/operation_metadata.proto package documentaipb diff --git a/documentai/apiv1beta3/documentaipb/processor.pb.go b/documentai/apiv1beta3/documentaipb/processor.pb.go index 7178a8e483fb..a939f27edcaa 100644 --- a/documentai/apiv1beta3/documentaipb/processor.pb.go +++ b/documentai/apiv1beta3/documentaipb/processor.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/documentai/v1beta3/processor.proto package documentaipb diff --git a/documentai/apiv1beta3/documentaipb/processor_type.pb.go b/documentai/apiv1beta3/documentaipb/processor_type.pb.go index c3b7b3299269..6bb7563a370b 100644 --- a/documentai/apiv1beta3/documentaipb/processor_type.pb.go +++ b/documentai/apiv1beta3/documentaipb/processor_type.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/documentai/v1beta3/processor_type.proto package documentaipb @@ -131,7 +131,7 @@ func (x *ProcessorType) GetLaunchStage() api.LaunchStage { if x != nil { return x.LaunchStage } - return api.LaunchStage_LAUNCH_STAGE_UNSPECIFIED + return api.LaunchStage(0) } // The location information about where the processor is available. diff --git a/domains/apiv1beta1/domains_client.go b/domains/apiv1beta1/domains_client.go index 54d5b38c6ccd..291209836c2a 100644 --- a/domains/apiv1beta1/domains_client.go +++ b/domains/apiv1beta1/domains_client.go @@ -884,6 +884,7 @@ func (c *restClient) SearchDomains(ctx context.Context, req *domainspb.SearchDom baseUrl.Path += fmt.Sprintf("/v1beta1/%v/registrations:searchDomains", req.GetLocation()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("query", fmt.Sprintf("%v", req.GetQuery())) baseUrl.RawQuery = params.Encode() @@ -943,6 +944,7 @@ func (c *restClient) RetrieveRegisterParameters(ctx context.Context, req *domain baseUrl.Path += fmt.Sprintf("/v1beta1/%v/registrations:retrieveRegisterParameters", req.GetLocation()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("domainName", fmt.Sprintf("%v", req.GetDomainName())) baseUrl.RawQuery = params.Encode() @@ -1018,6 +1020,11 @@ func (c *restClient) RegisterDomain(ctx context.Context, req *domainspb.Register } baseUrl.Path += fmt.Sprintf("/v1beta1/%v/registrations:register", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1080,6 +1087,7 @@ func (c *restClient) RetrieveTransferParameters(ctx context.Context, req *domain baseUrl.Path += fmt.Sprintf("/v1beta1/%v/registrations:retrieveTransferParameters", req.GetLocation()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("domainName", fmt.Sprintf("%v", req.GetDomainName())) baseUrl.RawQuery = params.Encode() @@ -1162,6 +1170,11 @@ func (c *restClient) TransferDomain(ctx context.Context, req *domainspb.Transfer } baseUrl.Path += fmt.Sprintf("/v1beta1/%v/registrations:transfer", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1233,6 +1246,7 @@ func (c *restClient) ListRegistrations(ctx context.Context, req *domainspb.ListR baseUrl.Path += fmt.Sprintf("/v1beta1/%v/registrations", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1309,6 +1323,11 @@ func (c *restClient) GetRegistration(ctx context.Context, req *domainspb.GetRegi } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1377,6 +1396,7 @@ func (c *restClient) UpdateRegistration(ctx context.Context, req *domainspb.Upda baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetRegistration().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -1450,6 +1470,11 @@ func (c *restClient) ConfigureManagementSettings(ctx context.Context, req *domai } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:configureManagementSettings", req.GetRegistration()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "registration", url.QueryEscape(req.GetRegistration()))) @@ -1513,6 +1538,11 @@ func (c *restClient) ConfigureDnsSettings(ctx context.Context, req *domainspb.Co } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:configureDnsSettings", req.GetRegistration()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "registration", url.QueryEscape(req.GetRegistration()))) @@ -1577,6 +1607,11 @@ func (c *restClient) ConfigureContactSettings(ctx context.Context, req *domainsp } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:configureContactSettings", req.GetRegistration()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "registration", url.QueryEscape(req.GetRegistration()))) @@ -1648,6 +1683,11 @@ func (c *restClient) ExportRegistration(ctx context.Context, req *domainspb.Expo } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:export", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1725,6 +1765,11 @@ func (c *restClient) DeleteRegistration(ctx context.Context, req *domainspb.Dele } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1786,6 +1831,11 @@ func (c *restClient) RetrieveAuthorizationCode(ctx context.Context, req *domains } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:retrieveAuthorizationCode", req.GetRegistration()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "registration", url.QueryEscape(req.GetRegistration()))) @@ -1848,6 +1898,11 @@ func (c *restClient) ResetAuthorizationCode(ctx context.Context, req *domainspb. } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:resetAuthorizationCode", req.GetRegistration()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "registration", url.QueryEscape(req.GetRegistration()))) diff --git a/domains/apiv1beta1/domainspb/domains.pb.go b/domains/apiv1beta1/domainspb/domains.pb.go index 49004a27f031..0eb85a883e6d 100644 --- a/domains/apiv1beta1/domainspb/domains.pb.go +++ b/domains/apiv1beta1/domainspb/domains.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/domains/v1beta1/domains.proto package domainspb @@ -1018,7 +1018,6 @@ type DnsSettings struct { // The DNS provider of the registration. // // Types that are assignable to DnsProvider: - // // *DnsSettings_CustomDns_ // *DnsSettings_GoogleDomainsDns_ DnsProvider isDnsSettings_DnsProvider `protobuf_oneof:"dns_provider"` @@ -4582,12 +4581,14 @@ type DomainsClient interface { // Cloud Domains. For domains managed by Google Domains, transferring to Cloud // Domains is not supported. // + // // Use the returned values to call `TransferDomain`. RetrieveTransferParameters(ctx context.Context, in *RetrieveTransferParametersRequest, opts ...grpc.CallOption) (*RetrieveTransferParametersResponse, error) // Transfers a domain name from another registrar to Cloud Domains. For // domains managed by Google Domains, transferring to Cloud Domains is not // supported. // + // // Before calling this method, go to the domain's current registrar to unlock // the domain for transfer and retrieve the domain's transfer authorization // code. Then call `RetrieveTransferParameters` to confirm that the domain is @@ -4838,12 +4839,14 @@ type DomainsServer interface { // Cloud Domains. For domains managed by Google Domains, transferring to Cloud // Domains is not supported. // + // // Use the returned values to call `TransferDomain`. RetrieveTransferParameters(context.Context, *RetrieveTransferParametersRequest) (*RetrieveTransferParametersResponse, error) // Transfers a domain name from another registrar to Cloud Domains. For // domains managed by Google Domains, transferring to Cloud Domains is not // supported. // + // // Before calling this method, go to the domain's current registrar to unlock // the domain for transfer and retrieve the domain's transfer authorization // code. Then call `RetrieveTransferParameters` to confirm that the domain is diff --git a/edgecontainer/apiv1/doc.go b/edgecontainer/apiv1/doc.go index 0237da150bf5..812f4ea4169a 100644 --- a/edgecontainer/apiv1/doc.go +++ b/edgecontainer/apiv1/doc.go @@ -86,6 +86,8 @@ package edgecontainer // import "cloud.google.com/go/edgecontainer/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -174,3 +176,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/edgecontainer/apiv1/edge_container_client.go b/edgecontainer/apiv1/edge_container_client.go index 0adf5610649d..852a04b02730 100644 --- a/edgecontainer/apiv1/edge_container_client.go +++ b/edgecontainer/apiv1/edge_container_client.go @@ -17,9 +17,12 @@ package edgecontainer import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,15 +30,18 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -188,6 +194,106 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + ListClusters: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetCluster: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateCluster: []gax.CallOption{}, + UpdateCluster: []gax.CallOption{}, + DeleteCluster: []gax.CallOption{}, + GenerateAccessToken: []gax.CallOption{}, + ListNodePools: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetNodePool: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateNodePool: []gax.CallOption{}, + UpdateNodePool: []gax.CallOption{}, + DeleteNodePool: []gax.CallOption{}, + ListMachines: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetMachine: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListVpnConnections: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetVpnConnection: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateVpnConnection: []gax.CallOption{}, + DeleteVpnConnection: []gax.CallOption{}, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + CancelOperation: []gax.CallOption{}, + DeleteOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalClient is an interface that defines the methods available from Distributed Cloud Edge Container API. type internalClient interface { Close() error @@ -534,6 +640,90 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new edge container rest client. +// +// EdgeContainer API provides management of Kubernetes Clusters on Google Edge +// Cloud deployments. +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://edgecontainer.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://edgecontainer.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://edgecontainer.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) ListClusters(ctx context.Context, req *edgecontainerpb.ListClustersRequest, opts ...gax.CallOption) *ClusterIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1166,92 +1356,1739 @@ func (c *gRPCClient) ListOperations(ctx context.Context, req *longrunningpb.List return it } -// CreateClusterOperation manages a long-running operation from CreateCluster. -type CreateClusterOperation struct { - lro *longrunning.Operation -} +// ListClusters lists Clusters in a given project and location. +func (c *restClient) ListClusters(ctx context.Context, req *edgecontainerpb.ListClustersRequest, opts ...gax.CallOption) *ClusterIterator { + it := &ClusterIterator{} + req = proto.Clone(req).(*edgecontainerpb.ListClustersRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*edgecontainerpb.Cluster, string, error) { + resp := &edgecontainerpb.ListClustersResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/clusters", req.GetParent()) -// CreateClusterOperation returns a new CreateClusterOperation from a given name. -// The name must be that of a previously created CreateClusterOperation, possibly from a different process. -func (c *gRPCClient) CreateClusterOperation(name string) *CreateClusterOperation { - return &CreateClusterOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetClusters(), resp.GetNextPageToken(), nil } -} -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *CreateClusterOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*edgecontainerpb.Cluster, error) { - var resp edgecontainerpb.Cluster - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { - return nil, err + 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 } - return &resp, nil + + it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it } -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *CreateClusterOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*edgecontainerpb.Cluster, error) { - var resp edgecontainerpb.Cluster - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { +// GetCluster gets details of a single Cluster. +func (c *restClient) GetCluster(ctx context.Context, req *edgecontainerpb.GetClusterRequest, opts ...gax.CallOption) (*edgecontainerpb.Cluster, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - if !op.Done() { - return nil, nil + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetCluster[0:len((*c.CallOptions).GetCluster):len((*c.CallOptions).GetCluster)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &edgecontainerpb.Cluster{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e } - return &resp, nil + return resp, nil } -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *CreateClusterOperation) Metadata() (*edgecontainerpb.OperationMetadata, error) { - var meta edgecontainerpb.OperationMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { +// CreateCluster creates a new Cluster in a given project and location. +func (c *restClient) CreateCluster(ctx context.Context, req *edgecontainerpb.CreateClusterRequest, opts ...gax.CallOption) (*CreateClusterOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetCluster() + jsonReq, err := m.Marshal(body) + if err != nil { return nil, err } - return &meta, nil -} -// Done reports whether the long-running operation has completed. -func (op *CreateClusterOperation) Done() bool { - return op.lro.Done() -} + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/clusters", req.GetParent()) -// 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 *CreateClusterOperation) Name() string { - return op.lro.Name() -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("clusterId", fmt.Sprintf("%v", req.GetClusterId())) + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } -// CreateNodePoolOperation manages a long-running operation from CreateNodePool. -type CreateNodePoolOperation struct { - lro *longrunning.Operation -} + baseUrl.RawQuery = params.Encode() -// CreateNodePoolOperation returns a new CreateNodePoolOperation from a given name. -// The name must be that of a previously created CreateNodePoolOperation, possibly from a different process. + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateClusterOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateCluster updates the parameters of a single Cluster. +func (c *restClient) UpdateCluster(ctx context.Context, req *edgecontainerpb.UpdateClusterRequest, opts ...gax.CallOption) (*UpdateClusterOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetCluster() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetCluster().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "cluster.name", url.QueryEscape(req.GetCluster().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateClusterOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteCluster deletes a single Cluster. +func (c *restClient) DeleteCluster(ctx context.Context, req *edgecontainerpb.DeleteClusterRequest, opts ...gax.CallOption) (*DeleteClusterOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteClusterOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GenerateAccessToken generates an access token for a Cluster. +func (c *restClient) GenerateAccessToken(ctx context.Context, req *edgecontainerpb.GenerateAccessTokenRequest, opts ...gax.CallOption) (*edgecontainerpb.GenerateAccessTokenResponse, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:generateAccessToken", req.GetCluster()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "cluster", url.QueryEscape(req.GetCluster()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GenerateAccessToken[0:len((*c.CallOptions).GenerateAccessToken):len((*c.CallOptions).GenerateAccessToken)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &edgecontainerpb.GenerateAccessTokenResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListNodePools lists NodePools in a given project and location. +func (c *restClient) ListNodePools(ctx context.Context, req *edgecontainerpb.ListNodePoolsRequest, opts ...gax.CallOption) *NodePoolIterator { + it := &NodePoolIterator{} + req = proto.Clone(req).(*edgecontainerpb.ListNodePoolsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*edgecontainerpb.NodePool, string, error) { + resp := &edgecontainerpb.ListNodePoolsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/nodePools", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetNodePools(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetNodePool gets details of a single NodePool. +func (c *restClient) GetNodePool(ctx context.Context, req *edgecontainerpb.GetNodePoolRequest, opts ...gax.CallOption) (*edgecontainerpb.NodePool, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetNodePool[0:len((*c.CallOptions).GetNodePool):len((*c.CallOptions).GetNodePool)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &edgecontainerpb.NodePool{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateNodePool creates a new NodePool in a given project and location. +func (c *restClient) CreateNodePool(ctx context.Context, req *edgecontainerpb.CreateNodePoolRequest, opts ...gax.CallOption) (*CreateNodePoolOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetNodePool() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/nodePools", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("nodePoolId", fmt.Sprintf("%v", req.GetNodePoolId())) + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateNodePoolOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateNodePool updates the parameters of a single NodePool. +func (c *restClient) UpdateNodePool(ctx context.Context, req *edgecontainerpb.UpdateNodePoolRequest, opts ...gax.CallOption) (*UpdateNodePoolOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetNodePool() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetNodePool().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "node_pool.name", url.QueryEscape(req.GetNodePool().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateNodePoolOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteNodePool deletes a single NodePool. +func (c *restClient) DeleteNodePool(ctx context.Context, req *edgecontainerpb.DeleteNodePoolRequest, opts ...gax.CallOption) (*DeleteNodePoolOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteNodePoolOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListMachines lists Machines in a given project and location. +func (c *restClient) ListMachines(ctx context.Context, req *edgecontainerpb.ListMachinesRequest, opts ...gax.CallOption) *MachineIterator { + it := &MachineIterator{} + req = proto.Clone(req).(*edgecontainerpb.ListMachinesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*edgecontainerpb.Machine, string, error) { + resp := &edgecontainerpb.ListMachinesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/machines", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetMachines(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetMachine gets details of a single Machine. +func (c *restClient) GetMachine(ctx context.Context, req *edgecontainerpb.GetMachineRequest, opts ...gax.CallOption) (*edgecontainerpb.Machine, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetMachine[0:len((*c.CallOptions).GetMachine):len((*c.CallOptions).GetMachine)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &edgecontainerpb.Machine{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListVpnConnections lists VPN connections in a given project and location. +func (c *restClient) ListVpnConnections(ctx context.Context, req *edgecontainerpb.ListVpnConnectionsRequest, opts ...gax.CallOption) *VpnConnectionIterator { + it := &VpnConnectionIterator{} + req = proto.Clone(req).(*edgecontainerpb.ListVpnConnectionsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*edgecontainerpb.VpnConnection, string, error) { + resp := &edgecontainerpb.ListVpnConnectionsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/vpnConnections", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetVpnConnections(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetVpnConnection gets details of a single VPN connection. +func (c *restClient) GetVpnConnection(ctx context.Context, req *edgecontainerpb.GetVpnConnectionRequest, opts ...gax.CallOption) (*edgecontainerpb.VpnConnection, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetVpnConnection[0:len((*c.CallOptions).GetVpnConnection):len((*c.CallOptions).GetVpnConnection)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &edgecontainerpb.VpnConnection{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateVpnConnection creates a new VPN connection in a given project and location. +func (c *restClient) CreateVpnConnection(ctx context.Context, req *edgecontainerpb.CreateVpnConnectionRequest, opts ...gax.CallOption) (*CreateVpnConnectionOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetVpnConnection() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/vpnConnections", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + params.Add("vpnConnectionId", fmt.Sprintf("%v", req.GetVpnConnectionId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateVpnConnectionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteVpnConnection deletes a single VPN connection. +func (c *restClient) DeleteVpnConnection(ctx context.Context, req *edgecontainerpb.DeleteVpnConnectionRequest, opts ...gax.CallOption) (*DeleteVpnConnectionOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteVpnConnectionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetLocation gets information about a location. +func (c *restClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *restClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *restClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// DeleteOperation is a utility method from google.longrunning.Operations. +func (c *restClient) DeleteOperation(ctx context.Context, req *longrunningpb.DeleteOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *restClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *restClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CreateClusterOperation manages a long-running operation from CreateCluster. +type CreateClusterOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateClusterOperation returns a new CreateClusterOperation from a given name. +// The name must be that of a previously created CreateClusterOperation, possibly from a different process. +func (c *gRPCClient) CreateClusterOperation(name string) *CreateClusterOperation { + return &CreateClusterOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateClusterOperation returns a new CreateClusterOperation from a given name. +// The name must be that of a previously created CreateClusterOperation, possibly from a different process. +func (c *restClient) CreateClusterOperation(name string) *CreateClusterOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateClusterOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CreateClusterOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*edgecontainerpb.Cluster, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp edgecontainerpb.Cluster + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *CreateClusterOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*edgecontainerpb.Cluster, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp edgecontainerpb.Cluster + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *CreateClusterOperation) Metadata() (*edgecontainerpb.OperationMetadata, error) { + var meta edgecontainerpb.OperationMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *CreateClusterOperation) Done() bool { + return op.lro.Done() +} + +// 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 *CreateClusterOperation) Name() string { + return op.lro.Name() +} + +// CreateNodePoolOperation manages a long-running operation from CreateNodePool. +type CreateNodePoolOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateNodePoolOperation returns a new CreateNodePoolOperation from a given name. +// The name must be that of a previously created CreateNodePoolOperation, possibly from a different process. func (c *gRPCClient) CreateNodePoolOperation(name string) *CreateNodePoolOperation { return &CreateNodePoolOperation{ lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } +// CreateNodePoolOperation returns a new CreateNodePoolOperation from a given name. +// The name must be that of a previously created CreateNodePoolOperation, possibly from a different process. +func (c *restClient) CreateNodePoolOperation(name string) *CreateNodePoolOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateNodePoolOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateNodePoolOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*edgecontainerpb.NodePool, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp edgecontainerpb.NodePool if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1269,6 +3106,7 @@ func (op *CreateNodePoolOperation) Wait(ctx context.Context, opts ...gax.CallOpt // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateNodePoolOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*edgecontainerpb.NodePool, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp edgecontainerpb.NodePool if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1306,7 +3144,8 @@ func (op *CreateNodePoolOperation) Name() string { // CreateVpnConnectionOperation manages a long-running operation from CreateVpnConnection. type CreateVpnConnectionOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateVpnConnectionOperation returns a new CreateVpnConnectionOperation from a given name. @@ -1317,10 +3156,21 @@ func (c *gRPCClient) CreateVpnConnectionOperation(name string) *CreateVpnConnect } } +// CreateVpnConnectionOperation returns a new CreateVpnConnectionOperation from a given name. +// The name must be that of a previously created CreateVpnConnectionOperation, possibly from a different process. +func (c *restClient) CreateVpnConnectionOperation(name string) *CreateVpnConnectionOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateVpnConnectionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateVpnConnectionOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*edgecontainerpb.VpnConnection, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp edgecontainerpb.VpnConnection if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1338,6 +3188,7 @@ func (op *CreateVpnConnectionOperation) Wait(ctx context.Context, opts ...gax.Ca // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateVpnConnectionOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*edgecontainerpb.VpnConnection, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp edgecontainerpb.VpnConnection if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1375,7 +3226,8 @@ func (op *CreateVpnConnectionOperation) Name() string { // DeleteClusterOperation manages a long-running operation from DeleteCluster. type DeleteClusterOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteClusterOperation returns a new DeleteClusterOperation from a given name. @@ -1386,10 +3238,21 @@ func (c *gRPCClient) DeleteClusterOperation(name string) *DeleteClusterOperation } } +// DeleteClusterOperation returns a new DeleteClusterOperation from a given name. +// The name must be that of a previously created DeleteClusterOperation, possibly from a different process. +func (c *restClient) DeleteClusterOperation(name string) *DeleteClusterOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteClusterOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteClusterOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -1403,6 +3266,7 @@ func (op *DeleteClusterOperation) Wait(ctx context.Context, opts ...gax.CallOpti // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteClusterOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -1433,7 +3297,8 @@ func (op *DeleteClusterOperation) Name() string { // DeleteNodePoolOperation manages a long-running operation from DeleteNodePool. type DeleteNodePoolOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteNodePoolOperation returns a new DeleteNodePoolOperation from a given name. @@ -1444,10 +3309,21 @@ func (c *gRPCClient) DeleteNodePoolOperation(name string) *DeleteNodePoolOperati } } +// DeleteNodePoolOperation returns a new DeleteNodePoolOperation from a given name. +// The name must be that of a previously created DeleteNodePoolOperation, possibly from a different process. +func (c *restClient) DeleteNodePoolOperation(name string) *DeleteNodePoolOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteNodePoolOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteNodePoolOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -1461,6 +3337,7 @@ func (op *DeleteNodePoolOperation) Wait(ctx context.Context, opts ...gax.CallOpt // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteNodePoolOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -1491,7 +3368,8 @@ func (op *DeleteNodePoolOperation) Name() string { // DeleteVpnConnectionOperation manages a long-running operation from DeleteVpnConnection. type DeleteVpnConnectionOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteVpnConnectionOperation returns a new DeleteVpnConnectionOperation from a given name. @@ -1502,10 +3380,21 @@ func (c *gRPCClient) DeleteVpnConnectionOperation(name string) *DeleteVpnConnect } } +// DeleteVpnConnectionOperation returns a new DeleteVpnConnectionOperation from a given name. +// The name must be that of a previously created DeleteVpnConnectionOperation, possibly from a different process. +func (c *restClient) DeleteVpnConnectionOperation(name string) *DeleteVpnConnectionOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteVpnConnectionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteVpnConnectionOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -1519,6 +3408,7 @@ func (op *DeleteVpnConnectionOperation) Wait(ctx context.Context, opts ...gax.Ca // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteVpnConnectionOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -1549,7 +3439,8 @@ func (op *DeleteVpnConnectionOperation) Name() string { // UpdateClusterOperation manages a long-running operation from UpdateCluster. type UpdateClusterOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateClusterOperation returns a new UpdateClusterOperation from a given name. @@ -1560,10 +3451,21 @@ func (c *gRPCClient) UpdateClusterOperation(name string) *UpdateClusterOperation } } +// UpdateClusterOperation returns a new UpdateClusterOperation from a given name. +// The name must be that of a previously created UpdateClusterOperation, possibly from a different process. +func (c *restClient) UpdateClusterOperation(name string) *UpdateClusterOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateClusterOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateClusterOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*edgecontainerpb.Cluster, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp edgecontainerpb.Cluster if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1581,6 +3483,7 @@ func (op *UpdateClusterOperation) Wait(ctx context.Context, opts ...gax.CallOpti // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateClusterOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*edgecontainerpb.Cluster, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp edgecontainerpb.Cluster if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1618,7 +3521,8 @@ func (op *UpdateClusterOperation) Name() string { // UpdateNodePoolOperation manages a long-running operation from UpdateNodePool. type UpdateNodePoolOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateNodePoolOperation returns a new UpdateNodePoolOperation from a given name. @@ -1629,10 +3533,21 @@ func (c *gRPCClient) UpdateNodePoolOperation(name string) *UpdateNodePoolOperati } } +// UpdateNodePoolOperation returns a new UpdateNodePoolOperation from a given name. +// The name must be that of a previously created UpdateNodePoolOperation, possibly from a different process. +func (c *restClient) UpdateNodePoolOperation(name string) *UpdateNodePoolOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateNodePoolOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateNodePoolOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*edgecontainerpb.NodePool, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp edgecontainerpb.NodePool if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1650,6 +3565,7 @@ func (op *UpdateNodePoolOperation) Wait(ctx context.Context, opts ...gax.CallOpt // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateNodePoolOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*edgecontainerpb.NodePool, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp edgecontainerpb.NodePool if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/edgecontainer/apiv1/edge_container_client_example_test.go b/edgecontainer/apiv1/edge_container_client_example_test.go index 4e595270cd99..358d7a96557e 100644 --- a/edgecontainer/apiv1/edge_container_client_example_test.go +++ b/edgecontainer/apiv1/edge_container_client_example_test.go @@ -43,6 +43,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := edgecontainer.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_ListClusters() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/edgecontainer/apiv1/edgecontainerpb/resources.pb.go b/edgecontainer/apiv1/edgecontainerpb/resources.pb.go index 966d9b6a40c0..20e9ec30b200 100644 --- a/edgecontainer/apiv1/edgecontainerpb/resources.pb.go +++ b/edgecontainer/apiv1/edgecontainerpb/resources.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/edgecontainer/v1/resources.proto package edgecontainerpb diff --git a/edgecontainer/apiv1/edgecontainerpb/service.pb.go b/edgecontainer/apiv1/edgecontainerpb/service.pb.go index f89ff6310fa7..e1856b2d2729 100644 --- a/edgecontainer/apiv1/edgecontainerpb/service.pb.go +++ b/edgecontainer/apiv1/edgecontainerpb/service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/edgecontainer/v1/service.proto package edgecontainerpb diff --git a/edgecontainer/apiv1/gapic_metadata.json b/edgecontainer/apiv1/gapic_metadata.json index f6b17a43fa31..9f7bb3dfeabc 100644 --- a/edgecontainer/apiv1/gapic_metadata.json +++ b/edgecontainer/apiv1/gapic_metadata.json @@ -126,6 +126,126 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "CreateCluster": { + "methods": [ + "CreateCluster" + ] + }, + "CreateNodePool": { + "methods": [ + "CreateNodePool" + ] + }, + "CreateVpnConnection": { + "methods": [ + "CreateVpnConnection" + ] + }, + "DeleteCluster": { + "methods": [ + "DeleteCluster" + ] + }, + "DeleteNodePool": { + "methods": [ + "DeleteNodePool" + ] + }, + "DeleteOperation": { + "methods": [ + "DeleteOperation" + ] + }, + "DeleteVpnConnection": { + "methods": [ + "DeleteVpnConnection" + ] + }, + "GenerateAccessToken": { + "methods": [ + "GenerateAccessToken" + ] + }, + "GetCluster": { + "methods": [ + "GetCluster" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "GetMachine": { + "methods": [ + "GetMachine" + ] + }, + "GetNodePool": { + "methods": [ + "GetNodePool" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "GetVpnConnection": { + "methods": [ + "GetVpnConnection" + ] + }, + "ListClusters": { + "methods": [ + "ListClusters" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListMachines": { + "methods": [ + "ListMachines" + ] + }, + "ListNodePools": { + "methods": [ + "ListNodePools" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "ListVpnConnections": { + "methods": [ + "ListVpnConnections" + ] + }, + "UpdateCluster": { + "methods": [ + "UpdateCluster" + ] + }, + "UpdateNodePool": { + "methods": [ + "UpdateNodePool" + ] + } + } } } } diff --git a/errorreporting/apiv1beta1/error_group_client.go b/errorreporting/apiv1beta1/error_group_client.go index 50c55c4dde24..7f72f525f2fa 100644 --- a/errorreporting/apiv1beta1/error_group_client.go +++ b/errorreporting/apiv1beta1/error_group_client.go @@ -371,6 +371,11 @@ func (c *errorGroupRESTClient) GetGroup(ctx context.Context, req *errorreporting } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetGroupName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "group_name", url.QueryEscape(req.GetGroupName()))) @@ -432,6 +437,11 @@ func (c *errorGroupRESTClient) UpdateGroup(ctx context.Context, req *errorreport } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetGroup().GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "group.name", url.QueryEscape(req.GetGroup().GetName()))) diff --git a/errorreporting/apiv1beta1/error_stats_client.go b/errorreporting/apiv1beta1/error_stats_client.go index 5bdb6176bf04..fe688d64cf5d 100644 --- a/errorreporting/apiv1beta1/error_stats_client.go +++ b/errorreporting/apiv1beta1/error_stats_client.go @@ -486,6 +486,7 @@ func (c *errorStatsRESTClient) ListGroupStats(ctx context.Context, req *errorrep baseUrl.Path += fmt.Sprintf("/v1beta1/%v/groupStats", req.GetProjectName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetAlignment() != 0 { params.Add("alignment", fmt.Sprintf("%v", req.GetAlignment())) } @@ -496,8 +497,10 @@ func (c *errorStatsRESTClient) ListGroupStats(ctx context.Context, req *errorrep } params.Add("alignmentTime", string(alignmentTime)) } - if req.GetGroupId() != nil { - params.Add("groupId", fmt.Sprintf("%v", req.GetGroupId())) + if items := req.GetGroupId(); len(items) > 0 { + for _, item := range items { + params.Add("groupId", fmt.Sprintf("%v", item)) + } } if req.GetOrder() != 0 { params.Add("order", fmt.Sprintf("%v", req.GetOrder())) @@ -608,6 +611,7 @@ func (c *errorStatsRESTClient) ListEvents(ctx context.Context, req *errorreporti baseUrl.Path += fmt.Sprintf("/v1beta1/%v/events", req.GetProjectName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("groupId", fmt.Sprintf("%v", req.GetGroupId())) if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) @@ -694,6 +698,11 @@ func (c *errorStatsRESTClient) DeleteEvents(ctx context.Context, req *errorrepor } baseUrl.Path += fmt.Sprintf("/v1beta1/%v/events", req.GetProjectName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "project_name", url.QueryEscape(req.GetProjectName()))) diff --git a/errorreporting/apiv1beta1/errorreportingpb/common.pb.go b/errorreporting/apiv1beta1/errorreportingpb/common.pb.go index 8ae9e9197d10..bfb8e1a1970a 100644 --- a/errorreporting/apiv1beta1/errorreportingpb/common.pb.go +++ b/errorreporting/apiv1beta1/errorreportingpb/common.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/devtools/clouderrorreporting/v1beta1/common.proto package errorreportingpb diff --git a/errorreporting/apiv1beta1/errorreportingpb/error_group_service.pb.go b/errorreporting/apiv1beta1/errorreportingpb/error_group_service.pb.go index 17d211735733..d36dcf675ea1 100644 --- a/errorreporting/apiv1beta1/errorreportingpb/error_group_service.pb.go +++ b/errorreporting/apiv1beta1/errorreportingpb/error_group_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/devtools/clouderrorreporting/v1beta1/error_group_service.proto package errorreportingpb diff --git a/errorreporting/apiv1beta1/errorreportingpb/error_stats_service.pb.go b/errorreporting/apiv1beta1/errorreportingpb/error_stats_service.pb.go index 3901ec8823dd..78af2872b771 100644 --- a/errorreporting/apiv1beta1/errorreportingpb/error_stats_service.pb.go +++ b/errorreporting/apiv1beta1/errorreportingpb/error_stats_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/devtools/clouderrorreporting/v1beta1/error_stats_service.proto package errorreportingpb diff --git a/errorreporting/apiv1beta1/errorreportingpb/report_errors_service.pb.go b/errorreporting/apiv1beta1/errorreportingpb/report_errors_service.pb.go index a6197263344f..c93d6e29385d 100644 --- a/errorreporting/apiv1beta1/errorreportingpb/report_errors_service.pb.go +++ b/errorreporting/apiv1beta1/errorreportingpb/report_errors_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/devtools/clouderrorreporting/v1beta1/report_errors_service.proto package errorreportingpb diff --git a/errorreporting/apiv1beta1/report_errors_client.go b/errorreporting/apiv1beta1/report_errors_client.go index 0903b5d6488c..c6badde4864d 100644 --- a/errorreporting/apiv1beta1/report_errors_client.go +++ b/errorreporting/apiv1beta1/report_errors_client.go @@ -333,6 +333,11 @@ func (c *reportErrorsRESTClient) ReportErrorEvent(ctx context.Context, req *erro } baseUrl.Path += fmt.Sprintf("/v1beta1/%v/events:report", req.GetProjectName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "project_name", url.QueryEscape(req.GetProjectName()))) diff --git a/essentialcontacts/apiv1/doc.go b/essentialcontacts/apiv1/doc.go index e3aa3d24a2fa..83d7739fdef2 100644 --- a/essentialcontacts/apiv1/doc.go +++ b/essentialcontacts/apiv1/doc.go @@ -78,6 +78,8 @@ package essentialcontacts // import "cloud.google.com/go/essentialcontacts/apiv1 import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -166,3 +168,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/essentialcontacts/apiv1/essential_contacts_client.go b/essentialcontacts/apiv1/essential_contacts_client.go index ffed6a3f1dce..2b7006779f7e 100644 --- a/essentialcontacts/apiv1/essential_contacts_client.go +++ b/essentialcontacts/apiv1/essential_contacts_client.go @@ -17,21 +17,27 @@ package essentialcontacts import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" essentialcontactspb "cloud.google.com/go/essentialcontacts/apiv1/essentialcontactspb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -92,6 +98,36 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + CreateContact: []gax.CallOption{}, + UpdateContact: []gax.CallOption{}, + ListContacts: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetContact: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeleteContact: []gax.CallOption{}, + ComputeContacts: []gax.CallOption{}, + SendTestMessage: []gax.CallOption{}, + } +} + // internalClient is an interface that defines the methods available from Essential Contacts API. type internalClient interface { Close() error @@ -261,6 +297,74 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new essential contacts service rest client. +// +// Manages contacts for important Google Cloud notifications. +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://essentialcontacts.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://essentialcontacts.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://essentialcontacts.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) CreateContact(ctx context.Context, req *essentialcontactspb.CreateContactRequest, opts ...gax.CallOption) (*essentialcontactspb.Contact, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) @@ -453,6 +557,472 @@ func (c *gRPCClient) SendTestMessage(ctx context.Context, req *essentialcontacts return err } +// CreateContact adds a new contact for a resource. +func (c *restClient) CreateContact(ctx context.Context, req *essentialcontactspb.CreateContactRequest, opts ...gax.CallOption) (*essentialcontactspb.Contact, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetContact() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/contacts", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateContact[0:len((*c.CallOptions).CreateContact):len((*c.CallOptions).CreateContact)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &essentialcontactspb.Contact{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateContact updates a contact. +// Note: A contact’s email address cannot be changed. +func (c *restClient) UpdateContact(ctx context.Context, req *essentialcontactspb.UpdateContactRequest, opts ...gax.CallOption) (*essentialcontactspb.Contact, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetContact() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetContact().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "contact.name", url.QueryEscape(req.GetContact().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateContact[0:len((*c.CallOptions).UpdateContact):len((*c.CallOptions).UpdateContact)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &essentialcontactspb.Contact{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListContacts lists the contacts that have been set on a resource. +func (c *restClient) ListContacts(ctx context.Context, req *essentialcontactspb.ListContactsRequest, opts ...gax.CallOption) *ContactIterator { + it := &ContactIterator{} + req = proto.Clone(req).(*essentialcontactspb.ListContactsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*essentialcontactspb.Contact, string, error) { + resp := &essentialcontactspb.ListContactsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/contacts", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetContacts(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetContact gets a single contact. +func (c *restClient) GetContact(ctx context.Context, req *essentialcontactspb.GetContactRequest, opts ...gax.CallOption) (*essentialcontactspb.Contact, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetContact[0:len((*c.CallOptions).GetContact):len((*c.CallOptions).GetContact)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &essentialcontactspb.Contact{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteContact deletes a contact. +func (c *restClient) DeleteContact(ctx context.Context, req *essentialcontactspb.DeleteContactRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// ComputeContacts lists all contacts for the resource that are subscribed to the +// specified notification categories, including contacts inherited from +// any parent resources. +func (c *restClient) ComputeContacts(ctx context.Context, req *essentialcontactspb.ComputeContactsRequest, opts ...gax.CallOption) *ContactIterator { + it := &ContactIterator{} + req = proto.Clone(req).(*essentialcontactspb.ComputeContactsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*essentialcontactspb.Contact, string, error) { + resp := &essentialcontactspb.ComputeContactsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/contacts:compute", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if items := req.GetNotificationCategories(); len(items) > 0 { + for _, item := range items { + params.Add("notificationCategories", fmt.Sprintf("%v", item)) + } + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetContacts(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// SendTestMessage allows a contact admin to send a test message to contact to verify that it +// has been configured correctly. +func (c *restClient) SendTestMessage(ctx context.Context, req *essentialcontactspb.SendTestMessageRequest, opts ...gax.CallOption) error { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/contacts:sendTestMessage", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + // ContactIterator manages a stream of *essentialcontactspb.Contact. type ContactIterator struct { items []*essentialcontactspb.Contact diff --git a/essentialcontacts/apiv1/essential_contacts_client_example_test.go b/essentialcontacts/apiv1/essential_contacts_client_example_test.go index 765233c0be00..824a104a28c1 100644 --- a/essentialcontacts/apiv1/essential_contacts_client_example_test.go +++ b/essentialcontacts/apiv1/essential_contacts_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := essentialcontacts.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_CreateContact() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/essentialcontacts/apiv1/essentialcontactspb/enums.pb.go b/essentialcontacts/apiv1/essentialcontactspb/enums.pb.go index 1f1d475d436b..68ce8af1256c 100644 --- a/essentialcontacts/apiv1/essentialcontactspb/enums.pb.go +++ b/essentialcontacts/apiv1/essentialcontactspb/enums.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/essentialcontacts/v1/enums.proto package essentialcontactspb diff --git a/essentialcontacts/apiv1/essentialcontactspb/service.pb.go b/essentialcontacts/apiv1/essentialcontactspb/service.pb.go index 1402faf59b41..f888b317473a 100644 --- a/essentialcontacts/apiv1/essentialcontactspb/service.pb.go +++ b/essentialcontacts/apiv1/essentialcontactspb/service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/essentialcontacts/v1/service.proto package essentialcontactspb diff --git a/essentialcontacts/apiv1/gapic_metadata.json b/essentialcontacts/apiv1/gapic_metadata.json index cfebdf9707d2..2cac1fb274d2 100644 --- a/essentialcontacts/apiv1/gapic_metadata.json +++ b/essentialcontacts/apiv1/gapic_metadata.json @@ -46,6 +46,46 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "ComputeContacts": { + "methods": [ + "ComputeContacts" + ] + }, + "CreateContact": { + "methods": [ + "CreateContact" + ] + }, + "DeleteContact": { + "methods": [ + "DeleteContact" + ] + }, + "GetContact": { + "methods": [ + "GetContact" + ] + }, + "ListContacts": { + "methods": [ + "ListContacts" + ] + }, + "SendTestMessage": { + "methods": [ + "SendTestMessage" + ] + }, + "UpdateContact": { + "methods": [ + "UpdateContact" + ] + } + } } } } diff --git a/eventarc/apiv1/doc.go b/eventarc/apiv1/doc.go index 9b8854f9f4a3..eedf8634da63 100644 --- a/eventarc/apiv1/doc.go +++ b/eventarc/apiv1/doc.go @@ -80,6 +80,8 @@ package eventarc // import "cloud.google.com/go/eventarc/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -168,3 +170,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/eventarc/apiv1/eventarc_client.go b/eventarc/apiv1/eventarc_client.go index 2e7b6f6151b3..ac85d28b6e46 100644 --- a/eventarc/apiv1/eventarc_client.go +++ b/eventarc/apiv1/eventarc_client.go @@ -17,9 +17,12 @@ package eventarc import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,15 +30,18 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" iampb "google.golang.org/genproto/googleapis/iam/v1" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -116,6 +122,38 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + GetTrigger: []gax.CallOption{}, + ListTriggers: []gax.CallOption{}, + CreateTrigger: []gax.CallOption{}, + UpdateTrigger: []gax.CallOption{}, + DeleteTrigger: []gax.CallOption{}, + GetChannel: []gax.CallOption{}, + ListChannels: []gax.CallOption{}, + CreateChannel: []gax.CallOption{}, + UpdateChannel: []gax.CallOption{}, + DeleteChannel: []gax.CallOption{}, + GetProvider: []gax.CallOption{}, + ListProviders: []gax.CallOption{}, + GetChannelConnection: []gax.CallOption{}, + ListChannelConnections: []gax.CallOption{}, + CreateChannelConnection: []gax.CallOption{}, + DeleteChannelConnection: []gax.CallOption{}, + GetGoogleChannelConfig: []gax.CallOption{}, + UpdateGoogleChannelConfig: []gax.CallOption{}, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + GetIamPolicy: []gax.CallOption{}, + SetIamPolicy: []gax.CallOption{}, + TestIamPermissions: []gax.CallOption{}, + CancelOperation: []gax.CallOption{}, + DeleteOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalClient is an interface that defines the methods available from Eventarc API. type internalClient interface { Close() error @@ -500,6 +538,90 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new eventarc rest client. +// +// Eventarc allows users to subscribe to various events that are provided by +// Google Cloud services and forward them to supported destinations. +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://eventarc.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://eventarc.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://eventarc.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) GetTrigger(ctx context.Context, req *eventarcpb.GetTriggerRequest, opts ...gax.CallOption) (*eventarcpb.Trigger, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1135,109 +1257,2011 @@ func (c *gRPCClient) ListOperations(ctx context.Context, req *longrunningpb.List return it } -// CreateChannelOperation manages a long-running operation from CreateChannel. -type CreateChannelOperation struct { - lro *longrunning.Operation -} +// GetTrigger get a single trigger. +func (c *restClient) GetTrigger(ctx context.Context, req *eventarcpb.GetTriggerRequest, opts ...gax.CallOption) (*eventarcpb.Trigger, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) -// CreateChannelOperation returns a new CreateChannelOperation from a given name. -// The name must be that of a previously created CreateChannelOperation, possibly from a different process. -func (c *gRPCClient) CreateChannelOperation(name string) *CreateChannelOperation { - return &CreateChannelOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetTrigger[0:len((*c.CallOptions).GetTrigger):len((*c.CallOptions).GetTrigger)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &eventarcpb.Trigger{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e } + return resp, nil } -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *CreateChannelOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*eventarcpb.Channel, error) { - var resp eventarcpb.Channel - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { - return nil, err +// ListTriggers list triggers. +func (c *restClient) ListTriggers(ctx context.Context, req *eventarcpb.ListTriggersRequest, opts ...gax.CallOption) *TriggerIterator { + it := &TriggerIterator{} + req = proto.Clone(req).(*eventarcpb.ListTriggersRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*eventarcpb.Trigger, string, error) { + resp := &eventarcpb.ListTriggersResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/triggers", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetTriggers(), resp.GetNextPageToken(), nil } - return &resp, 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it } -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *CreateChannelOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*eventarcpb.Channel, error) { - var resp eventarcpb.Channel - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { +// CreateTrigger create a new trigger in a particular project and location. +func (c *restClient) CreateTrigger(ctx context.Context, req *eventarcpb.CreateTriggerRequest, opts ...gax.CallOption) (*CreateTriggerOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetTrigger() + jsonReq, err := m.Marshal(body) + if err != nil { return nil, err } - if !op.Done() { - return nil, nil - } - return &resp, nil -} -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *CreateChannelOperation) Metadata() (*eventarcpb.OperationMetadata, error) { - var meta eventarcpb.OperationMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - return &meta, nil -} + baseUrl.Path += fmt.Sprintf("/v1/%v/triggers", req.GetParent()) -// Done reports whether the long-running operation has completed. -func (op *CreateChannelOperation) Done() bool { - return op.lro.Done() -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("triggerId", fmt.Sprintf("%v", req.GetTriggerId())) + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) -// 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 *CreateChannelOperation) Name() string { - return op.lro.Name() -} + baseUrl.RawQuery = params.Encode() -// CreateChannelConnectionOperation manages a long-running operation from CreateChannelConnection. -type CreateChannelConnectionOperation struct { - lro *longrunning.Operation -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) -// CreateChannelConnectionOperation returns a new CreateChannelConnectionOperation from a given name. -// The name must be that of a previously created CreateChannelConnectionOperation, possibly from a different process. -func (c *gRPCClient) CreateChannelConnectionOperation(name string) *CreateChannelConnectionOperation { - return &CreateChannelConnectionOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateTriggerOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil } -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *CreateChannelConnectionOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*eventarcpb.ChannelConnection, error) { - var resp eventarcpb.ChannelConnection - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { +// UpdateTrigger update a single trigger. +func (c *restClient) UpdateTrigger(ctx context.Context, req *eventarcpb.UpdateTriggerRequest, opts ...gax.CallOption) (*UpdateTriggerOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetTrigger() + jsonReq, err := m.Marshal(body) + if err != nil { return nil, err } - return &resp, nil -} -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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. + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetTrigger().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetAllowMissing() { + params.Add("allowMissing", fmt.Sprintf("%v", req.GetAllowMissing())) + } + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "trigger.name", url.QueryEscape(req.GetTrigger().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateTriggerOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteTrigger delete a single trigger. +func (c *restClient) DeleteTrigger(ctx context.Context, req *eventarcpb.DeleteTriggerRequest, opts ...gax.CallOption) (*DeleteTriggerOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetAllowMissing() { + params.Add("allowMissing", fmt.Sprintf("%v", req.GetAllowMissing())) + } + if req.GetEtag() != "" { + params.Add("etag", fmt.Sprintf("%v", req.GetEtag())) + } + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteTriggerOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetChannel get a single Channel. +func (c *restClient) GetChannel(ctx context.Context, req *eventarcpb.GetChannelRequest, opts ...gax.CallOption) (*eventarcpb.Channel, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetChannel[0:len((*c.CallOptions).GetChannel):len((*c.CallOptions).GetChannel)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &eventarcpb.Channel{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListChannels list channels. +func (c *restClient) ListChannels(ctx context.Context, req *eventarcpb.ListChannelsRequest, opts ...gax.CallOption) *ChannelIterator { + it := &ChannelIterator{} + req = proto.Clone(req).(*eventarcpb.ListChannelsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*eventarcpb.Channel, string, error) { + resp := &eventarcpb.ListChannelsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/channels", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetChannels(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CreateChannel create a new channel in a particular project and location. +func (c *restClient) CreateChannel(ctx context.Context, req *eventarcpb.CreateChannelRequest, opts ...gax.CallOption) (*CreateChannelOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetChannel() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/channels", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("channelId", fmt.Sprintf("%v", req.GetChannelId())) + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateChannelOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateChannel update a single channel. +func (c *restClient) UpdateChannel(ctx context.Context, req *eventarcpb.UpdateChannelRequest, opts ...gax.CallOption) (*UpdateChannelOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetChannel() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetChannel().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "channel.name", url.QueryEscape(req.GetChannel().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateChannelOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteChannel delete a single channel. +func (c *restClient) DeleteChannel(ctx context.Context, req *eventarcpb.DeleteChannelRequest, opts ...gax.CallOption) (*DeleteChannelOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteChannelOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetProvider get a single Provider. +func (c *restClient) GetProvider(ctx context.Context, req *eventarcpb.GetProviderRequest, opts ...gax.CallOption) (*eventarcpb.Provider, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetProvider[0:len((*c.CallOptions).GetProvider):len((*c.CallOptions).GetProvider)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &eventarcpb.Provider{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListProviders list providers. +func (c *restClient) ListProviders(ctx context.Context, req *eventarcpb.ListProvidersRequest, opts ...gax.CallOption) *ProviderIterator { + it := &ProviderIterator{} + req = proto.Clone(req).(*eventarcpb.ListProvidersRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*eventarcpb.Provider, string, error) { + resp := &eventarcpb.ListProvidersResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/providers", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetProviders(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetChannelConnection get a single ChannelConnection. +func (c *restClient) GetChannelConnection(ctx context.Context, req *eventarcpb.GetChannelConnectionRequest, opts ...gax.CallOption) (*eventarcpb.ChannelConnection, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetChannelConnection[0:len((*c.CallOptions).GetChannelConnection):len((*c.CallOptions).GetChannelConnection)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &eventarcpb.ChannelConnection{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListChannelConnections list channel connections. +func (c *restClient) ListChannelConnections(ctx context.Context, req *eventarcpb.ListChannelConnectionsRequest, opts ...gax.CallOption) *ChannelConnectionIterator { + it := &ChannelConnectionIterator{} + req = proto.Clone(req).(*eventarcpb.ListChannelConnectionsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*eventarcpb.ChannelConnection, string, error) { + resp := &eventarcpb.ListChannelConnectionsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/channelConnections", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetChannelConnections(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CreateChannelConnection create a new ChannelConnection in a particular project and location. +func (c *restClient) CreateChannelConnection(ctx context.Context, req *eventarcpb.CreateChannelConnectionRequest, opts ...gax.CallOption) (*CreateChannelConnectionOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetChannelConnection() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/channelConnections", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("channelConnectionId", fmt.Sprintf("%v", req.GetChannelConnectionId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateChannelConnectionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteChannelConnection delete a single ChannelConnection. +func (c *restClient) DeleteChannelConnection(ctx context.Context, req *eventarcpb.DeleteChannelConnectionRequest, opts ...gax.CallOption) (*DeleteChannelConnectionOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteChannelConnectionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetGoogleChannelConfig get a GoogleChannelConfig +func (c *restClient) GetGoogleChannelConfig(ctx context.Context, req *eventarcpb.GetGoogleChannelConfigRequest, opts ...gax.CallOption) (*eventarcpb.GoogleChannelConfig, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetGoogleChannelConfig[0:len((*c.CallOptions).GetGoogleChannelConfig):len((*c.CallOptions).GetGoogleChannelConfig)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &eventarcpb.GoogleChannelConfig{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateGoogleChannelConfig update a single GoogleChannelConfig +func (c *restClient) UpdateGoogleChannelConfig(ctx context.Context, req *eventarcpb.UpdateGoogleChannelConfigRequest, opts ...gax.CallOption) (*eventarcpb.GoogleChannelConfig, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetGoogleChannelConfig() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetGoogleChannelConfig().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "google_channel_config.name", url.QueryEscape(req.GetGoogleChannelConfig().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateGoogleChannelConfig[0:len((*c.CallOptions).UpdateGoogleChannelConfig):len((*c.CallOptions).UpdateGoogleChannelConfig)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &eventarcpb.GoogleChannelConfig{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetLocation gets information about a location. +func (c *restClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *restClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetIamPolicy gets the access control policy for a resource. Returns an empty policy +// if the resource exists and does not have a policy set. +func (c *restClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:getIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetOptions().GetRequestedPolicyVersion() != 0 { + params.Add("options.requestedPolicyVersion", fmt.Sprintf("%v", req.GetOptions().GetRequestedPolicyVersion())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SetIamPolicy sets the access control policy on the specified resource. Replaces +// any existing policy. +// +// Can return NOT_FOUND, INVALID_ARGUMENT, and PERMISSION_DENIED +// errors. +func (c *restClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:setIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// TestIamPermissions returns permissions that a caller has on the specified resource. If the +// resource does not exist, this will return an empty set of +// permissions, not a NOT_FOUND error. +// +// Note: This operation is designed to be used for building +// permission-aware UIs and command-line tools, not for authorization +// checking. This operation may “fail open” without warning. +func (c *restClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:testIamPermissions", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.TestIamPermissionsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *restClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// DeleteOperation is a utility method from google.longrunning.Operations. +func (c *restClient) DeleteOperation(ctx context.Context, req *longrunningpb.DeleteOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *restClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *restClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CreateChannelOperation manages a long-running operation from CreateChannel. +type CreateChannelOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateChannelOperation returns a new CreateChannelOperation from a given name. +// The name must be that of a previously created CreateChannelOperation, possibly from a different process. +func (c *gRPCClient) CreateChannelOperation(name string) *CreateChannelOperation { + return &CreateChannelOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateChannelOperation returns a new CreateChannelOperation from a given name. +// The name must be that of a previously created CreateChannelOperation, possibly from a different process. +func (c *restClient) CreateChannelOperation(name string) *CreateChannelOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateChannelOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CreateChannelOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*eventarcpb.Channel, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp eventarcpb.Channel + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *CreateChannelOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*eventarcpb.Channel, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp eventarcpb.Channel + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *CreateChannelOperation) Metadata() (*eventarcpb.OperationMetadata, error) { + var meta eventarcpb.OperationMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *CreateChannelOperation) Done() bool { + return op.lro.Done() +} + +// 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 *CreateChannelOperation) Name() string { + return op.lro.Name() +} + +// CreateChannelConnectionOperation manages a long-running operation from CreateChannelConnection. +type CreateChannelConnectionOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateChannelConnectionOperation returns a new CreateChannelConnectionOperation from a given name. +// The name must be that of a previously created CreateChannelConnectionOperation, possibly from a different process. +func (c *gRPCClient) CreateChannelConnectionOperation(name string) *CreateChannelConnectionOperation { + return &CreateChannelConnectionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateChannelConnectionOperation returns a new CreateChannelConnectionOperation from a given name. +// The name must be that of a previously created CreateChannelConnectionOperation, possibly from a different process. +func (c *restClient) CreateChannelConnectionOperation(name string) *CreateChannelConnectionOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateChannelConnectionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CreateChannelConnectionOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*eventarcpb.ChannelConnection, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp eventarcpb.ChannelConnection + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateChannelConnectionOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*eventarcpb.ChannelConnection, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp eventarcpb.ChannelConnection if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1275,7 +3299,8 @@ func (op *CreateChannelConnectionOperation) Name() string { // CreateTriggerOperation manages a long-running operation from CreateTrigger. type CreateTriggerOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateTriggerOperation returns a new CreateTriggerOperation from a given name. @@ -1286,10 +3311,21 @@ func (c *gRPCClient) CreateTriggerOperation(name string) *CreateTriggerOperation } } +// CreateTriggerOperation returns a new CreateTriggerOperation from a given name. +// The name must be that of a previously created CreateTriggerOperation, possibly from a different process. +func (c *restClient) CreateTriggerOperation(name string) *CreateTriggerOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateTriggerOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateTriggerOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*eventarcpb.Trigger, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp eventarcpb.Trigger if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1307,6 +3343,7 @@ func (op *CreateTriggerOperation) Wait(ctx context.Context, opts ...gax.CallOpti // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateTriggerOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*eventarcpb.Trigger, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp eventarcpb.Trigger if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1344,7 +3381,8 @@ func (op *CreateTriggerOperation) Name() string { // DeleteChannelOperation manages a long-running operation from DeleteChannel. type DeleteChannelOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteChannelOperation returns a new DeleteChannelOperation from a given name. @@ -1355,10 +3393,21 @@ func (c *gRPCClient) DeleteChannelOperation(name string) *DeleteChannelOperation } } +// DeleteChannelOperation returns a new DeleteChannelOperation from a given name. +// The name must be that of a previously created DeleteChannelOperation, possibly from a different process. +func (c *restClient) DeleteChannelOperation(name string) *DeleteChannelOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteChannelOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteChannelOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*eventarcpb.Channel, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp eventarcpb.Channel if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1376,6 +3425,7 @@ func (op *DeleteChannelOperation) Wait(ctx context.Context, opts ...gax.CallOpti // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteChannelOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*eventarcpb.Channel, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp eventarcpb.Channel if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1413,7 +3463,8 @@ func (op *DeleteChannelOperation) Name() string { // DeleteChannelConnectionOperation manages a long-running operation from DeleteChannelConnection. type DeleteChannelConnectionOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteChannelConnectionOperation returns a new DeleteChannelConnectionOperation from a given name. @@ -1424,10 +3475,21 @@ func (c *gRPCClient) DeleteChannelConnectionOperation(name string) *DeleteChanne } } +// DeleteChannelConnectionOperation returns a new DeleteChannelConnectionOperation from a given name. +// The name must be that of a previously created DeleteChannelConnectionOperation, possibly from a different process. +func (c *restClient) DeleteChannelConnectionOperation(name string) *DeleteChannelConnectionOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteChannelConnectionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteChannelConnectionOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*eventarcpb.ChannelConnection, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp eventarcpb.ChannelConnection if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1445,6 +3507,7 @@ func (op *DeleteChannelConnectionOperation) Wait(ctx context.Context, opts ...ga // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteChannelConnectionOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*eventarcpb.ChannelConnection, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp eventarcpb.ChannelConnection if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1482,7 +3545,8 @@ func (op *DeleteChannelConnectionOperation) Name() string { // DeleteTriggerOperation manages a long-running operation from DeleteTrigger. type DeleteTriggerOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteTriggerOperation returns a new DeleteTriggerOperation from a given name. @@ -1493,10 +3557,21 @@ func (c *gRPCClient) DeleteTriggerOperation(name string) *DeleteTriggerOperation } } +// DeleteTriggerOperation returns a new DeleteTriggerOperation from a given name. +// The name must be that of a previously created DeleteTriggerOperation, possibly from a different process. +func (c *restClient) DeleteTriggerOperation(name string) *DeleteTriggerOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteTriggerOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteTriggerOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*eventarcpb.Trigger, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp eventarcpb.Trigger if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1514,6 +3589,7 @@ func (op *DeleteTriggerOperation) Wait(ctx context.Context, opts ...gax.CallOpti // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteTriggerOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*eventarcpb.Trigger, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp eventarcpb.Trigger if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1551,7 +3627,8 @@ func (op *DeleteTriggerOperation) Name() string { // UpdateChannelOperation manages a long-running operation from UpdateChannel. type UpdateChannelOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateChannelOperation returns a new UpdateChannelOperation from a given name. @@ -1562,10 +3639,21 @@ func (c *gRPCClient) UpdateChannelOperation(name string) *UpdateChannelOperation } } +// UpdateChannelOperation returns a new UpdateChannelOperation from a given name. +// The name must be that of a previously created UpdateChannelOperation, possibly from a different process. +func (c *restClient) UpdateChannelOperation(name string) *UpdateChannelOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateChannelOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateChannelOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*eventarcpb.Channel, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp eventarcpb.Channel if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1583,6 +3671,7 @@ func (op *UpdateChannelOperation) Wait(ctx context.Context, opts ...gax.CallOpti // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateChannelOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*eventarcpb.Channel, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp eventarcpb.Channel if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1620,7 +3709,8 @@ func (op *UpdateChannelOperation) Name() string { // UpdateTriggerOperation manages a long-running operation from UpdateTrigger. type UpdateTriggerOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateTriggerOperation returns a new UpdateTriggerOperation from a given name. @@ -1631,10 +3721,21 @@ func (c *gRPCClient) UpdateTriggerOperation(name string) *UpdateTriggerOperation } } +// UpdateTriggerOperation returns a new UpdateTriggerOperation from a given name. +// The name must be that of a previously created UpdateTriggerOperation, possibly from a different process. +func (c *restClient) UpdateTriggerOperation(name string) *UpdateTriggerOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateTriggerOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateTriggerOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*eventarcpb.Trigger, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp eventarcpb.Trigger if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1652,6 +3753,7 @@ func (op *UpdateTriggerOperation) Wait(ctx context.Context, opts ...gax.CallOpti // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateTriggerOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*eventarcpb.Trigger, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp eventarcpb.Trigger if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/eventarc/apiv1/eventarc_client_example_test.go b/eventarc/apiv1/eventarc_client_example_test.go index be2f6bbf969b..017e7345deed 100644 --- a/eventarc/apiv1/eventarc_client_example_test.go +++ b/eventarc/apiv1/eventarc_client_example_test.go @@ -44,6 +44,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := eventarc.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_GetTrigger() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/eventarc/apiv1/eventarcpb/channel.pb.go b/eventarc/apiv1/eventarcpb/channel.pb.go index ad38540d8e92..30b25eac20cf 100644 --- a/eventarc/apiv1/eventarcpb/channel.pb.go +++ b/eventarc/apiv1/eventarcpb/channel.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/eventarc/v1/channel.proto package eventarcpb @@ -55,9 +55,9 @@ const ( // The INACTIVE state indicates that the Channel cannot receive events // permanently. There are two possible cases this state can happen: // - // 1. The SaaS provider disconnected from this Channel. - // 2. The Channel activation token has expired but the SaaS provider - // wasn't connected. + // 1. The SaaS provider disconnected from this Channel. + // 2. The Channel activation token has expired but the SaaS provider + // wasn't connected. // // To re-establish a Connection with a provider, the subscriber // should create a new Channel and give it to the provider. @@ -134,7 +134,6 @@ type Channel struct { // `projects/{project}/locations/{location}/providers/{provider_id}`. Provider string `protobuf:"bytes,7,opt,name=provider,proto3" json:"provider,omitempty"` // Types that are assignable to Transport: - // // *Channel_PubsubTopic Transport isChannel_Transport `protobuf_oneof:"transport"` // Output only. The state of a Channel. diff --git a/eventarc/apiv1/eventarcpb/channel_connection.pb.go b/eventarc/apiv1/eventarcpb/channel_connection.pb.go index e29096e6e3a7..8c11fe5af9c6 100644 --- a/eventarc/apiv1/eventarcpb/channel_connection.pb.go +++ b/eventarc/apiv1/eventarcpb/channel_connection.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/eventarc/v1/channel_connection.proto package eventarcpb diff --git a/eventarc/apiv1/eventarcpb/discovery.pb.go b/eventarc/apiv1/eventarcpb/discovery.pb.go index 5adcd1050636..a5ed4d4f9ff2 100644 --- a/eventarc/apiv1/eventarcpb/discovery.pb.go +++ b/eventarc/apiv1/eventarcpb/discovery.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/eventarc/v1/discovery.proto package eventarcpb diff --git a/eventarc/apiv1/eventarcpb/eventarc.pb.go b/eventarc/apiv1/eventarcpb/eventarc.pb.go index be9c5d71520a..c3e61ba352b0 100644 --- a/eventarc/apiv1/eventarcpb/eventarc.pb.go +++ b/eventarc/apiv1/eventarcpb/eventarc.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/eventarc/v1/eventarc.proto package eventarcpb diff --git a/eventarc/apiv1/eventarcpb/google_channel_config.pb.go b/eventarc/apiv1/eventarcpb/google_channel_config.pb.go index d6339e02f28b..d77790f27942 100644 --- a/eventarc/apiv1/eventarcpb/google_channel_config.pb.go +++ b/eventarc/apiv1/eventarcpb/google_channel_config.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/eventarc/v1/google_channel_config.proto package eventarcpb diff --git a/eventarc/apiv1/eventarcpb/trigger.pb.go b/eventarc/apiv1/eventarcpb/trigger.pb.go index 81185bbc7f92..bb31db930b3f 100644 --- a/eventarc/apiv1/eventarcpb/trigger.pb.go +++ b/eventarc/apiv1/eventarcpb/trigger.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/eventarc/v1/trigger.proto package eventarcpb @@ -331,7 +331,7 @@ func (x *StateCondition) GetCode() code.Code { if x != nil { return x.Code } - return code.Code_OK + return code.Code(0) } func (x *StateCondition) GetMessage() string { @@ -348,7 +348,6 @@ type Destination struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Descriptor_: - // // *Destination_CloudRun // *Destination_CloudFunction // *Destination_Gke @@ -469,7 +468,6 @@ type Transport struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Intermediary: - // // *Transport_Pubsub Intermediary isTransport_Intermediary `protobuf_oneof:"intermediary"` } diff --git a/eventarc/apiv1/gapic_metadata.json b/eventarc/apiv1/gapic_metadata.json index e682d9772f34..3f1eb2552be5 100644 --- a/eventarc/apiv1/gapic_metadata.json +++ b/eventarc/apiv1/gapic_metadata.json @@ -146,6 +146,146 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "CreateChannel": { + "methods": [ + "CreateChannel" + ] + }, + "CreateChannelConnection": { + "methods": [ + "CreateChannelConnection" + ] + }, + "CreateTrigger": { + "methods": [ + "CreateTrigger" + ] + }, + "DeleteChannel": { + "methods": [ + "DeleteChannel" + ] + }, + "DeleteChannelConnection": { + "methods": [ + "DeleteChannelConnection" + ] + }, + "DeleteOperation": { + "methods": [ + "DeleteOperation" + ] + }, + "DeleteTrigger": { + "methods": [ + "DeleteTrigger" + ] + }, + "GetChannel": { + "methods": [ + "GetChannel" + ] + }, + "GetChannelConnection": { + "methods": [ + "GetChannelConnection" + ] + }, + "GetGoogleChannelConfig": { + "methods": [ + "GetGoogleChannelConfig" + ] + }, + "GetIamPolicy": { + "methods": [ + "GetIamPolicy" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "GetProvider": { + "methods": [ + "GetProvider" + ] + }, + "GetTrigger": { + "methods": [ + "GetTrigger" + ] + }, + "ListChannelConnections": { + "methods": [ + "ListChannelConnections" + ] + }, + "ListChannels": { + "methods": [ + "ListChannels" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "ListProviders": { + "methods": [ + "ListProviders" + ] + }, + "ListTriggers": { + "methods": [ + "ListTriggers" + ] + }, + "SetIamPolicy": { + "methods": [ + "SetIamPolicy" + ] + }, + "TestIamPermissions": { + "methods": [ + "TestIamPermissions" + ] + }, + "UpdateChannel": { + "methods": [ + "UpdateChannel" + ] + }, + "UpdateGoogleChannelConfig": { + "methods": [ + "UpdateGoogleChannelConfig" + ] + }, + "UpdateTrigger": { + "methods": [ + "UpdateTrigger" + ] + } + } } } } diff --git a/eventarc/publishing/apiv1/doc.go b/eventarc/publishing/apiv1/doc.go index 8ae073db3658..89907f48247b 100644 --- a/eventarc/publishing/apiv1/doc.go +++ b/eventarc/publishing/apiv1/doc.go @@ -80,6 +80,8 @@ package publishing // import "cloud.google.com/go/eventarc/publishing/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -168,3 +170,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/eventarc/publishing/apiv1/gapic_metadata.json b/eventarc/publishing/apiv1/gapic_metadata.json index 81f523640acc..0cd1c96c82ae 100644 --- a/eventarc/publishing/apiv1/gapic_metadata.json +++ b/eventarc/publishing/apiv1/gapic_metadata.json @@ -21,6 +21,21 @@ ] } } + }, + "rest": { + "libraryClient": "PublisherClient", + "rpcs": { + "PublishChannelConnectionEvents": { + "methods": [ + "PublishChannelConnectionEvents" + ] + }, + "PublishEvents": { + "methods": [ + "PublishEvents" + ] + } + } } } } diff --git a/eventarc/publishing/apiv1/publisher_client.go b/eventarc/publishing/apiv1/publisher_client.go index 75b8f1c11c8e..42b3413c9319 100644 --- a/eventarc/publishing/apiv1/publisher_client.go +++ b/eventarc/publishing/apiv1/publisher_client.go @@ -17,19 +17,25 @@ package publishing import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" publishingpb "cloud.google.com/go/eventarc/publishing/apiv1/publishingpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" ) var newPublisherClientHook clientHook @@ -59,6 +65,13 @@ func defaultPublisherCallOptions() *PublisherCallOptions { } } +func defaultPublisherRESTCallOptions() *PublisherCallOptions { + return &PublisherCallOptions{ + PublishChannelConnectionEvents: []gax.CallOption{}, + PublishEvents: []gax.CallOption{}, + } +} + // internalPublisherClient is an interface that defines the methods available from Eventarc Publishing API. type internalPublisherClient interface { Close() error @@ -240,6 +253,97 @@ func (c *publisherGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type publisherRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing PublisherClient + CallOptions **PublisherCallOptions +} + +// NewPublisherRESTClient creates a new publisher rest client. +// +// Eventarc processes events generated by an event provider and delivers them to +// a subscriber. +// +// An event provider is a software-as-a-service (SaaS) system or +// product that can generate and deliver events through Eventarc. +// +// A third-party event provider is an event provider from outside of Google. +// +// A partner is a third-party event provider that is integrated with Eventarc. +// +// A subscriber is a GCP customer interested in receiving events. +// +// Channel is a first-class Eventarc resource that is created and managed +// by the subscriber in their GCP project. A Channel represents a subscriber’s +// intent to receive events from an event provider. A Channel is associated with +// exactly one event provider. +// +// ChannelConnection is a first-class Eventarc resource that +// is created and managed by the partner in their GCP project. A +// ChannelConnection represents a connection between a partner and a +// subscriber’s Channel. A ChannelConnection has a one-to-one mapping with a +// Channel. +// +// Publisher allows an event provider to publish events to Eventarc. +func NewPublisherRESTClient(ctx context.Context, opts ...option.ClientOption) (*PublisherClient, error) { + clientOpts := append(defaultPublisherRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultPublisherRESTCallOptions() + c := &publisherRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &PublisherClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultPublisherRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://eventarcpublishing.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://eventarcpublishing.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://eventarcpublishing.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *publisherRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *publisherRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *publisherRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *publisherGRPCClient) PublishChannelConnectionEvents(ctx context.Context, req *publishingpb.PublishChannelConnectionEventsRequest, opts ...gax.CallOption) (*publishingpb.PublishChannelConnectionEventsResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) @@ -278,3 +382,131 @@ func (c *publisherGRPCClient) PublishEvents(ctx context.Context, req *publishing } return resp, nil } + +// PublishChannelConnectionEvents publish events to a ChannelConnection in a partner’s project. +func (c *publisherRESTClient) PublishChannelConnectionEvents(ctx context.Context, req *publishingpb.PublishChannelConnectionEventsRequest, opts ...gax.CallOption) (*publishingpb.PublishChannelConnectionEventsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:publishEvents", req.GetChannelConnection()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "channel_connection", url.QueryEscape(req.GetChannelConnection()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).PublishChannelConnectionEvents[0:len((*c.CallOptions).PublishChannelConnectionEvents):len((*c.CallOptions).PublishChannelConnectionEvents)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &publishingpb.PublishChannelConnectionEventsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// PublishEvents publish events to a subscriber’s channel. +func (c *publisherRESTClient) PublishEvents(ctx context.Context, req *publishingpb.PublishEventsRequest, opts ...gax.CallOption) (*publishingpb.PublishEventsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:publishEvents", req.GetChannel()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "channel", url.QueryEscape(req.GetChannel()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).PublishEvents[0:len((*c.CallOptions).PublishEvents):len((*c.CallOptions).PublishEvents)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &publishingpb.PublishEventsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} diff --git a/eventarc/publishing/apiv1/publisher_client_example_test.go b/eventarc/publishing/apiv1/publisher_client_example_test.go index 8d76c2ed8339..eaf06a0358d5 100644 --- a/eventarc/publishing/apiv1/publisher_client_example_test.go +++ b/eventarc/publishing/apiv1/publisher_client_example_test.go @@ -40,6 +40,23 @@ func ExampleNewPublisherClient() { _ = c } +func ExampleNewPublisherRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := publishing.NewPublisherRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExamplePublisherClient_PublishChannelConnectionEvents() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/eventarc/publishing/apiv1/publishingpb/publisher.pb.go b/eventarc/publishing/apiv1/publishingpb/publisher.pb.go index 88dbbfd8e12c..4815943d34f4 100644 --- a/eventarc/publishing/apiv1/publishingpb/publisher.pb.go +++ b/eventarc/publishing/apiv1/publishingpb/publisher.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/eventarc/publishing/v1/publisher.proto package publishingpb diff --git a/filestore/apiv1/cloud_filestore_manager_client.go b/filestore/apiv1/cloud_filestore_manager_client.go index fad7dfb6ee31..3a859300cc56 100644 --- a/filestore/apiv1/cloud_filestore_manager_client.go +++ b/filestore/apiv1/cloud_filestore_manager_client.go @@ -17,9 +17,12 @@ package filestore import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,15 +30,18 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" commonpb "google.golang.org/genproto/googleapis/cloud/common" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -124,6 +130,58 @@ func defaultCloudFilestoreManagerCallOptions() *CloudFilestoreManagerCallOptions } } +func defaultCloudFilestoreManagerRESTCallOptions() *CloudFilestoreManagerCallOptions { + return &CloudFilestoreManagerCallOptions{ + ListInstances: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 250 * time.Millisecond, + Max: 32000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetInstance: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 250 * time.Millisecond, + Max: 32000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateInstance: []gax.CallOption{}, + UpdateInstance: []gax.CallOption{}, + RestoreInstance: []gax.CallOption{}, + DeleteInstance: []gax.CallOption{}, + ListBackups: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 250 * time.Millisecond, + Max: 32000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetBackup: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 250 * time.Millisecond, + Max: 32000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateBackup: []gax.CallOption{}, + DeleteBackup: []gax.CallOption{}, + UpdateBackup: []gax.CallOption{}, + } +} + // internalCloudFilestoreManagerClient is an interface that defines the methods available from Cloud Filestore API. type internalCloudFilestoreManagerClient interface { Close() error @@ -440,6 +498,113 @@ func (c *cloudFilestoreManagerGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type cloudFilestoreManagerRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing CloudFilestoreManagerClient + CallOptions **CloudFilestoreManagerCallOptions +} + +// NewCloudFilestoreManagerRESTClient creates a new cloud filestore manager rest client. +// +// Configures and manages Cloud Filestore resources. +// +// Cloud Filestore Manager v1. +// +// The file.googleapis.com service implements the Cloud Filestore API and +// defines the following resource model for managing instances: +// +// The service works with a collection of cloud projects, named: /projects/* +// +// Each project has a collection of available locations, named: /locations/* +// +// Each location has a collection of instances and backups, named: +// /instances/* and /backups/* respectively. +// +// As such, Cloud Filestore instances are resources of the form: +// /projects/{project_number}/locations/{location_id}/instances/{instance_id} +// and backups are resources of the form: +// /projects/{project_number}/locations/{location_id}/backup/{backup_id} +// +// Note that location_id must be a GCP zone for instances and but to a GCP +// region for backups; for example: +// +// projects/12345/locations/us-central1-c/instances/my-filestore +// +// projects/12345/locations/us-central1/backups/my-backup +func NewCloudFilestoreManagerRESTClient(ctx context.Context, opts ...option.ClientOption) (*CloudFilestoreManagerClient, error) { + clientOpts := append(defaultCloudFilestoreManagerRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultCloudFilestoreManagerRESTCallOptions() + c := &cloudFilestoreManagerRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &CloudFilestoreManagerClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultCloudFilestoreManagerRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://file.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://file.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://file.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *cloudFilestoreManagerRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *cloudFilestoreManagerRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *cloudFilestoreManagerRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *cloudFilestoreManagerGRPCClient) ListInstances(ctx context.Context, req *filestorepb.ListInstancesRequest, opts ...gax.CallOption) *InstanceIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -742,102 +907,924 @@ func (c *cloudFilestoreManagerGRPCClient) UpdateBackup(ctx context.Context, req }, nil } -// CreateBackupOperation manages a long-running operation from CreateBackup. -type CreateBackupOperation struct { - lro *longrunning.Operation -} +// ListInstances lists all instances in a project for either a specified location +// or for all locations. +func (c *cloudFilestoreManagerRESTClient) ListInstances(ctx context.Context, req *filestorepb.ListInstancesRequest, opts ...gax.CallOption) *InstanceIterator { + it := &InstanceIterator{} + req = proto.Clone(req).(*filestorepb.ListInstancesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*filestorepb.Instance, string, error) { + resp := &filestorepb.ListInstancesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/instances", req.GetParent()) -// CreateBackupOperation returns a new CreateBackupOperation from a given name. -// The name must be that of a previously created CreateBackupOperation, possibly from a different process. -func (c *cloudFilestoreManagerGRPCClient) CreateBackupOperation(name string) *CreateBackupOperation { - return &CreateBackupOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *CreateBackupOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*filestorepb.Backup, error) { - var resp filestorepb.Backup - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { - return nil, err + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetInstances(), resp.GetNextPageToken(), nil } - return &resp, nil -} -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *CreateBackupOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*filestorepb.Backup, error) { - var resp filestorepb.Backup - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { - return nil, err - } - if !op.Done() { - return nil, 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 } - return &resp, nil + + it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it } -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *CreateBackupOperation) Metadata() (*commonpb.OperationMetadata, error) { - var meta commonpb.OperationMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { +// GetInstance gets the details of a specific instance. +func (c *cloudFilestoreManagerRESTClient) GetInstance(ctx context.Context, req *filestorepb.GetInstanceRequest, opts ...gax.CallOption) (*filestorepb.Instance, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - return &meta, nil -} + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) -// Done reports whether the long-running operation has completed. -func (op *CreateBackupOperation) Done() bool { - return op.lro.Done() -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") -// 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 *CreateBackupOperation) Name() string { - return op.lro.Name() -} + baseUrl.RawQuery = params.Encode() -// CreateInstanceOperation manages a long-running operation from CreateInstance. -type CreateInstanceOperation struct { - lro *longrunning.Operation -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) -// CreateInstanceOperation returns a new CreateInstanceOperation from a given name. -// The name must be that of a previously created CreateInstanceOperation, possibly from a different process. -func (c *cloudFilestoreManagerGRPCClient) CreateInstanceOperation(name string) *CreateInstanceOperation { - return &CreateInstanceOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetInstance[0:len((*c.CallOptions).GetInstance):len((*c.CallOptions).GetInstance)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &filestorepb.Instance{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e } + return resp, nil } -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *CreateInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*filestorepb.Instance, error) { - var resp filestorepb.Instance - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { +// CreateInstance creates an instance. +// When creating from a backup, the capacity of the new instance needs to be +// equal to or larger than the capacity of the backup (and also equal to or +// larger than the minimum capacity of the tier). +func (c *cloudFilestoreManagerRESTClient) CreateInstance(ctx context.Context, req *filestorepb.CreateInstanceRequest, opts ...gax.CallOption) (*CreateInstanceOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetInstance() + jsonReq, err := m.Marshal(body) + if err != nil { return nil, err } - return &resp, nil -} -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/instances", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("instanceId", fmt.Sprintf("%v", req.GetInstanceId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateInstance updates the settings of a specific instance. +func (c *cloudFilestoreManagerRESTClient) UpdateInstance(ctx context.Context, req *filestorepb.UpdateInstanceRequest, opts ...gax.CallOption) (*UpdateInstanceOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetInstance() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetInstance().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "instance.name", url.QueryEscape(req.GetInstance().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// RestoreInstance restores an existing instance’s file share from a backup. +// +// The capacity of the instance needs to be equal to or larger than the +// capacity of the backup (and also equal to or larger than the minimum +// capacity of the tier). +func (c *cloudFilestoreManagerRESTClient) RestoreInstance(ctx context.Context, req *filestorepb.RestoreInstanceRequest, opts ...gax.CallOption) (*RestoreInstanceOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:restore", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &RestoreInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteInstance deletes an instance. +func (c *cloudFilestoreManagerRESTClient) DeleteInstance(ctx context.Context, req *filestorepb.DeleteInstanceRequest, opts ...gax.CallOption) (*DeleteInstanceOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListBackups lists all backups in a project for either a specified location or for all +// locations. +func (c *cloudFilestoreManagerRESTClient) ListBackups(ctx context.Context, req *filestorepb.ListBackupsRequest, opts ...gax.CallOption) *BackupIterator { + it := &BackupIterator{} + req = proto.Clone(req).(*filestorepb.ListBackupsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*filestorepb.Backup, string, error) { + resp := &filestorepb.ListBackupsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/backups", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetBackups(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetBackup gets the details of a specific backup. +func (c *cloudFilestoreManagerRESTClient) GetBackup(ctx context.Context, req *filestorepb.GetBackupRequest, opts ...gax.CallOption) (*filestorepb.Backup, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetBackup[0:len((*c.CallOptions).GetBackup):len((*c.CallOptions).GetBackup)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &filestorepb.Backup{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateBackup creates a backup. +func (c *cloudFilestoreManagerRESTClient) CreateBackup(ctx context.Context, req *filestorepb.CreateBackupRequest, opts ...gax.CallOption) (*CreateBackupOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetBackup() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/backups", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("backupId", fmt.Sprintf("%v", req.GetBackupId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateBackupOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteBackup deletes a backup. +func (c *cloudFilestoreManagerRESTClient) DeleteBackup(ctx context.Context, req *filestorepb.DeleteBackupRequest, opts ...gax.CallOption) (*DeleteBackupOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteBackupOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateBackup updates the settings of a specific backup. +func (c *cloudFilestoreManagerRESTClient) UpdateBackup(ctx context.Context, req *filestorepb.UpdateBackupRequest, opts ...gax.CallOption) (*UpdateBackupOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetBackup() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetBackup().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "backup.name", url.QueryEscape(req.GetBackup().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateBackupOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// CreateBackupOperation manages a long-running operation from CreateBackup. +type CreateBackupOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateBackupOperation returns a new CreateBackupOperation from a given name. +// The name must be that of a previously created CreateBackupOperation, possibly from a different process. +func (c *cloudFilestoreManagerGRPCClient) CreateBackupOperation(name string) *CreateBackupOperation { + return &CreateBackupOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateBackupOperation returns a new CreateBackupOperation from a given name. +// The name must be that of a previously created CreateBackupOperation, possibly from a different process. +func (c *cloudFilestoreManagerRESTClient) CreateBackupOperation(name string) *CreateBackupOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateBackupOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CreateBackupOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*filestorepb.Backup, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp filestorepb.Backup + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *CreateBackupOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*filestorepb.Backup, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp filestorepb.Backup + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *CreateBackupOperation) Metadata() (*commonpb.OperationMetadata, error) { + var meta commonpb.OperationMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *CreateBackupOperation) Done() bool { + return op.lro.Done() +} + +// 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 *CreateBackupOperation) Name() string { + return op.lro.Name() +} + +// CreateInstanceOperation manages a long-running operation from CreateInstance. +type CreateInstanceOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateInstanceOperation returns a new CreateInstanceOperation from a given name. +// The name must be that of a previously created CreateInstanceOperation, possibly from a different process. +func (c *cloudFilestoreManagerGRPCClient) CreateInstanceOperation(name string) *CreateInstanceOperation { + return &CreateInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateInstanceOperation returns a new CreateInstanceOperation from a given name. +// The name must be that of a previously created CreateInstanceOperation, possibly from a different process. +func (c *cloudFilestoreManagerRESTClient) CreateInstanceOperation(name string) *CreateInstanceOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CreateInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*filestorepb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp filestorepb.Instance + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. // // 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. @@ -845,6 +1832,7 @@ func (op *CreateInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOpt // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateInstanceOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*filestorepb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp filestorepb.Instance if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -882,7 +1870,8 @@ func (op *CreateInstanceOperation) Name() string { // DeleteBackupOperation manages a long-running operation from DeleteBackup. type DeleteBackupOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteBackupOperation returns a new DeleteBackupOperation from a given name. @@ -893,10 +1882,21 @@ func (c *cloudFilestoreManagerGRPCClient) DeleteBackupOperation(name string) *De } } +// DeleteBackupOperation returns a new DeleteBackupOperation from a given name. +// The name must be that of a previously created DeleteBackupOperation, possibly from a different process. +func (c *cloudFilestoreManagerRESTClient) DeleteBackupOperation(name string) *DeleteBackupOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteBackupOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteBackupOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -910,6 +1910,7 @@ func (op *DeleteBackupOperation) Wait(ctx context.Context, opts ...gax.CallOptio // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteBackupOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -940,7 +1941,8 @@ func (op *DeleteBackupOperation) Name() string { // DeleteInstanceOperation manages a long-running operation from DeleteInstance. type DeleteInstanceOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteInstanceOperation returns a new DeleteInstanceOperation from a given name. @@ -951,10 +1953,21 @@ func (c *cloudFilestoreManagerGRPCClient) DeleteInstanceOperation(name string) * } } +// DeleteInstanceOperation returns a new DeleteInstanceOperation from a given name. +// The name must be that of a previously created DeleteInstanceOperation, possibly from a different process. +func (c *cloudFilestoreManagerRESTClient) DeleteInstanceOperation(name string) *DeleteInstanceOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -968,6 +1981,7 @@ func (op *DeleteInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOpt // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteInstanceOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -998,7 +2012,8 @@ func (op *DeleteInstanceOperation) Name() string { // RestoreInstanceOperation manages a long-running operation from RestoreInstance. type RestoreInstanceOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // RestoreInstanceOperation returns a new RestoreInstanceOperation from a given name. @@ -1009,10 +2024,21 @@ func (c *cloudFilestoreManagerGRPCClient) RestoreInstanceOperation(name string) } } +// RestoreInstanceOperation returns a new RestoreInstanceOperation from a given name. +// The name must be that of a previously created RestoreInstanceOperation, possibly from a different process. +func (c *cloudFilestoreManagerRESTClient) RestoreInstanceOperation(name string) *RestoreInstanceOperation { + override := fmt.Sprintf("/v1/%s", name) + return &RestoreInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *RestoreInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*filestorepb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp filestorepb.Instance if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1030,6 +2056,7 @@ func (op *RestoreInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOp // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *RestoreInstanceOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*filestorepb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp filestorepb.Instance if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1067,7 +2094,8 @@ func (op *RestoreInstanceOperation) Name() string { // UpdateBackupOperation manages a long-running operation from UpdateBackup. type UpdateBackupOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateBackupOperation returns a new UpdateBackupOperation from a given name. @@ -1078,10 +2106,21 @@ func (c *cloudFilestoreManagerGRPCClient) UpdateBackupOperation(name string) *Up } } +// UpdateBackupOperation returns a new UpdateBackupOperation from a given name. +// The name must be that of a previously created UpdateBackupOperation, possibly from a different process. +func (c *cloudFilestoreManagerRESTClient) UpdateBackupOperation(name string) *UpdateBackupOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateBackupOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateBackupOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*filestorepb.Backup, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp filestorepb.Backup if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1099,6 +2138,7 @@ func (op *UpdateBackupOperation) Wait(ctx context.Context, opts ...gax.CallOptio // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateBackupOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*filestorepb.Backup, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp filestorepb.Backup if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1136,7 +2176,8 @@ func (op *UpdateBackupOperation) Name() string { // UpdateInstanceOperation manages a long-running operation from UpdateInstance. type UpdateInstanceOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateInstanceOperation returns a new UpdateInstanceOperation from a given name. @@ -1147,10 +2188,21 @@ func (c *cloudFilestoreManagerGRPCClient) UpdateInstanceOperation(name string) * } } +// UpdateInstanceOperation returns a new UpdateInstanceOperation from a given name. +// The name must be that of a previously created UpdateInstanceOperation, possibly from a different process. +func (c *cloudFilestoreManagerRESTClient) UpdateInstanceOperation(name string) *UpdateInstanceOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*filestorepb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp filestorepb.Instance if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1168,6 +2220,7 @@ func (op *UpdateInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOpt // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateInstanceOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*filestorepb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp filestorepb.Instance if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/filestore/apiv1/cloud_filestore_manager_client_example_test.go b/filestore/apiv1/cloud_filestore_manager_client_example_test.go index e939655ef38b..69c6e767954a 100644 --- a/filestore/apiv1/cloud_filestore_manager_client_example_test.go +++ b/filestore/apiv1/cloud_filestore_manager_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewCloudFilestoreManagerClient() { _ = c } +func ExampleNewCloudFilestoreManagerRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := filestore.NewCloudFilestoreManagerRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleCloudFilestoreManagerClient_ListInstances() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/filestore/apiv1/doc.go b/filestore/apiv1/doc.go index a2552fc0ca59..163b0fbb79a3 100644 --- a/filestore/apiv1/doc.go +++ b/filestore/apiv1/doc.go @@ -87,6 +87,8 @@ package filestore // import "cloud.google.com/go/filestore/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -175,3 +177,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/filestore/apiv1/filestorepb/cloud_filestore_service.pb.go b/filestore/apiv1/filestorepb/cloud_filestore_service.pb.go index a58c4e028699..d3efcbbb890a 100644 --- a/filestore/apiv1/filestorepb/cloud_filestore_service.pb.go +++ b/filestore/apiv1/filestorepb/cloud_filestore_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/filestore/v1/cloud_filestore_service.proto package filestorepb @@ -508,7 +508,6 @@ type FileShareConfig struct { // share is created from scratch. // // Types that are assignable to Source: - // // *FileShareConfig_SourceBackup Source isFileShareConfig_Source `protobuf_oneof:"source"` // Nfs Export Options. @@ -1039,7 +1038,6 @@ type RestoreInstanceRequest struct { // backup is being restored to. FileShare string `protobuf:"bytes,2,opt,name=file_share,json=fileShare,proto3" json:"file_share,omitempty"` // Types that are assignable to Source: - // // *RestoreInstanceRequest_SourceBackup Source isRestoreInstanceRequest_Source `protobuf_oneof:"source"` } diff --git a/filestore/apiv1/gapic_metadata.json b/filestore/apiv1/gapic_metadata.json index ff93039ce211..d77ca8895765 100644 --- a/filestore/apiv1/gapic_metadata.json +++ b/filestore/apiv1/gapic_metadata.json @@ -66,6 +66,66 @@ ] } } + }, + "rest": { + "libraryClient": "CloudFilestoreManagerClient", + "rpcs": { + "CreateBackup": { + "methods": [ + "CreateBackup" + ] + }, + "CreateInstance": { + "methods": [ + "CreateInstance" + ] + }, + "DeleteBackup": { + "methods": [ + "DeleteBackup" + ] + }, + "DeleteInstance": { + "methods": [ + "DeleteInstance" + ] + }, + "GetBackup": { + "methods": [ + "GetBackup" + ] + }, + "GetInstance": { + "methods": [ + "GetInstance" + ] + }, + "ListBackups": { + "methods": [ + "ListBackups" + ] + }, + "ListInstances": { + "methods": [ + "ListInstances" + ] + }, + "RestoreInstance": { + "methods": [ + "RestoreInstance" + ] + }, + "UpdateBackup": { + "methods": [ + "UpdateBackup" + ] + }, + "UpdateInstance": { + "methods": [ + "UpdateInstance" + ] + } + } } } } diff --git a/firestore/apiv1/admin/adminpb/database.pb.go b/firestore/apiv1/admin/adminpb/database.pb.go index 576c04734be1..605b80aef0bf 100644 --- a/firestore/apiv1/admin/adminpb/database.pb.go +++ b/firestore/apiv1/admin/adminpb/database.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/firestore/admin/v1/database.proto package adminpb diff --git a/firestore/apiv1/admin/adminpb/field.pb.go b/firestore/apiv1/admin/adminpb/field.pb.go index 15bb014836ba..cf1523bfd947 100644 --- a/firestore/apiv1/admin/adminpb/field.pb.go +++ b/firestore/apiv1/admin/adminpb/field.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/firestore/admin/v1/field.proto package adminpb @@ -125,12 +125,10 @@ type Field struct { // // Examples: // (Note: Comments here are written in markdown syntax, so there is an - // - // additional layer of backticks to represent a code block) - // - // `\`address.city\“ represents a field named `address.city`, not the map key + // additional layer of backticks to represent a code block) + // `\`address.city\`` represents a field named `address.city`, not the map key // `city` in the field `address`. - // `\`*\“ represents a field named `*`, not any field. + // `\`*\`` represents a field named `*`, not any field. // // A special `Field` contains the default indexing settings for all fields. // This field's resource name is: diff --git a/firestore/apiv1/admin/adminpb/firestore_admin.pb.go b/firestore/apiv1/admin/adminpb/firestore_admin.pb.go index b0a53cee031f..1fe9e7b47dbf 100644 --- a/firestore/apiv1/admin/adminpb/firestore_admin.pb.go +++ b/firestore/apiv1/admin/adminpb/firestore_admin.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/firestore/admin/v1/firestore_admin.proto package adminpb diff --git a/firestore/apiv1/admin/adminpb/index.pb.go b/firestore/apiv1/admin/adminpb/index.pb.go index 20b6d4261dd3..60eb64b4dead 100644 --- a/firestore/apiv1/admin/adminpb/index.pb.go +++ b/firestore/apiv1/admin/adminpb/index.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/firestore/admin/v1/index.proto package adminpb @@ -379,7 +379,6 @@ type Index_IndexField struct { // How the field value is indexed. // // Types that are assignable to ValueMode: - // // *Index_IndexField_Order_ // *Index_IndexField_ArrayConfig_ ValueMode isIndex_IndexField_ValueMode `protobuf_oneof:"value_mode"` diff --git a/firestore/apiv1/admin/adminpb/location.pb.go b/firestore/apiv1/admin/adminpb/location.pb.go index d0877c2d28dd..4d69c8b3aa6d 100644 --- a/firestore/apiv1/admin/adminpb/location.pb.go +++ b/firestore/apiv1/admin/adminpb/location.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/firestore/admin/v1/location.proto package adminpb diff --git a/firestore/apiv1/admin/adminpb/operation.pb.go b/firestore/apiv1/admin/adminpb/operation.pb.go index 7d90e9048c51..d6100b26404e 100644 --- a/firestore/apiv1/admin/adminpb/operation.pb.go +++ b/firestore/apiv1/admin/adminpb/operation.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/firestore/admin/v1/operation.proto package adminpb diff --git a/firestore/apiv1/admin/doc.go b/firestore/apiv1/admin/doc.go index 5d60f5491a94..b13598de4ba6 100644 --- a/firestore/apiv1/admin/doc.go +++ b/firestore/apiv1/admin/doc.go @@ -86,6 +86,8 @@ package apiv1 // import "cloud.google.com/go/firestore/apiv1/admin" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -175,3 +177,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/firestore/apiv1/admin/firestore_admin_client.go b/firestore/apiv1/admin/firestore_admin_client.go index 1f8cec58fa5b..dde5704feeab 100644 --- a/firestore/apiv1/admin/firestore_admin_client.go +++ b/firestore/apiv1/admin/firestore_admin_client.go @@ -17,9 +17,12 @@ package apiv1 import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,14 +30,17 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -153,6 +159,82 @@ func defaultFirestoreAdminCallOptions() *FirestoreAdminCallOptions { } } +func defaultFirestoreAdminRESTCallOptions() *FirestoreAdminCallOptions { + return &FirestoreAdminCallOptions{ + CreateIndex: []gax.CallOption{}, + ListIndexes: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusInternalServerError, + http.StatusGatewayTimeout) + }), + }, + GetIndex: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusInternalServerError, + http.StatusGatewayTimeout) + }), + }, + DeleteIndex: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusInternalServerError, + http.StatusGatewayTimeout) + }), + }, + GetField: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusInternalServerError, + http.StatusGatewayTimeout) + }), + }, + UpdateField: []gax.CallOption{}, + ListFields: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusInternalServerError, + http.StatusGatewayTimeout) + }), + }, + ExportDocuments: []gax.CallOption{}, + ImportDocuments: []gax.CallOption{}, + GetDatabase: []gax.CallOption{}, + ListDatabases: []gax.CallOption{}, + UpdateDatabase: []gax.CallOption{}, + CancelOperation: []gax.CallOption{}, + DeleteOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalFirestoreAdminClient is an interface that defines the methods available from Cloud Firestore API. type internalFirestoreAdminClient interface { Close() error @@ -518,6 +600,116 @@ func (c *firestoreAdminGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type firestoreAdminRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing FirestoreAdminClient + CallOptions **FirestoreAdminCallOptions +} + +// NewFirestoreAdminRESTClient creates a new firestore admin rest client. +// +// The Cloud Firestore Admin API. +// +// This API provides several administrative services for Cloud Firestore. +// +// Project, Database, Namespace, Collection, Collection Group, and Document are +// used as defined in the Google Cloud Firestore API. +// +// Operation: An Operation represents work being performed in the background. +// +// The index service manages Cloud Firestore indexes. +// +// Index creation is performed asynchronously. +// An Operation resource is created for each such asynchronous operation. +// The state of the operation (including any errors encountered) +// may be queried via the Operation resource. +// +// The Operations collection provides a record of actions performed for the +// specified Project (including any Operations in progress). Operations are not +// created directly but through calls on other collections or resources. +// +// An Operation that is done may be deleted so that it is no longer listed as +// part of the Operation collection. Operations are garbage collected after +// 30 days. By default, ListOperations will only return in progress and failed +// operations. To list completed operation, issue a ListOperations request with +// the filter done: true. +// +// Operations are created by service FirestoreAdmin, but are accessed via +// service google.longrunning.Operations. +func NewFirestoreAdminRESTClient(ctx context.Context, opts ...option.ClientOption) (*FirestoreAdminClient, error) { + clientOpts := append(defaultFirestoreAdminRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultFirestoreAdminRESTCallOptions() + c := &firestoreAdminRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &FirestoreAdminClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultFirestoreAdminRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://firestore.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://firestore.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://firestore.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *firestoreAdminRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *firestoreAdminRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *firestoreAdminRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *firestoreAdminGRPCClient) CreateIndex(ctx context.Context, req *adminpb.CreateIndexRequest, opts ...gax.CallOption) (*CreateIndexOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) @@ -907,126 +1099,1231 @@ func (c *firestoreAdminGRPCClient) ListOperations(ctx context.Context, req *long return it } -// CreateIndexOperation manages a long-running operation from CreateIndex. -type CreateIndexOperation struct { - lro *longrunning.Operation -} - -// CreateIndexOperation returns a new CreateIndexOperation from a given name. -// The name must be that of a previously created CreateIndexOperation, possibly from a different process. -func (c *firestoreAdminGRPCClient) CreateIndexOperation(name string) *CreateIndexOperation { - return &CreateIndexOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} - -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *CreateIndexOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*adminpb.Index, error) { - var resp adminpb.Index - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { +// CreateIndex creates a composite index. This returns a google.longrunning.Operation +// which may be used to track the status of the creation. The metadata for +// the operation will be the type IndexOperationMetadata. +func (c *firestoreAdminRESTClient) CreateIndex(ctx context.Context, req *adminpb.CreateIndexRequest, opts ...gax.CallOption) (*CreateIndexOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetIndex() + jsonReq, err := m.Marshal(body) + if err != nil { return nil, err } - return &resp, nil -} -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *CreateIndexOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*adminpb.Index, error) { - var resp adminpb.Index - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - if !op.Done() { - return nil, nil - } - return &resp, nil -} + baseUrl.Path += fmt.Sprintf("/v1/%v/indexes", req.GetParent()) -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *CreateIndexOperation) Metadata() (*adminpb.IndexOperationMetadata, error) { - var meta adminpb.IndexOperationMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { - return nil, err - } - return &meta, nil -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") -// Done reports whether the long-running operation has completed. -func (op *CreateIndexOperation) Done() bool { - return op.lro.Done() -} + baseUrl.RawQuery = params.Encode() -// 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 *CreateIndexOperation) Name() string { - return op.lro.Name() -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) -// ExportDocumentsOperation manages a long-running operation from ExportDocuments. -type ExportDocumentsOperation struct { - lro *longrunning.Operation -} + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers -// ExportDocumentsOperation returns a new ExportDocumentsOperation from a given name. -// The name must be that of a previously created ExportDocumentsOperation, possibly from a different process. -func (c *firestoreAdminGRPCClient) ExportDocumentsOperation(name string) *ExportDocumentsOperation { - return &ExportDocumentsOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *ExportDocumentsOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*adminpb.ExportDocumentsResponse, error) { - var resp adminpb.ExportDocumentsResponse - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { - return nil, err - } - return &resp, nil -} + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *ExportDocumentsOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*adminpb.ExportDocumentsResponse, error) { - var resp adminpb.ExportDocumentsResponse - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { - return nil, err - } - if !op.Done() { - return nil, nil + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e } - return &resp, nil + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateIndexOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil } -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *ExportDocumentsOperation) Metadata() (*adminpb.ExportDocumentsMetadata, error) { - var meta adminpb.ExportDocumentsMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { +// ListIndexes lists composite indexes. +func (c *firestoreAdminRESTClient) ListIndexes(ctx context.Context, req *adminpb.ListIndexesRequest, opts ...gax.CallOption) *IndexIterator { + it := &IndexIterator{} + req = proto.Clone(req).(*adminpb.ListIndexesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*adminpb.Index, string, error) { + resp := &adminpb.ListIndexesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/indexes", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetIndexes(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetIndex gets a composite index. +func (c *firestoreAdminRESTClient) GetIndex(ctx context.Context, req *adminpb.GetIndexRequest, opts ...gax.CallOption) (*adminpb.Index, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetIndex[0:len((*c.CallOptions).GetIndex):len((*c.CallOptions).GetIndex)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &adminpb.Index{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteIndex deletes a composite index. +func (c *firestoreAdminRESTClient) DeleteIndex(ctx context.Context, req *adminpb.DeleteIndexRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetField gets the metadata and configuration for a Field. +func (c *firestoreAdminRESTClient) GetField(ctx context.Context, req *adminpb.GetFieldRequest, opts ...gax.CallOption) (*adminpb.Field, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetField[0:len((*c.CallOptions).GetField):len((*c.CallOptions).GetField)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &adminpb.Field{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateField updates a field configuration. Currently, field updates apply only to +// single field index configuration. However, calls to +// FirestoreAdmin.UpdateField should provide a field mask to avoid +// changing any configuration that the caller isn’t aware of. The field mask +// should be specified as: { paths: "index_config" }. +// +// This call returns a google.longrunning.Operation which may be used to +// track the status of the field update. The metadata for +// the operation will be the type FieldOperationMetadata. +// +// To configure the default field settings for the database, use +// the special Field with resource name: +// projects/{project_id}/databases/{database_id}/collectionGroups/__default__/fields/*. +func (c *firestoreAdminRESTClient) UpdateField(ctx context.Context, req *adminpb.UpdateFieldRequest, opts ...gax.CallOption) (*UpdateFieldOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetField() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetField().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "field.name", url.QueryEscape(req.GetField().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateFieldOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListFields lists the field configuration and metadata for this database. +// +// Currently, FirestoreAdmin.ListFields only supports listing fields +// that have been explicitly overridden. To issue this query, call +// FirestoreAdmin.ListFields with the filter set to +// indexConfig.usesAncestorConfig:false . +func (c *firestoreAdminRESTClient) ListFields(ctx context.Context, req *adminpb.ListFieldsRequest, opts ...gax.CallOption) *FieldIterator { + it := &FieldIterator{} + req = proto.Clone(req).(*adminpb.ListFieldsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*adminpb.Field, string, error) { + resp := &adminpb.ListFieldsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/fields", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetFields(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// ExportDocuments exports a copy of all or a subset of documents from Google Cloud Firestore +// to another storage system, such as Google Cloud Storage. Recent updates to +// documents may not be reflected in the export. The export occurs in the +// background and its progress can be monitored and managed via the +// Operation resource that is created. The output of an export may only be +// used once the associated operation is done. If an export operation is +// cancelled before completion it may leave partial data behind in Google +// Cloud Storage. +// +// For more details on export behavior and output format, refer to: +// https://cloud.google.com/firestore/docs/manage-data/export-import (at https://cloud.google.com/firestore/docs/manage-data/export-import) +func (c *firestoreAdminRESTClient) ExportDocuments(ctx context.Context, req *adminpb.ExportDocumentsRequest, opts ...gax.CallOption) (*ExportDocumentsOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:exportDocuments", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &ExportDocumentsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ImportDocuments imports documents into Google Cloud Firestore. Existing documents with the +// same name are overwritten. The import occurs in the background and its +// progress can be monitored and managed via the Operation resource that is +// created. If an ImportDocuments operation is cancelled, it is possible +// that a subset of the data has already been imported to Cloud Firestore. +func (c *firestoreAdminRESTClient) ImportDocuments(ctx context.Context, req *adminpb.ImportDocumentsRequest, opts ...gax.CallOption) (*ImportDocumentsOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:importDocuments", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &ImportDocumentsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetDatabase gets information about a database. +func (c *firestoreAdminRESTClient) GetDatabase(ctx context.Context, req *adminpb.GetDatabaseRequest, opts ...gax.CallOption) (*adminpb.Database, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetDatabase[0:len((*c.CallOptions).GetDatabase):len((*c.CallOptions).GetDatabase)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &adminpb.Database{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListDatabases list all the databases in the project. +func (c *firestoreAdminRESTClient) ListDatabases(ctx context.Context, req *adminpb.ListDatabasesRequest, opts ...gax.CallOption) (*adminpb.ListDatabasesResponse, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/databases", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).ListDatabases[0:len((*c.CallOptions).ListDatabases):len((*c.CallOptions).ListDatabases)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &adminpb.ListDatabasesResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateDatabase updates a database. +func (c *firestoreAdminRESTClient) UpdateDatabase(ctx context.Context, req *adminpb.UpdateDatabaseRequest, opts ...gax.CallOption) (*UpdateDatabaseOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetDatabase() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetDatabase().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "database.name", url.QueryEscape(req.GetDatabase().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateDatabaseOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *firestoreAdminRESTClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// DeleteOperation is a utility method from google.longrunning.Operations. +func (c *firestoreAdminRESTClient) DeleteOperation(ctx context.Context, req *longrunningpb.DeleteOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *firestoreAdminRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *firestoreAdminRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CreateIndexOperation manages a long-running operation from CreateIndex. +type CreateIndexOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateIndexOperation returns a new CreateIndexOperation from a given name. +// The name must be that of a previously created CreateIndexOperation, possibly from a different process. +func (c *firestoreAdminGRPCClient) CreateIndexOperation(name string) *CreateIndexOperation { + return &CreateIndexOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateIndexOperation returns a new CreateIndexOperation from a given name. +// The name must be that of a previously created CreateIndexOperation, possibly from a different process. +func (c *firestoreAdminRESTClient) CreateIndexOperation(name string) *CreateIndexOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateIndexOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CreateIndexOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*adminpb.Index, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp adminpb.Index + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *CreateIndexOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*adminpb.Index, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp adminpb.Index + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *CreateIndexOperation) Metadata() (*adminpb.IndexOperationMetadata, error) { + var meta adminpb.IndexOperationMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *CreateIndexOperation) Done() bool { + return op.lro.Done() +} + +// 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 *CreateIndexOperation) Name() string { + return op.lro.Name() +} + +// ExportDocumentsOperation manages a long-running operation from ExportDocuments. +type ExportDocumentsOperation struct { + lro *longrunning.Operation + pollPath string +} + +// ExportDocumentsOperation returns a new ExportDocumentsOperation from a given name. +// The name must be that of a previously created ExportDocumentsOperation, possibly from a different process. +func (c *firestoreAdminGRPCClient) ExportDocumentsOperation(name string) *ExportDocumentsOperation { + return &ExportDocumentsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// ExportDocumentsOperation returns a new ExportDocumentsOperation from a given name. +// The name must be that of a previously created ExportDocumentsOperation, possibly from a different process. +func (c *firestoreAdminRESTClient) ExportDocumentsOperation(name string) *ExportDocumentsOperation { + override := fmt.Sprintf("/v1/%s", name) + return &ExportDocumentsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *ExportDocumentsOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*adminpb.ExportDocumentsResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp adminpb.ExportDocumentsResponse + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *ExportDocumentsOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*adminpb.ExportDocumentsResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp adminpb.ExportDocumentsResponse + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *ExportDocumentsOperation) Metadata() (*adminpb.ExportDocumentsMetadata, error) { + var meta adminpb.ExportDocumentsMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { return nil, nil } else if err != nil { return nil, err @@ -1047,7 +2344,8 @@ func (op *ExportDocumentsOperation) Name() string { // ImportDocumentsOperation manages a long-running operation from ImportDocuments. type ImportDocumentsOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // ImportDocumentsOperation returns a new ImportDocumentsOperation from a given name. @@ -1058,10 +2356,21 @@ func (c *firestoreAdminGRPCClient) ImportDocumentsOperation(name string) *Import } } +// ImportDocumentsOperation returns a new ImportDocumentsOperation from a given name. +// The name must be that of a previously created ImportDocumentsOperation, possibly from a different process. +func (c *firestoreAdminRESTClient) ImportDocumentsOperation(name string) *ImportDocumentsOperation { + override := fmt.Sprintf("/v1/%s", name) + return &ImportDocumentsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *ImportDocumentsOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -1075,6 +2384,7 @@ func (op *ImportDocumentsOperation) Wait(ctx context.Context, opts ...gax.CallOp // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *ImportDocumentsOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -1105,7 +2415,8 @@ func (op *ImportDocumentsOperation) Name() string { // UpdateDatabaseOperation manages a long-running operation from UpdateDatabase. type UpdateDatabaseOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateDatabaseOperation returns a new UpdateDatabaseOperation from a given name. @@ -1116,10 +2427,21 @@ func (c *firestoreAdminGRPCClient) UpdateDatabaseOperation(name string) *UpdateD } } +// UpdateDatabaseOperation returns a new UpdateDatabaseOperation from a given name. +// The name must be that of a previously created UpdateDatabaseOperation, possibly from a different process. +func (c *firestoreAdminRESTClient) UpdateDatabaseOperation(name string) *UpdateDatabaseOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateDatabaseOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateDatabaseOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*adminpb.Database, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp adminpb.Database if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1137,6 +2459,7 @@ func (op *UpdateDatabaseOperation) Wait(ctx context.Context, opts ...gax.CallOpt // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateDatabaseOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*adminpb.Database, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp adminpb.Database if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1174,7 +2497,8 @@ func (op *UpdateDatabaseOperation) Name() string { // UpdateFieldOperation manages a long-running operation from UpdateField. type UpdateFieldOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateFieldOperation returns a new UpdateFieldOperation from a given name. @@ -1185,10 +2509,21 @@ func (c *firestoreAdminGRPCClient) UpdateFieldOperation(name string) *UpdateFiel } } +// UpdateFieldOperation returns a new UpdateFieldOperation from a given name. +// The name must be that of a previously created UpdateFieldOperation, possibly from a different process. +func (c *firestoreAdminRESTClient) UpdateFieldOperation(name string) *UpdateFieldOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateFieldOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateFieldOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*adminpb.Field, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp adminpb.Field if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1206,6 +2541,7 @@ func (op *UpdateFieldOperation) Wait(ctx context.Context, opts ...gax.CallOption // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateFieldOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*adminpb.Field, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp adminpb.Field if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/firestore/apiv1/admin/firestore_admin_client_example_test.go b/firestore/apiv1/admin/firestore_admin_client_example_test.go index 7fac3877c1f9..736984d3aa14 100644 --- a/firestore/apiv1/admin/firestore_admin_client_example_test.go +++ b/firestore/apiv1/admin/firestore_admin_client_example_test.go @@ -42,6 +42,23 @@ func ExampleNewFirestoreAdminClient() { _ = c } +func ExampleNewFirestoreAdminRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := apiv1.NewFirestoreAdminRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleFirestoreAdminClient_CreateIndex() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/firestore/apiv1/admin/gapic_metadata.json b/firestore/apiv1/admin/gapic_metadata.json index 8cb741a95519..47c44125e55c 100644 --- a/firestore/apiv1/admin/gapic_metadata.json +++ b/firestore/apiv1/admin/gapic_metadata.json @@ -91,6 +91,91 @@ ] } } + }, + "rest": { + "libraryClient": "FirestoreAdminClient", + "rpcs": { + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "CreateIndex": { + "methods": [ + "CreateIndex" + ] + }, + "DeleteIndex": { + "methods": [ + "DeleteIndex" + ] + }, + "DeleteOperation": { + "methods": [ + "DeleteOperation" + ] + }, + "ExportDocuments": { + "methods": [ + "ExportDocuments" + ] + }, + "GetDatabase": { + "methods": [ + "GetDatabase" + ] + }, + "GetField": { + "methods": [ + "GetField" + ] + }, + "GetIndex": { + "methods": [ + "GetIndex" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ImportDocuments": { + "methods": [ + "ImportDocuments" + ] + }, + "ListDatabases": { + "methods": [ + "ListDatabases" + ] + }, + "ListFields": { + "methods": [ + "ListFields" + ] + }, + "ListIndexes": { + "methods": [ + "ListIndexes" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "UpdateDatabase": { + "methods": [ + "UpdateDatabase" + ] + }, + "UpdateField": { + "methods": [ + "UpdateField" + ] + } + } } } } diff --git a/firestore/apiv1/doc.go b/firestore/apiv1/doc.go index 485dc729132d..02d9f5673146 100644 --- a/firestore/apiv1/doc.go +++ b/firestore/apiv1/doc.go @@ -81,6 +81,8 @@ package firestore // import "cloud.google.com/go/firestore/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -170,3 +172,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/firestore/apiv1/firestore_client.go b/firestore/apiv1/firestore_client.go index 870b02f6ba8b..3429d86762db 100644 --- a/firestore/apiv1/firestore_client.go +++ b/firestore/apiv1/firestore_client.go @@ -17,22 +17,28 @@ package firestore import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" firestorepb "cloud.google.com/go/firestore/apiv1/firestorepb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -287,6 +293,204 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + GetDocument: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusTooManyRequests, + http.StatusServiceUnavailable, + http.StatusInternalServerError, + http.StatusGatewayTimeout) + }), + }, + ListDocuments: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusTooManyRequests, + http.StatusServiceUnavailable, + http.StatusInternalServerError, + http.StatusGatewayTimeout) + }), + }, + UpdateDocument: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusTooManyRequests, + http.StatusServiceUnavailable) + }), + }, + DeleteDocument: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusTooManyRequests, + http.StatusServiceUnavailable, + http.StatusInternalServerError, + http.StatusGatewayTimeout) + }), + }, + BatchGetDocuments: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusTooManyRequests, + http.StatusServiceUnavailable, + http.StatusInternalServerError, + http.StatusGatewayTimeout) + }), + }, + BeginTransaction: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusTooManyRequests, + http.StatusServiceUnavailable, + http.StatusInternalServerError, + http.StatusGatewayTimeout) + }), + }, + Commit: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusTooManyRequests, + http.StatusServiceUnavailable) + }), + }, + Rollback: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusTooManyRequests, + http.StatusServiceUnavailable, + http.StatusInternalServerError, + http.StatusGatewayTimeout) + }), + }, + RunQuery: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusTooManyRequests, + http.StatusServiceUnavailable, + http.StatusInternalServerError, + http.StatusGatewayTimeout) + }), + }, + RunAggregationQuery: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusTooManyRequests, + http.StatusServiceUnavailable, + http.StatusInternalServerError, + http.StatusGatewayTimeout) + }), + }, + PartitionQuery: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusTooManyRequests, + http.StatusServiceUnavailable, + http.StatusInternalServerError, + http.StatusGatewayTimeout) + }), + }, + Write: []gax.CallOption{}, + Listen: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusTooManyRequests, + http.StatusServiceUnavailable, + http.StatusInternalServerError, + http.StatusGatewayTimeout) + }), + }, + ListCollectionIds: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusTooManyRequests, + http.StatusServiceUnavailable, + http.StatusInternalServerError, + http.StatusGatewayTimeout) + }), + }, + BatchWrite: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusTooManyRequests, + http.StatusServiceUnavailable, + http.StatusConflict) + }), + }, + CreateDocument: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusTooManyRequests, + http.StatusServiceUnavailable) + }), + }, + CancelOperation: []gax.CallOption{}, + DeleteOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalClient is an interface that defines the methods available from Cloud Firestore API. type internalClient interface { Close() error @@ -423,11 +627,15 @@ func (c *Client) PartitionQuery(ctx context.Context, req *firestorepb.PartitionQ } // Write streams batches of document updates and deletes, in order. +// +// This method is not supported for the REST transport. func (c *Client) Write(ctx context.Context, opts ...gax.CallOption) (firestorepb.Firestore_WriteClient, error) { return c.internalClient.Write(ctx, opts...) } // Listen listens to changes. +// +// This method is not supported for the REST transport. func (c *Client) Listen(ctx context.Context, opts ...gax.CallOption) (firestorepb.Firestore_ListenClient, error) { return c.internalClient.Listen(ctx, opts...) } @@ -566,6 +774,81 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new firestore rest client. +// +// The Cloud Firestore service. +// +// Cloud Firestore is a fast, fully managed, serverless, cloud-native NoSQL +// document database that simplifies storing, syncing, and querying data for +// your mobile, web, and IoT apps at global scale. Its client libraries provide +// live synchronization and offline support, while its security features and +// integrations with Firebase and Google Cloud Platform (GCP) accelerate +// building truly serverless apps. +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://firestore.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://firestore.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://firestore.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) GetDocument(ctx context.Context, req *firestorepb.GetDocumentRequest, opts ...gax.CallOption) (*firestorepb.Document, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) @@ -1035,6 +1318,1390 @@ func (c *gRPCClient) ListOperations(ctx context.Context, req *longrunningpb.List return it } +// GetDocument gets a single document. +func (c *restClient) GetDocument(ctx context.Context, req *firestorepb.GetDocumentRequest, opts ...gax.CallOption) (*firestorepb.Document, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if items := req.GetMask().GetFieldPaths(); len(items) > 0 { + for _, item := range items { + params.Add("mask.fieldPaths", fmt.Sprintf("%v", item)) + } + } + if req.GetReadTime() != nil { + readTime, err := protojson.Marshal(req.GetReadTime()) + if err != nil { + return nil, err + } + params.Add("readTime", string(readTime)) + } + if req.GetTransaction() != nil { + params.Add("transaction", fmt.Sprintf("%v", req.GetTransaction())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetDocument[0:len((*c.CallOptions).GetDocument):len((*c.CallOptions).GetDocument)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &firestorepb.Document{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListDocuments lists documents. +func (c *restClient) ListDocuments(ctx context.Context, req *firestorepb.ListDocumentsRequest, opts ...gax.CallOption) *DocumentIterator { + it := &DocumentIterator{} + req = proto.Clone(req).(*firestorepb.ListDocumentsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*firestorepb.Document, string, error) { + resp := &firestorepb.ListDocumentsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/%v", req.GetParent(), req.GetCollectionId()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if items := req.GetMask().GetFieldPaths(); len(items) > 0 { + for _, item := range items { + params.Add("mask.fieldPaths", fmt.Sprintf("%v", item)) + } + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + if req.GetReadTime() != nil { + readTime, err := protojson.Marshal(req.GetReadTime()) + if err != nil { + return nil, "", err + } + params.Add("readTime", string(readTime)) + } + if req.GetShowMissing() { + params.Add("showMissing", fmt.Sprintf("%v", req.GetShowMissing())) + } + if req.GetTransaction() != nil { + params.Add("transaction", fmt.Sprintf("%v", req.GetTransaction())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetDocuments(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// UpdateDocument updates or inserts a document. +func (c *restClient) UpdateDocument(ctx context.Context, req *firestorepb.UpdateDocumentRequest, opts ...gax.CallOption) (*firestorepb.Document, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetDocument() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetDocument().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetCurrentDocument().GetExists() { + params.Add("currentDocument.exists", fmt.Sprintf("%v", req.GetCurrentDocument().GetExists())) + } + if req.GetCurrentDocument().GetUpdateTime() != nil { + updateTime, err := protojson.Marshal(req.GetCurrentDocument().GetUpdateTime()) + if err != nil { + return nil, err + } + params.Add("currentDocument.updateTime", string(updateTime)) + } + if items := req.GetMask().GetFieldPaths(); len(items) > 0 { + for _, item := range items { + params.Add("mask.fieldPaths", fmt.Sprintf("%v", item)) + } + } + if items := req.GetUpdateMask().GetFieldPaths(); len(items) > 0 { + for _, item := range items { + params.Add("updateMask.fieldPaths", fmt.Sprintf("%v", item)) + } + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "document.name", url.QueryEscape(req.GetDocument().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateDocument[0:len((*c.CallOptions).UpdateDocument):len((*c.CallOptions).UpdateDocument)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &firestorepb.Document{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteDocument deletes a document. +func (c *restClient) DeleteDocument(ctx context.Context, req *firestorepb.DeleteDocumentRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetCurrentDocument().GetExists() { + params.Add("currentDocument.exists", fmt.Sprintf("%v", req.GetCurrentDocument().GetExists())) + } + if req.GetCurrentDocument().GetUpdateTime() != nil { + updateTime, err := protojson.Marshal(req.GetCurrentDocument().GetUpdateTime()) + if err != nil { + return err + } + params.Add("currentDocument.updateTime", string(updateTime)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// BatchGetDocuments gets multiple documents. +// +// Documents returned by this method are not guaranteed to be returned in the +// same order that they were requested. +func (c *restClient) BatchGetDocuments(ctx context.Context, req *firestorepb.BatchGetDocumentsRequest, opts ...gax.CallOption) (firestorepb.Firestore_BatchGetDocumentsClient, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/documents:batchGet", req.GetDatabase()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "database", url.QueryEscape(req.GetDatabase()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + var streamClient *batchGetDocumentsRESTClient + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + streamClient = &batchGetDocumentsRESTClient{ + ctx: ctx, + md: metadata.MD(httpRsp.Header), + stream: gax.NewProtoJSONStreamReader(httpRsp.Body, (&firestorepb.BatchGetDocumentsResponse{}).ProtoReflect().Type()), + } + return nil + }, opts...) + + return streamClient, e +} + +// batchGetDocumentsRESTClient is the stream client used to consume the server stream created by +// the REST implementation of BatchGetDocuments. +type batchGetDocumentsRESTClient struct { + ctx context.Context + md metadata.MD + stream *gax.ProtoJSONStream +} + +func (c *batchGetDocumentsRESTClient) Recv() (*firestorepb.BatchGetDocumentsResponse, error) { + if err := c.ctx.Err(); err != nil { + defer c.stream.Close() + return nil, err + } + msg, err := c.stream.Recv() + if err != nil { + defer c.stream.Close() + return nil, err + } + res := msg.(*firestorepb.BatchGetDocumentsResponse) + return res, nil +} + +func (c *batchGetDocumentsRESTClient) Header() (metadata.MD, error) { + return c.md, nil +} + +func (c *batchGetDocumentsRESTClient) Trailer() metadata.MD { + return c.md +} + +func (c *batchGetDocumentsRESTClient) CloseSend() error { + // This is a no-op to fulfill the interface. + return fmt.Errorf("this method is not implemented for a server-stream") +} + +func (c *batchGetDocumentsRESTClient) Context() context.Context { + return c.ctx +} + +func (c *batchGetDocumentsRESTClient) SendMsg(m interface{}) error { + // This is a no-op to fulfill the interface. + return fmt.Errorf("this method is not implemented for a server-stream") +} + +func (c *batchGetDocumentsRESTClient) RecvMsg(m interface{}) error { + // This is a no-op to fulfill the interface. + return fmt.Errorf("this method is not implemented, use Recv") +} + +// BeginTransaction starts a new transaction. +func (c *restClient) BeginTransaction(ctx context.Context, req *firestorepb.BeginTransactionRequest, opts ...gax.CallOption) (*firestorepb.BeginTransactionResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/documents:beginTransaction", req.GetDatabase()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "database", url.QueryEscape(req.GetDatabase()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).BeginTransaction[0:len((*c.CallOptions).BeginTransaction):len((*c.CallOptions).BeginTransaction)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &firestorepb.BeginTransactionResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// Commit commits a transaction, while optionally updating documents. +func (c *restClient) Commit(ctx context.Context, req *firestorepb.CommitRequest, opts ...gax.CallOption) (*firestorepb.CommitResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/documents:commit", req.GetDatabase()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "database", url.QueryEscape(req.GetDatabase()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).Commit[0:len((*c.CallOptions).Commit):len((*c.CallOptions).Commit)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &firestorepb.CommitResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// Rollback rolls back a transaction. +func (c *restClient) Rollback(ctx context.Context, req *firestorepb.RollbackRequest, opts ...gax.CallOption) error { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/documents:rollback", req.GetDatabase()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "database", url.QueryEscape(req.GetDatabase()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// RunQuery runs a query. +func (c *restClient) RunQuery(ctx context.Context, req *firestorepb.RunQueryRequest, opts ...gax.CallOption) (firestorepb.Firestore_RunQueryClient, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:runQuery", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + var streamClient *runQueryRESTClient + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + streamClient = &runQueryRESTClient{ + ctx: ctx, + md: metadata.MD(httpRsp.Header), + stream: gax.NewProtoJSONStreamReader(httpRsp.Body, (&firestorepb.RunQueryResponse{}).ProtoReflect().Type()), + } + return nil + }, opts...) + + return streamClient, e +} + +// runQueryRESTClient is the stream client used to consume the server stream created by +// the REST implementation of RunQuery. +type runQueryRESTClient struct { + ctx context.Context + md metadata.MD + stream *gax.ProtoJSONStream +} + +func (c *runQueryRESTClient) Recv() (*firestorepb.RunQueryResponse, error) { + if err := c.ctx.Err(); err != nil { + defer c.stream.Close() + return nil, err + } + msg, err := c.stream.Recv() + if err != nil { + defer c.stream.Close() + return nil, err + } + res := msg.(*firestorepb.RunQueryResponse) + return res, nil +} + +func (c *runQueryRESTClient) Header() (metadata.MD, error) { + return c.md, nil +} + +func (c *runQueryRESTClient) Trailer() metadata.MD { + return c.md +} + +func (c *runQueryRESTClient) CloseSend() error { + // This is a no-op to fulfill the interface. + return fmt.Errorf("this method is not implemented for a server-stream") +} + +func (c *runQueryRESTClient) Context() context.Context { + return c.ctx +} + +func (c *runQueryRESTClient) SendMsg(m interface{}) error { + // This is a no-op to fulfill the interface. + return fmt.Errorf("this method is not implemented for a server-stream") +} + +func (c *runQueryRESTClient) RecvMsg(m interface{}) error { + // This is a no-op to fulfill the interface. + return fmt.Errorf("this method is not implemented, use Recv") +} + +// RunAggregationQuery runs an aggregation query. +// +// Rather than producing Document results like Firestore.RunQuery, +// this API allows running an aggregation to produce a series of +// AggregationResult server-side. +// +// High-Level Example: +func (c *restClient) RunAggregationQuery(ctx context.Context, req *firestorepb.RunAggregationQueryRequest, opts ...gax.CallOption) (firestorepb.Firestore_RunAggregationQueryClient, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:runAggregationQuery", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + var streamClient *runAggregationQueryRESTClient + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + streamClient = &runAggregationQueryRESTClient{ + ctx: ctx, + md: metadata.MD(httpRsp.Header), + stream: gax.NewProtoJSONStreamReader(httpRsp.Body, (&firestorepb.RunAggregationQueryResponse{}).ProtoReflect().Type()), + } + return nil + }, opts...) + + return streamClient, e +} + +// runAggregationQueryRESTClient is the stream client used to consume the server stream created by +// the REST implementation of RunAggregationQuery. +type runAggregationQueryRESTClient struct { + ctx context.Context + md metadata.MD + stream *gax.ProtoJSONStream +} + +func (c *runAggregationQueryRESTClient) Recv() (*firestorepb.RunAggregationQueryResponse, error) { + if err := c.ctx.Err(); err != nil { + defer c.stream.Close() + return nil, err + } + msg, err := c.stream.Recv() + if err != nil { + defer c.stream.Close() + return nil, err + } + res := msg.(*firestorepb.RunAggregationQueryResponse) + return res, nil +} + +func (c *runAggregationQueryRESTClient) Header() (metadata.MD, error) { + return c.md, nil +} + +func (c *runAggregationQueryRESTClient) Trailer() metadata.MD { + return c.md +} + +func (c *runAggregationQueryRESTClient) CloseSend() error { + // This is a no-op to fulfill the interface. + return fmt.Errorf("this method is not implemented for a server-stream") +} + +func (c *runAggregationQueryRESTClient) Context() context.Context { + return c.ctx +} + +func (c *runAggregationQueryRESTClient) SendMsg(m interface{}) error { + // This is a no-op to fulfill the interface. + return fmt.Errorf("this method is not implemented for a server-stream") +} + +func (c *runAggregationQueryRESTClient) RecvMsg(m interface{}) error { + // This is a no-op to fulfill the interface. + return fmt.Errorf("this method is not implemented, use Recv") +} + +// PartitionQuery partitions a query by returning partition cursors that can be used to run +// the query in parallel. The returned partition cursors are split points that +// can be used by RunQuery as starting/end points for the query results. +func (c *restClient) PartitionQuery(ctx context.Context, req *firestorepb.PartitionQueryRequest, opts ...gax.CallOption) *CursorIterator { + it := &CursorIterator{} + req = proto.Clone(req).(*firestorepb.PartitionQueryRequest) + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*firestorepb.Cursor, string, error) { + resp := &firestorepb.PartitionQueryResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, "", err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:partitionQuery", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetPartitions(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// Write streams batches of document updates and deletes, in order. +// +// This method is not supported for the REST transport. +func (c *restClient) Write(ctx context.Context, opts ...gax.CallOption) (firestorepb.Firestore_WriteClient, error) { + return nil, fmt.Errorf("Write not yet supported for REST clients") +} + +// Listen listens to changes. +// +// This method is not supported for the REST transport. +func (c *restClient) Listen(ctx context.Context, opts ...gax.CallOption) (firestorepb.Firestore_ListenClient, error) { + return nil, fmt.Errorf("Listen not yet supported for REST clients") +} + +// ListCollectionIds lists all the collection IDs underneath a document. +func (c *restClient) ListCollectionIds(ctx context.Context, req *firestorepb.ListCollectionIdsRequest, opts ...gax.CallOption) *StringIterator { + it := &StringIterator{} + req = proto.Clone(req).(*firestorepb.ListCollectionIdsRequest) + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]string, string, error) { + resp := &firestorepb.ListCollectionIdsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, "", err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:listCollectionIds", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetCollectionIds(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// BatchWrite applies a batch of write operations. +// +// The BatchWrite method does not apply the write operations atomically +// and can apply them out of order. Method does not allow more than one write +// per document. Each write succeeds or fails independently. See the +// BatchWriteResponse for the success status of each write. +// +// If you require an atomically applied set of writes, use +// Commit instead. +func (c *restClient) BatchWrite(ctx context.Context, req *firestorepb.BatchWriteRequest, opts ...gax.CallOption) (*firestorepb.BatchWriteResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/documents:batchWrite", req.GetDatabase()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "database", url.QueryEscape(req.GetDatabase()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).BatchWrite[0:len((*c.CallOptions).BatchWrite):len((*c.CallOptions).BatchWrite)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &firestorepb.BatchWriteResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateDocument creates a new document. +func (c *restClient) CreateDocument(ctx context.Context, req *firestorepb.CreateDocumentRequest, opts ...gax.CallOption) (*firestorepb.Document, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetDocument() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/%v", req.GetParent(), req.GetCollectionId()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetDocumentId() != "" { + params.Add("documentId", fmt.Sprintf("%v", req.GetDocumentId())) + } + if items := req.GetMask().GetFieldPaths(); len(items) > 0 { + for _, item := range items { + params.Add("mask.fieldPaths", fmt.Sprintf("%v", item)) + } + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "parent", url.QueryEscape(req.GetParent()), "collection_id", url.QueryEscape(req.GetCollectionId()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateDocument[0:len((*c.CallOptions).CreateDocument):len((*c.CallOptions).CreateDocument)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &firestorepb.Document{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *restClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// DeleteOperation is a utility method from google.longrunning.Operations. +func (c *restClient) DeleteOperation(ctx context.Context, req *longrunningpb.DeleteOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *restClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *restClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + // CursorIterator manages a stream of *firestorepb.Cursor. type CursorIterator struct { items []*firestorepb.Cursor diff --git a/firestore/apiv1/firestore_client_example_test.go b/firestore/apiv1/firestore_client_example_test.go index 06155b8ab23e..bc84b0c6ee64 100644 --- a/firestore/apiv1/firestore_client_example_test.go +++ b/firestore/apiv1/firestore_client_example_test.go @@ -43,6 +43,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := firestore.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_GetDocument() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/firestore/apiv1/firestorepb/aggregation_result.pb.go b/firestore/apiv1/firestorepb/aggregation_result.pb.go index 7a085248f6ec..c855c9609bc4 100644 --- a/firestore/apiv1/firestorepb/aggregation_result.pb.go +++ b/firestore/apiv1/firestorepb/aggregation_result.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/firestore/v1/aggregation_result.proto package firestorepb diff --git a/firestore/apiv1/firestorepb/common.pb.go b/firestore/apiv1/firestorepb/common.pb.go index 24b348988f17..909757f0010f 100644 --- a/firestore/apiv1/firestorepb/common.pb.go +++ b/firestore/apiv1/firestorepb/common.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/firestore/v1/common.proto package firestorepb @@ -99,7 +99,6 @@ type Precondition struct { // The type of precondition. // // Types that are assignable to ConditionType: - // // *Precondition_Exists // *Precondition_UpdateTime ConditionType isPrecondition_ConditionType `protobuf_oneof:"condition_type"` @@ -187,7 +186,6 @@ type TransactionOptions struct { // The mode of the transaction. // // Types that are assignable to Mode: - // // *TransactionOptions_ReadOnly_ // *TransactionOptions_ReadWrite_ Mode isTransactionOptions_Mode `protobuf_oneof:"mode"` @@ -323,7 +321,6 @@ type TransactionOptions_ReadOnly struct { // consistency. // // Types that are assignable to ConsistencySelector: - // // *TransactionOptions_ReadOnly_ReadTime ConsistencySelector isTransactionOptions_ReadOnly_ConsistencySelector `protobuf_oneof:"consistency_selector"` } diff --git a/firestore/apiv1/firestorepb/document.pb.go b/firestore/apiv1/firestorepb/document.pb.go index ea7a45bff40e..ffdd4e6a6101 100644 --- a/firestore/apiv1/firestorepb/document.pb.go +++ b/firestore/apiv1/firestorepb/document.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/firestore/v1/document.proto package firestorepb @@ -69,10 +69,10 @@ type Document struct { // `"foo" : { map_value: { "x&y" : { string_value: "hello" }}}` would be // represented by the field path `foo.x&y`. // - // Within a field path, a quoted field name starts and ends with “ ` “ and - // may contain any character. Some characters, including “ ` “, must be - // escaped using a `\`. For example, “ `x&y` “ represents `x&y` and - // “ `bak\`tik` “ represents “ bak`tik “. + // Within a field path, a quoted field name starts and ends with `` ` `` and + // may contain any character. Some characters, including `` ` ``, must be + // escaped using a `\`. For example, `` `x&y` `` represents `x&y` and + // `` `bak\`tik` `` represents `` bak`tik ``. Fields map[string]*Value `protobuf:"bytes,2,rep,name=fields,proto3" json:"fields,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` // Output only. The time at which the document was created. // @@ -157,7 +157,6 @@ type Value struct { // Must have a value set. // // Types that are assignable to ValueType: - // // *Value_NullValue // *Value_BooleanValue // *Value_IntegerValue @@ -215,7 +214,7 @@ func (x *Value) GetNullValue() structpb.NullValue { if x, ok := x.GetValueType().(*Value_NullValue); ok { return x.NullValue } - return structpb.NullValue_NULL_VALUE + return structpb.NullValue(0) } func (x *Value) GetBooleanValue() bool { diff --git a/firestore/apiv1/firestorepb/firestore.pb.go b/firestore/apiv1/firestorepb/firestore.pb.go index 5a229e64b2cf..00719c6f8006 100644 --- a/firestore/apiv1/firestorepb/firestore.pb.go +++ b/firestore/apiv1/firestorepb/firestore.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/firestore/v1/firestore.proto package firestorepb @@ -133,7 +133,6 @@ type GetDocumentRequest struct { // If not set, defaults to strong consistency. // // Types that are assignable to ConsistencySelector: - // // *GetDocumentRequest_Transaction // *GetDocumentRequest_ReadTime ConsistencySelector isGetDocumentRequest_ConsistencySelector `protobuf_oneof:"consistency_selector"` @@ -256,7 +255,6 @@ type ListDocumentsRequest struct { // If not set, defaults to strong consistency. // // Types that are assignable to ConsistencySelector: - // // *ListDocumentsRequest_Transaction // *ListDocumentsRequest_ReadTime ConsistencySelector isListDocumentsRequest_ConsistencySelector `protobuf_oneof:"consistency_selector"` @@ -711,7 +709,6 @@ type BatchGetDocumentsRequest struct { // If not set, defaults to strong consistency. // // Types that are assignable to ConsistencySelector: - // // *BatchGetDocumentsRequest_Transaction // *BatchGetDocumentsRequest_NewTransaction // *BatchGetDocumentsRequest_ReadTime @@ -838,7 +835,6 @@ type BatchGetDocumentsResponse struct { // This can be empty if the server is just returning a transaction. // // Types that are assignable to Result: - // // *BatchGetDocumentsResponse_Found // *BatchGetDocumentsResponse_Missing Result isBatchGetDocumentsResponse_Result `protobuf_oneof:"result"` @@ -1255,14 +1251,12 @@ type RunQueryRequest struct { // The query to run. // // Types that are assignable to QueryType: - // // *RunQueryRequest_StructuredQuery QueryType isRunQueryRequest_QueryType `protobuf_oneof:"query_type"` // The consistency mode for this transaction. // If not set, defaults to strong consistency. // // Types that are assignable to ConsistencySelector: - // // *RunQueryRequest_Transaction // *RunQueryRequest_NewTransaction // *RunQueryRequest_ReadTime @@ -1421,7 +1415,6 @@ type RunQueryResponse struct { // `document` present, but when set, no more results are returned. // // Types that are assignable to ContinuationSelector: - // // *RunQueryResponse_Done ContinuationSelector isRunQueryResponse_ContinuationSelector `protobuf_oneof:"continuation_selector"` } @@ -1528,13 +1521,11 @@ type RunAggregationQueryRequest struct { // The query to run. // // Types that are assignable to QueryType: - // // *RunAggregationQueryRequest_StructuredAggregationQuery QueryType isRunAggregationQueryRequest_QueryType `protobuf_oneof:"query_type"` // The consistency mode for the query, defaults to strong consistency. // // Types that are assignable to ConsistencySelector: - // // *RunAggregationQueryRequest_Transaction // *RunAggregationQueryRequest_NewTransaction // *RunAggregationQueryRequest_ReadTime @@ -1755,7 +1746,6 @@ type PartitionQueryRequest struct { // The query to partition. // // Types that are assignable to QueryType: - // // *PartitionQueryRequest_StructuredQuery QueryType isPartitionQueryRequest_QueryType `protobuf_oneof:"query_type"` // The desired maximum number of partition points. @@ -1774,8 +1764,8 @@ type PartitionQueryRequest struct { // // For example, two subsequent calls using a page_token may return: // - // - cursor B, cursor M, cursor Q - // - cursor A, cursor U, cursor W + // * cursor B, cursor M, cursor Q + // * cursor A, cursor U, cursor W // // To obtain a complete result set ordered with respect to the results of the // query supplied to PartitionQuery, the results sets should be merged: @@ -1793,7 +1783,6 @@ type PartitionQueryRequest struct { // If not set, defaults to strong consistency. // // Types that are assignable to ConsistencySelector: - // // *PartitionQueryRequest_ReadTime ConsistencySelector isPartitionQueryRequest_ConsistencySelector `protobuf_oneof:"consistency_selector"` } @@ -1929,9 +1918,9 @@ type PartitionQueryResponse struct { // running the following three queries will return the entire result set of // the original query: // - // - query, end_at A - // - query, start_at A, end_at B - // - query, start_at B + // * query, end_at A + // * query, start_at A, end_at B + // * query, start_at B // // An empty result may indicate that the query has too few results to be // partitioned. @@ -2200,7 +2189,6 @@ type ListenRequest struct { // The supported target changes. // // Types that are assignable to TargetChange: - // // *ListenRequest_AddTarget // *ListenRequest_RemoveTarget TargetChange isListenRequest_TargetChange `protobuf_oneof:"target_change"` @@ -2302,7 +2290,6 @@ type ListenResponse struct { // The supported responses. // // Types that are assignable to ResponseType: - // // *ListenResponse_TargetChange // *ListenResponse_DocumentChange // *ListenResponse_DocumentDelete @@ -2438,7 +2425,6 @@ type Target struct { // The type of target to listen to. // // Types that are assignable to TargetType: - // // *Target_Query // *Target_Documents TargetType isTarget_TargetType `protobuf_oneof:"target_type"` @@ -2448,7 +2434,6 @@ type Target struct { // subsequent changes. // // Types that are assignable to ResumeType: - // // *Target_ResumeToken // *Target_ReadTime ResumeType isTarget_ResumeType `protobuf_oneof:"resume_type"` @@ -2708,7 +2693,6 @@ type ListCollectionIdsRequest struct { // If not set, defaults to strong consistency. // // Types that are assignable to ConsistencySelector: - // // *ListCollectionIdsRequest_ReadTime ConsistencySelector isListCollectionIdsRequest_ConsistencySelector `protobuf_oneof:"consistency_selector"` } @@ -3054,7 +3038,6 @@ type Target_QueryTarget struct { // The query to run. // // Types that are assignable to QueryType: - // // *Target_QueryTarget_StructuredQuery QueryType isTarget_QueryTarget_QueryType `protobuf_oneof:"query_type"` } diff --git a/firestore/apiv1/firestorepb/query.pb.go b/firestore/apiv1/firestorepb/query.pb.go index 198498365a21..f7c72a7fef97 100644 --- a/firestore/apiv1/firestorepb/query.pb.go +++ b/firestore/apiv1/firestorepb/query.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/firestore/v1/query.proto package firestorepb @@ -199,10 +199,10 @@ const ( // // Requires: // - // - That `value` is a non-empty `ArrayValue` with at most 10 values. - // - No other `IN`, `ARRAY_CONTAINS_ANY`, `NOT_IN`, `NOT_EQUAL`, - // `IS_NOT_NULL`, or `IS_NOT_NAN`. - // - That `field` comes first in the `order_by`. + // * That `value` is a non-empty `ArrayValue` with at most 10 values. + // * No other `IN`, `ARRAY_CONTAINS_ANY`, `NOT_IN`, `NOT_EQUAL`, + // `IS_NOT_NULL`, or `IS_NOT_NAN`. + // * That `field` comes first in the `order_by`. StructuredQuery_FieldFilter_NOT_IN StructuredQuery_FieldFilter_Operator = 10 ) @@ -352,19 +352,19 @@ type StructuredQuery struct { // no ordering at all. In all cases, Firestore guarantees a stable ordering // through the following rules: // - // - The `order_by` is required to reference all fields used with an - // inequality filter. - // - All fields that are required to be in the `order_by` but are not already - // present are appended in lexicographical ordering of the field name. - // - If an order on `__name__` is not specified, it is appended by default. + // * The `order_by` is required to reference all fields used with an + // inequality filter. + // * All fields that are required to be in the `order_by` but are not already + // present are appended in lexicographical ordering of the field name. + // * If an order on `__name__` is not specified, it is appended by default. // // Fields are appended with the same sort direction as the last order // specified, or 'ASCENDING' if no order was specified. For example: // - // - `ORDER BY a` becomes `ORDER BY a ASC, __name__ ASC` - // - `ORDER BY a DESC` becomes `ORDER BY a DESC, __name__ DESC` - // - `WHERE a > 1` becomes `WHERE a > 1 ORDER BY a ASC, __name__ ASC` - // - `WHERE __name__ > ... AND a > 1` becomes + // * `ORDER BY a` becomes `ORDER BY a ASC, __name__ ASC` + // * `ORDER BY a DESC` becomes `ORDER BY a DESC, __name__ DESC` + // * `WHERE a > 1` becomes `WHERE a > 1 ORDER BY a ASC, __name__ ASC` + // * `WHERE __name__ > ... AND a > 1` becomes // `WHERE __name__ > ... AND a > 1 ORDER BY a ASC, __name__ ASC` OrderBy []*StructuredQuery_Order `protobuf:"bytes,4,rep,name=order_by,json=orderBy,proto3" json:"order_by,omitempty"` // A potential prefix of a position in the result set to start the query at. @@ -385,9 +385,9 @@ type StructuredQuery struct { // Continuing off the example above, attaching the following start cursors // will have varying impact: // - // - `START BEFORE (2, /k/123)`: start the query right before `a = 1 AND - // b > 2 AND __name__ > /k/123`. - // - `START AFTER (10)`: start the query right after `a = 1 AND b > 10`. + // - `START BEFORE (2, /k/123)`: start the query right before `a = 1 AND + // b > 2 AND __name__ > /k/123`. + // - `START AFTER (10)`: start the query right after `a = 1 AND b > 10`. // // Unlike `OFFSET` which requires scanning over the first N results to skip, // a start cursor allows the query to begin at a logical position. This @@ -396,8 +396,8 @@ type StructuredQuery struct { // // Requires: // - // - The number of values cannot be greater than the number of fields - // specified in the `ORDER BY` clause. + // * The number of values cannot be greater than the number of fields + // specified in the `ORDER BY` clause. StartAt *Cursor `protobuf:"bytes,7,opt,name=start_at,json=startAt,proto3" json:"start_at,omitempty"` // A potential prefix of a position in the result set to end the query at. // @@ -406,8 +406,8 @@ type StructuredQuery struct { // // Requires: // - // - The number of values cannot be greater than the number of fields - // specified in the `ORDER BY` clause. + // * The number of values cannot be greater than the number of fields + // specified in the `ORDER BY` clause. EndAt *Cursor `protobuf:"bytes,8,opt,name=end_at,json=endAt,proto3" json:"end_at,omitempty"` // The number of documents to skip before returning the first result. // @@ -525,7 +525,6 @@ type StructuredAggregationQuery struct { // The base query to aggregate over. // // Types that are assignable to QueryType: - // // *StructuredAggregationQuery_StructuredQuery QueryType isStructuredAggregationQuery_QueryType `protobuf_oneof:"query_type"` // Optional. Series of aggregations to apply over the results of the `structured_query`. @@ -732,7 +731,6 @@ type StructuredQuery_Filter struct { // The type of filter. // // Types that are assignable to FilterType: - // // *StructuredQuery_Filter_CompositeFilter // *StructuredQuery_Filter_FieldFilter // *StructuredQuery_Filter_UnaryFilter @@ -964,7 +962,6 @@ type StructuredQuery_UnaryFilter struct { // The argument to the filter. // // Types that are assignable to OperandType: - // // *StructuredQuery_UnaryFilter_Field OperandType isStructuredQuery_UnaryFilter_OperandType `protobuf_oneof:"operand_type"` } @@ -1205,7 +1202,6 @@ type StructuredAggregationQuery_Aggregation struct { // The type of aggregation to perform, required. // // Types that are assignable to Operator: - // // *StructuredAggregationQuery_Aggregation_Count_ Operator isStructuredAggregationQuery_Aggregation_Operator `protobuf_oneof:"operator"` // Optional. Optional name of the field to store the result of the aggregation into. @@ -1215,16 +1211,12 @@ type StructuredAggregationQuery_Aggregation struct { // // ``` // AGGREGATE - // - // COUNT_UP_TO(1) AS count_up_to_1, - // COUNT_UP_TO(2), - // COUNT_UP_TO(3) AS count_up_to_3, - // COUNT_UP_TO(4) - // + // COUNT_UP_TO(1) AS count_up_to_1, + // COUNT_UP_TO(2), + // COUNT_UP_TO(3) AS count_up_to_3, + // COUNT_UP_TO(4) // OVER ( - // - // ... - // + // ... // ); // ``` // @@ -1232,16 +1224,12 @@ type StructuredAggregationQuery_Aggregation struct { // // ``` // AGGREGATE - // - // COUNT_UP_TO(1) AS count_up_to_1, - // COUNT_UP_TO(2) AS field_1, - // COUNT_UP_TO(3) AS count_up_to_3, - // COUNT_UP_TO(4) AS field_2 - // + // COUNT_UP_TO(1) AS count_up_to_1, + // COUNT_UP_TO(2) AS field_1, + // COUNT_UP_TO(3) AS count_up_to_3, + // COUNT_UP_TO(4) AS field_2 // OVER ( - // - // ... - // + // ... // ); // ``` // diff --git a/firestore/apiv1/firestorepb/write.pb.go b/firestore/apiv1/firestorepb/write.pb.go index 49714338a1ac..7bedd9670b65 100644 --- a/firestore/apiv1/firestorepb/write.pb.go +++ b/firestore/apiv1/firestorepb/write.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/firestore/v1/write.proto package firestorepb @@ -96,7 +96,6 @@ type Write struct { // The operation to execute. // // Types that are assignable to Operation: - // // *Write_Update // *Write_Delete // *Write_Transform @@ -653,7 +652,6 @@ type DocumentTransform_FieldTransform struct { // The transformation to apply on the field. // // Types that are assignable to TransformType: - // // *DocumentTransform_FieldTransform_SetToServerValue // *DocumentTransform_FieldTransform_Increment // *DocumentTransform_FieldTransform_Maximum diff --git a/firestore/apiv1/gapic_metadata.json b/firestore/apiv1/gapic_metadata.json index b073738c35d4..89b5d48c3b3e 100644 --- a/firestore/apiv1/gapic_metadata.json +++ b/firestore/apiv1/gapic_metadata.json @@ -111,6 +111,111 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "BatchGetDocuments": { + "methods": [ + "BatchGetDocuments" + ] + }, + "BatchWrite": { + "methods": [ + "BatchWrite" + ] + }, + "BeginTransaction": { + "methods": [ + "BeginTransaction" + ] + }, + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "Commit": { + "methods": [ + "Commit" + ] + }, + "CreateDocument": { + "methods": [ + "CreateDocument" + ] + }, + "DeleteDocument": { + "methods": [ + "DeleteDocument" + ] + }, + "DeleteOperation": { + "methods": [ + "DeleteOperation" + ] + }, + "GetDocument": { + "methods": [ + "GetDocument" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ListCollectionIds": { + "methods": [ + "ListCollectionIds" + ] + }, + "ListDocuments": { + "methods": [ + "ListDocuments" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "Listen": { + "methods": [ + "Listen" + ] + }, + "PartitionQuery": { + "methods": [ + "PartitionQuery" + ] + }, + "Rollback": { + "methods": [ + "Rollback" + ] + }, + "RunAggregationQuery": { + "methods": [ + "RunAggregationQuery" + ] + }, + "RunQuery": { + "methods": [ + "RunQuery" + ] + }, + "UpdateDocument": { + "methods": [ + "UpdateDocument" + ] + }, + "Write": { + "methods": [ + "Write" + ] + } + } } } } diff --git a/functions/apiv1/cloud_functions_client.go b/functions/apiv1/cloud_functions_client.go index e4f962e2b807..353eaa92c94b 100644 --- a/functions/apiv1/cloud_functions_client.go +++ b/functions/apiv1/cloud_functions_client.go @@ -17,9 +17,12 @@ package functions import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,15 +30,18 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" iampb "google.golang.org/genproto/googleapis/iam/v1" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -128,6 +134,62 @@ func defaultCloudFunctionsCallOptions() *CloudFunctionsCallOptions { } } +func defaultCloudFunctionsRESTCallOptions() *CloudFunctionsCallOptions { + return &CloudFunctionsCallOptions{ + ListFunctions: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + GetFunction: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + CreateFunction: []gax.CallOption{}, + UpdateFunction: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + DeleteFunction: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + CallFunction: []gax.CallOption{}, + GenerateUploadUrl: []gax.CallOption{}, + GenerateDownloadUrl: []gax.CallOption{}, + SetIamPolicy: []gax.CallOption{}, + GetIamPolicy: []gax.CallOption{}, + TestIamPermissions: []gax.CallOption{}, + } +} + // internalCloudFunctionsClient is an interface that defines the methods available from Cloud Functions API. type internalCloudFunctionsClient interface { Close() error @@ -403,6 +465,89 @@ func (c *cloudFunctionsGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type cloudFunctionsRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing CloudFunctionsClient + CallOptions **CloudFunctionsCallOptions +} + +// NewCloudFunctionsRESTClient creates a new cloud functions service rest client. +// +// A service that application uses to manipulate triggers and functions. +func NewCloudFunctionsRESTClient(ctx context.Context, opts ...option.ClientOption) (*CloudFunctionsClient, error) { + clientOpts := append(defaultCloudFunctionsRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultCloudFunctionsRESTCallOptions() + c := &cloudFunctionsRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &CloudFunctionsClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultCloudFunctionsRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://cloudfunctions.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://cloudfunctions.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://cloudfunctions.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *cloudFunctionsRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *cloudFunctionsRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *cloudFunctionsRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *cloudFunctionsGRPCClient) ListFunctions(ctx context.Context, req *functionspb.ListFunctionsRequest, opts ...gax.CallOption) *CloudFunctionIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -649,136 +794,941 @@ func (c *cloudFunctionsGRPCClient) TestIamPermissions(ctx context.Context, req * return resp, nil } -// CreateFunctionOperation manages a long-running operation from CreateFunction. -type CreateFunctionOperation struct { - lro *longrunning.Operation -} +// ListFunctions returns a list of functions that belong to the requested project. +func (c *cloudFunctionsRESTClient) ListFunctions(ctx context.Context, req *functionspb.ListFunctionsRequest, opts ...gax.CallOption) *CloudFunctionIterator { + it := &CloudFunctionIterator{} + req = proto.Clone(req).(*functionspb.ListFunctionsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*functionspb.CloudFunction, string, error) { + resp := &functionspb.ListFunctionsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/functions", req.GetParent()) -// CreateFunctionOperation returns a new CreateFunctionOperation from a given name. -// The name must be that of a previously created CreateFunctionOperation, possibly from a different process. -func (c *cloudFunctionsGRPCClient) CreateFunctionOperation(name string) *CreateFunctionOperation { - return &CreateFunctionOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *CreateFunctionOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*functionspb.CloudFunction, error) { - var resp functionspb.CloudFunction - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { - return nil, err + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetFunctions(), resp.GetNextPageToken(), nil } - return &resp, nil -} -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *CreateFunctionOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*functionspb.CloudFunction, error) { - var resp functionspb.CloudFunction - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { - return nil, err - } - if !op.Done() { - return nil, 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 } - return &resp, nil + + it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it } -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *CreateFunctionOperation) Metadata() (*functionspb.OperationMetadataV1, error) { - var meta functionspb.OperationMetadataV1 - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { +// GetFunction returns a function with the given name from the requested project. +func (c *cloudFunctionsRESTClient) GetFunction(ctx context.Context, req *functionspb.GetFunctionRequest, opts ...gax.CallOption) (*functionspb.CloudFunction, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - return &meta, nil -} + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) -// Done reports whether the long-running operation has completed. -func (op *CreateFunctionOperation) Done() bool { - return op.lro.Done() -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") -// 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 *CreateFunctionOperation) Name() string { - return op.lro.Name() -} + baseUrl.RawQuery = params.Encode() -// DeleteFunctionOperation manages a long-running operation from DeleteFunction. -type DeleteFunctionOperation struct { - lro *longrunning.Operation -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) -// DeleteFunctionOperation returns a new DeleteFunctionOperation from a given name. -// The name must be that of a previously created DeleteFunctionOperation, possibly from a different process. -func (c *cloudFunctionsGRPCClient) DeleteFunctionOperation(name string) *DeleteFunctionOperation { - return &DeleteFunctionOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetFunction[0:len((*c.CallOptions).GetFunction):len((*c.CallOptions).GetFunction)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &functionspb.CloudFunction{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *DeleteFunctionOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { - return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) -} + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *DeleteFunctionOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { - return op.lro.Poll(ctx, nil, opts...) + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil } -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *DeleteFunctionOperation) Metadata() (*functionspb.OperationMetadataV1, error) { - var meta functionspb.OperationMetadataV1 - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { +// CreateFunction creates a new function. If a function with the given name already exists in +// the specified project, the long running operation will return +// ALREADY_EXISTS error. +func (c *cloudFunctionsRESTClient) CreateFunction(ctx context.Context, req *functionspb.CreateFunctionRequest, opts ...gax.CallOption) (*CreateFunctionOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetFunction() + jsonReq, err := m.Marshal(body) + if err != nil { return nil, err } - return &meta, nil -} -// Done reports whether the long-running operation has completed. -func (op *DeleteFunctionOperation) Done() bool { - return op.lro.Done() -} + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/functions", req.GetLocation()) -// 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 *DeleteFunctionOperation) Name() string { + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "location", url.QueryEscape(req.GetLocation()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateFunctionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateFunction updates existing function. +func (c *cloudFunctionsRESTClient) UpdateFunction(ctx context.Context, req *functionspb.UpdateFunctionRequest, opts ...gax.CallOption) (*UpdateFunctionOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetFunction() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetFunction().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "function.name", url.QueryEscape(req.GetFunction().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateFunctionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteFunction deletes a function with the given name from the specified project. If the +// given function is used by some trigger, the trigger will be updated to +// remove this function. +func (c *cloudFunctionsRESTClient) DeleteFunction(ctx context.Context, req *functionspb.DeleteFunctionRequest, opts ...gax.CallOption) (*DeleteFunctionOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteFunctionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// CallFunction synchronously invokes a deployed Cloud Function. To be used for testing +// purposes as very limited traffic is allowed. For more information on +// the actual limits, refer to +// Rate Limits (at https://cloud.google.com/functions/quotas#rate_limits). +func (c *cloudFunctionsRESTClient) CallFunction(ctx context.Context, req *functionspb.CallFunctionRequest, opts ...gax.CallOption) (*functionspb.CallFunctionResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:call", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CallFunction[0:len((*c.CallOptions).CallFunction):len((*c.CallOptions).CallFunction)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &functionspb.CallFunctionResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GenerateUploadUrl returns a signed URL for uploading a function source code. +// For more information about the signed URL usage see: +// https://cloud.google.com/storage/docs/access-control/signed-urls (at https://cloud.google.com/storage/docs/access-control/signed-urls). +// Once the function source code upload is complete, the used signed +// URL should be provided in CreateFunction or UpdateFunction request +// as a reference to the function source code. +// +// When uploading source code to the generated signed URL, please follow +// these restrictions: +// +// Source file type should be a zip file. +// +// Source file size should not exceed 100MB limit. +// +// No credentials should be attached - the signed URLs provide access to the +// target bucket using internal service identity; if credentials were +// attached, the identity from the credentials would be used, but that +// identity does not have permissions to upload files to the URL. +// +// When making a HTTP PUT request, these two headers need to be specified: +// +// content-type: application/zip +// +// x-goog-content-length-range: 0,104857600 +// +// And this header SHOULD NOT be specified: +// +// Authorization: Bearer YOUR_TOKEN +func (c *cloudFunctionsRESTClient) GenerateUploadUrl(ctx context.Context, req *functionspb.GenerateUploadUrlRequest, opts ...gax.CallOption) (*functionspb.GenerateUploadUrlResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/functions:generateUploadUrl", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GenerateUploadUrl[0:len((*c.CallOptions).GenerateUploadUrl):len((*c.CallOptions).GenerateUploadUrl)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &functionspb.GenerateUploadUrlResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GenerateDownloadUrl returns a signed URL for downloading deployed function source code. +// The URL is only valid for a limited period and should be used within +// minutes after generation. +// For more information about the signed URL usage see: +// https://cloud.google.com/storage/docs/access-control/signed-urls (at https://cloud.google.com/storage/docs/access-control/signed-urls) +func (c *cloudFunctionsRESTClient) GenerateDownloadUrl(ctx context.Context, req *functionspb.GenerateDownloadUrlRequest, opts ...gax.CallOption) (*functionspb.GenerateDownloadUrlResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:generateDownloadUrl", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GenerateDownloadUrl[0:len((*c.CallOptions).GenerateDownloadUrl):len((*c.CallOptions).GenerateDownloadUrl)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &functionspb.GenerateDownloadUrlResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SetIamPolicy sets the IAM access control policy on the specified function. +// Replaces any existing policy. +func (c *cloudFunctionsRESTClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:setIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetIamPolicy gets the IAM access control policy for a function. +// Returns an empty policy if the function exists and does not have a policy +// set. +func (c *cloudFunctionsRESTClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:getIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetOptions().GetRequestedPolicyVersion() != 0 { + params.Add("options.requestedPolicyVersion", fmt.Sprintf("%v", req.GetOptions().GetRequestedPolicyVersion())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// TestIamPermissions tests the specified permissions against the IAM access control policy +// for a function. +// If the function does not exist, this will return an empty set of +// permissions, not a NOT_FOUND error. +func (c *cloudFunctionsRESTClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:testIamPermissions", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.TestIamPermissionsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateFunctionOperation manages a long-running operation from CreateFunction. +type CreateFunctionOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateFunctionOperation returns a new CreateFunctionOperation from a given name. +// The name must be that of a previously created CreateFunctionOperation, possibly from a different process. +func (c *cloudFunctionsGRPCClient) CreateFunctionOperation(name string) *CreateFunctionOperation { + return &CreateFunctionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateFunctionOperation returns a new CreateFunctionOperation from a given name. +// The name must be that of a previously created CreateFunctionOperation, possibly from a different process. +func (c *cloudFunctionsRESTClient) CreateFunctionOperation(name string) *CreateFunctionOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateFunctionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CreateFunctionOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*functionspb.CloudFunction, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp functionspb.CloudFunction + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *CreateFunctionOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*functionspb.CloudFunction, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp functionspb.CloudFunction + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *CreateFunctionOperation) Metadata() (*functionspb.OperationMetadataV1, error) { + var meta functionspb.OperationMetadataV1 + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *CreateFunctionOperation) Done() bool { + return op.lro.Done() +} + +// 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 *CreateFunctionOperation) Name() string { + return op.lro.Name() +} + +// DeleteFunctionOperation manages a long-running operation from DeleteFunction. +type DeleteFunctionOperation struct { + lro *longrunning.Operation + pollPath string +} + +// DeleteFunctionOperation returns a new DeleteFunctionOperation from a given name. +// The name must be that of a previously created DeleteFunctionOperation, possibly from a different process. +func (c *cloudFunctionsGRPCClient) DeleteFunctionOperation(name string) *DeleteFunctionOperation { + return &DeleteFunctionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// DeleteFunctionOperation returns a new DeleteFunctionOperation from a given name. +// The name must be that of a previously created DeleteFunctionOperation, possibly from a different process. +func (c *cloudFunctionsRESTClient) DeleteFunctionOperation(name string) *DeleteFunctionOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteFunctionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *DeleteFunctionOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *DeleteFunctionOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + return op.lro.Poll(ctx, nil, opts...) +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *DeleteFunctionOperation) Metadata() (*functionspb.OperationMetadataV1, error) { + var meta functionspb.OperationMetadataV1 + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *DeleteFunctionOperation) Done() bool { + return op.lro.Done() +} + +// 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 *DeleteFunctionOperation) Name() string { return op.lro.Name() } // UpdateFunctionOperation manages a long-running operation from UpdateFunction. type UpdateFunctionOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateFunctionOperation returns a new UpdateFunctionOperation from a given name. @@ -789,10 +1739,21 @@ func (c *cloudFunctionsGRPCClient) UpdateFunctionOperation(name string) *UpdateF } } +// UpdateFunctionOperation returns a new UpdateFunctionOperation from a given name. +// The name must be that of a previously created UpdateFunctionOperation, possibly from a different process. +func (c *cloudFunctionsRESTClient) UpdateFunctionOperation(name string) *UpdateFunctionOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateFunctionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateFunctionOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*functionspb.CloudFunction, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp functionspb.CloudFunction if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -810,6 +1771,7 @@ func (op *UpdateFunctionOperation) Wait(ctx context.Context, opts ...gax.CallOpt // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateFunctionOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*functionspb.CloudFunction, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp functionspb.CloudFunction if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/functions/apiv1/cloud_functions_client_example_test.go b/functions/apiv1/cloud_functions_client_example_test.go index a2bfa81e6a80..58c4abcd9479 100644 --- a/functions/apiv1/cloud_functions_client_example_test.go +++ b/functions/apiv1/cloud_functions_client_example_test.go @@ -42,6 +42,23 @@ func ExampleNewCloudFunctionsClient() { _ = c } +func ExampleNewCloudFunctionsRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := functions.NewCloudFunctionsRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleCloudFunctionsClient_ListFunctions() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/functions/apiv1/doc.go b/functions/apiv1/doc.go index c9d1c058264a..dd4ac71dc8a9 100644 --- a/functions/apiv1/doc.go +++ b/functions/apiv1/doc.go @@ -87,6 +87,8 @@ package functions // import "cloud.google.com/go/functions/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -175,3 +177,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/functions/apiv1/functionspb/functions.pb.go b/functions/apiv1/functionspb/functions.pb.go index 23ca446a1487..6cf8d7cc392f 100644 --- a/functions/apiv1/functionspb/functions.pb.go +++ b/functions/apiv1/functionspb/functions.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/functions/v1/functions.proto package functionspb @@ -363,7 +363,6 @@ type CloudFunction struct { // The location of the function source code. // // Types that are assignable to SourceCode: - // // *CloudFunction_SourceArchiveUrl // *CloudFunction_SourceRepository // *CloudFunction_SourceUploadUrl @@ -371,7 +370,6 @@ type CloudFunction struct { // An event that triggers the function. // // Types that are assignable to Trigger: - // // *CloudFunction_HttpsTrigger // *CloudFunction_EventTrigger Trigger isCloudFunction_Trigger `protobuf_oneof:"trigger"` @@ -473,17 +471,17 @@ type CloudFunction struct { // CryptoKey Encrypter/Decrypter (roles/cloudkms.cryptoKeyEncrypterDecrypter)' // on the Key/KeyRing/Project/Organization (least access preferred). // - // 1. Google Cloud Functions service account - // (service-{project_number}@gcf-admin-robot.iam.gserviceaccount.com) - - // Required to protect the function's image. - // 2. Google Storage service account - // (service-{project_number}@gs-project-accounts.iam.gserviceaccount.com) - - // Required to protect the function's source code. - // If this service account does not exist, deploying a function without a - // KMS key or retrieving the service agent name provisions it. For more - // information, see - // https://cloud.google.com/storage/docs/projects#service-agents and - // https://cloud.google.com/storage/docs/getting-service-agent#gsutil. + // 1. Google Cloud Functions service account + // (service-{project_number}@gcf-admin-robot.iam.gserviceaccount.com) - + // Required to protect the function's image. + // 2. Google Storage service account + // (service-{project_number}@gs-project-accounts.iam.gserviceaccount.com) - + // Required to protect the function's source code. + // If this service account does not exist, deploying a function without a + // KMS key or retrieving the service agent name provisions it. For more + // information, see + // https://cloud.google.com/storage/docs/projects#service-agents and + // https://cloud.google.com/storage/docs/getting-service-agent#gsutil. // // Google Cloud Functions delegates access to service agents to protect // function resources in internal projects that are not accessible by the @@ -1011,13 +1009,12 @@ type EventTrigger struct { // Event types match pattern `providers/*/eventTypes/*.*`. // The pattern contains: // - // 1. namespace: For example, `cloud.storage` and - // `google.firebase.analytics`. - // 2. resource type: The type of resource on which event occurs. For - // example, the Google Cloud Storage API includes the type `object`. - // 3. action: The action that generates the event. For example, action for - // a Google Cloud Storage Object is 'change'. - // + // 1. namespace: For example, `cloud.storage` and + // `google.firebase.analytics`. + // 2. resource type: The type of resource on which event occurs. For + // example, the Google Cloud Storage API includes the type `object`. + // 3. action: The action that generates the event. For example, action for + // a Google Cloud Storage Object is 'change'. // These parts are lower case. EventType string `protobuf:"bytes,1,opt,name=event_type,json=eventType,proto3" json:"event_type,omitempty"` // Required. The resource(s) from which to observe events, for example, @@ -1026,13 +1023,13 @@ type EventTrigger struct { // Not all syntactically correct values are accepted by all services. For // example: // - // 1. The authorization model must support it. Google Cloud Functions - // only allows EventTriggers to be deployed that observe resources in the - // same project as the `CloudFunction`. - // 2. The resource type must match the pattern expected for an - // `event_type`. For example, an `EventTrigger` that has an - // `event_type` of "google.pubsub.topic.publish" should have a resource - // that matches Google Cloud Pub/Sub topics. + // 1. The authorization model must support it. Google Cloud Functions + // only allows EventTriggers to be deployed that observe resources in the + // same project as the `CloudFunction`. + // 2. The resource type must match the pattern expected for an + // `event_type`. For example, an `EventTrigger` that has an + // `event_type` of "google.pubsub.topic.publish" should have a resource + // that matches Google Cloud Pub/Sub topics. // // Additionally, some services may support short names when creating an // `EventTrigger`. These will always be returned in the normalized "long" @@ -1120,7 +1117,6 @@ type FailurePolicy struct { // Defines the action taken in case of a function execution failure. // // Types that are assignable to Action: - // // *FailurePolicy_Retry_ Action isFailurePolicy_Action `protobuf_oneof:"action"` } @@ -3146,12 +3142,12 @@ type CloudFunctionsServiceClient interface { // When uploading source code to the generated signed URL, please follow // these restrictions: // - // - Source file type should be a zip file. - // - Source file size should not exceed 100MB limit. - // - No credentials should be attached - the signed URLs provide access to the - // target bucket using internal service identity; if credentials were - // attached, the identity from the credentials would be used, but that - // identity does not have permissions to upload files to the URL. + // * Source file type should be a zip file. + // * Source file size should not exceed 100MB limit. + // * No credentials should be attached - the signed URLs provide access to the + // target bucket using internal service identity; if credentials were + // attached, the identity from the credentials would be used, but that + // identity does not have permissions to upload files to the URL. // // When making a HTTP PUT request, these two headers need to be specified: // @@ -3320,12 +3316,12 @@ type CloudFunctionsServiceServer interface { // When uploading source code to the generated signed URL, please follow // these restrictions: // - // - Source file type should be a zip file. - // - Source file size should not exceed 100MB limit. - // - No credentials should be attached - the signed URLs provide access to the - // target bucket using internal service identity; if credentials were - // attached, the identity from the credentials would be used, but that - // identity does not have permissions to upload files to the URL. + // * Source file type should be a zip file. + // * Source file size should not exceed 100MB limit. + // * No credentials should be attached - the signed URLs provide access to the + // target bucket using internal service identity; if credentials were + // attached, the identity from the credentials would be used, but that + // identity does not have permissions to upload files to the URL. // // When making a HTTP PUT request, these two headers need to be specified: // diff --git a/functions/apiv1/functionspb/operations.pb.go b/functions/apiv1/functionspb/operations.pb.go index 4a5342f7fd71..216308f0915d 100644 --- a/functions/apiv1/functionspb/operations.pb.go +++ b/functions/apiv1/functionspb/operations.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/functions/v1/operations.proto package functionspb diff --git a/functions/apiv1/gapic_metadata.json b/functions/apiv1/gapic_metadata.json index 176b9f45521a..15fbd3a8dbfe 100644 --- a/functions/apiv1/gapic_metadata.json +++ b/functions/apiv1/gapic_metadata.json @@ -66,6 +66,66 @@ ] } } + }, + "rest": { + "libraryClient": "CloudFunctionsClient", + "rpcs": { + "CallFunction": { + "methods": [ + "CallFunction" + ] + }, + "CreateFunction": { + "methods": [ + "CreateFunction" + ] + }, + "DeleteFunction": { + "methods": [ + "DeleteFunction" + ] + }, + "GenerateDownloadUrl": { + "methods": [ + "GenerateDownloadUrl" + ] + }, + "GenerateUploadUrl": { + "methods": [ + "GenerateUploadUrl" + ] + }, + "GetFunction": { + "methods": [ + "GetFunction" + ] + }, + "GetIamPolicy": { + "methods": [ + "GetIamPolicy" + ] + }, + "ListFunctions": { + "methods": [ + "ListFunctions" + ] + }, + "SetIamPolicy": { + "methods": [ + "SetIamPolicy" + ] + }, + "TestIamPermissions": { + "methods": [ + "TestIamPermissions" + ] + }, + "UpdateFunction": { + "methods": [ + "UpdateFunction" + ] + } + } } } } diff --git a/functions/apiv2/doc.go b/functions/apiv2/doc.go index 2a49ca76f00f..8c6882d3822b 100644 --- a/functions/apiv2/doc.go +++ b/functions/apiv2/doc.go @@ -83,6 +83,8 @@ package functions // import "cloud.google.com/go/functions/apiv2" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -171,3 +173,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/functions/apiv2/function_client.go b/functions/apiv2/function_client.go index 146f47cca112..78deba8a1aad 100644 --- a/functions/apiv2/function_client.go +++ b/functions/apiv2/function_client.go @@ -17,9 +17,12 @@ package functions import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,15 +30,18 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" iampb "google.golang.org/genproto/googleapis/iam/v1" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -90,6 +96,25 @@ func defaultFunctionCallOptions() *FunctionCallOptions { } } +func defaultFunctionRESTCallOptions() *FunctionCallOptions { + return &FunctionCallOptions{ + GetFunction: []gax.CallOption{}, + ListFunctions: []gax.CallOption{}, + CreateFunction: []gax.CallOption{}, + UpdateFunction: []gax.CallOption{}, + DeleteFunction: []gax.CallOption{}, + GenerateUploadUrl: []gax.CallOption{}, + GenerateDownloadUrl: []gax.CallOption{}, + ListRuntimes: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + GetIamPolicy: []gax.CallOption{}, + SetIamPolicy: []gax.CallOption{}, + TestIamPermissions: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalFunctionClient is an interface that defines the methods available from Cloud Functions API. type internalFunctionClient interface { Close() error @@ -400,6 +425,94 @@ func (c *functionGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type functionRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing FunctionClient + CallOptions **FunctionCallOptions +} + +// NewFunctionRESTClient creates a new function service rest client. +// +// Google Cloud Functions is used to deploy functions that are executed by +// Google in response to various events. Data connected with that event is +// passed to a function as the input data. +// +// A function is a resource which describes a function that should be +// executed and how it is triggered. +func NewFunctionRESTClient(ctx context.Context, opts ...option.ClientOption) (*FunctionClient, error) { + clientOpts := append(defaultFunctionRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultFunctionRESTCallOptions() + c := &functionRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &FunctionClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultFunctionRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://cloudfunctions.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://cloudfunctions.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://cloudfunctions.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *functionRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *functionRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *functionRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *functionGRPCClient) GetFunction(ctx context.Context, req *functionspb.GetFunctionRequest, opts ...gax.CallOption) (*functionspb.Function, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -728,150 +841,1210 @@ func (c *functionGRPCClient) ListOperations(ctx context.Context, req *longrunnin return it } -// CreateFunctionOperation manages a long-running operation from CreateFunction. -type CreateFunctionOperation struct { - lro *longrunning.Operation -} - -// CreateFunctionOperation returns a new CreateFunctionOperation from a given name. -// The name must be that of a previously created CreateFunctionOperation, possibly from a different process. -func (c *functionGRPCClient) CreateFunctionOperation(name string) *CreateFunctionOperation { - return &CreateFunctionOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} - -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *CreateFunctionOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*functionspb.Function, error) { - var resp functionspb.Function - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { +// GetFunction returns a function with the given name from the requested project. +func (c *functionRESTClient) GetFunction(ctx context.Context, req *functionspb.GetFunctionRequest, opts ...gax.CallOption) (*functionspb.Function, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - return &resp, nil -} + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *CreateFunctionOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*functionspb.Function, error) { - var resp functionspb.Function - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { - return nil, err - } - if !op.Done() { - return nil, nil - } - return &resp, nil -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *CreateFunctionOperation) Metadata() (*functionspb.OperationMetadata, error) { - var meta functionspb.OperationMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { - return nil, err + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetFunction[0:len((*c.CallOptions).GetFunction):len((*c.CallOptions).GetFunction)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &functionspb.Function{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e } - return &meta, nil + return resp, nil } -// Done reports whether the long-running operation has completed. -func (op *CreateFunctionOperation) Done() bool { - return op.lro.Done() -} +// ListFunctions returns a list of functions that belong to the requested project. +func (c *functionRESTClient) ListFunctions(ctx context.Context, req *functionspb.ListFunctionsRequest, opts ...gax.CallOption) *FunctionIterator { + it := &FunctionIterator{} + req = proto.Clone(req).(*functionspb.ListFunctionsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*functionspb.Function, string, error) { + resp := &functionspb.ListFunctionsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/functions", req.GetParent()) -// 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 *CreateFunctionOperation) Name() string { - return op.lro.Name() -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } -// DeleteFunctionOperation manages a long-running operation from DeleteFunction. -type DeleteFunctionOperation struct { - lro *longrunning.Operation -} + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetFunctions(), resp.GetNextPageToken(), nil + } -// DeleteFunctionOperation returns a new DeleteFunctionOperation from a given name. -// The name must be that of a previously created DeleteFunctionOperation, possibly from a different process. -func (c *functionGRPCClient) DeleteFunctionOperation(name string) *DeleteFunctionOperation { - return &DeleteFunctionOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + 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 } -} -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *DeleteFunctionOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { - return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) -} + it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *DeleteFunctionOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { - return op.lro.Poll(ctx, nil, opts...) + return it } -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *DeleteFunctionOperation) Metadata() (*functionspb.OperationMetadata, error) { - var meta functionspb.OperationMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { +// CreateFunction creates a new function. If a function with the given name already exists in +// the specified project, the long running operation will return +// ALREADY_EXISTS error. +func (c *functionRESTClient) CreateFunction(ctx context.Context, req *functionspb.CreateFunctionRequest, opts ...gax.CallOption) (*CreateFunctionOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetFunction() + jsonReq, err := m.Marshal(body) + if err != nil { return nil, err } - return &meta, nil -} -// Done reports whether the long-running operation has completed. -func (op *DeleteFunctionOperation) Done() bool { - return op.lro.Done() -} + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/functions", req.GetParent()) -// 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 *DeleteFunctionOperation) Name() string { - return op.lro.Name() -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFunctionId() != "" { + params.Add("functionId", fmt.Sprintf("%v", req.GetFunctionId())) + } -// UpdateFunctionOperation manages a long-running operation from UpdateFunction. -type UpdateFunctionOperation struct { - lro *longrunning.Operation -} + baseUrl.RawQuery = params.Encode() -// UpdateFunctionOperation returns a new UpdateFunctionOperation from a given name. -// The name must be that of a previously created UpdateFunctionOperation, possibly from a different process. -func (c *functionGRPCClient) UpdateFunctionOperation(name string) *UpdateFunctionOperation { - return &UpdateFunctionOperation{ + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &CreateFunctionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateFunction updates existing function. +func (c *functionRESTClient) UpdateFunction(ctx context.Context, req *functionspb.UpdateFunctionRequest, opts ...gax.CallOption) (*UpdateFunctionOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetFunction() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetFunction().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "function.name", url.QueryEscape(req.GetFunction().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &UpdateFunctionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteFunction deletes a function with the given name from the specified project. If the +// given function is used by some trigger, the trigger will be updated to +// remove this function. +func (c *functionRESTClient) DeleteFunction(ctx context.Context, req *functionspb.DeleteFunctionRequest, opts ...gax.CallOption) (*DeleteFunctionOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &DeleteFunctionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GenerateUploadUrl returns a signed URL for uploading a function source code. +// For more information about the signed URL usage see: +// https://cloud.google.com/storage/docs/access-control/signed-urls (at https://cloud.google.com/storage/docs/access-control/signed-urls). +// Once the function source code upload is complete, the used signed +// URL should be provided in CreateFunction or UpdateFunction request +// as a reference to the function source code. +// +// When uploading source code to the generated signed URL, please follow +// these restrictions: +// +// Source file type should be a zip file. +// +// No credentials should be attached - the signed URLs provide access to the +// target bucket using internal service identity; if credentials were +// attached, the identity from the credentials would be used, but that +// identity does not have permissions to upload files to the URL. +// +// When making a HTTP PUT request, these two headers need to be specified: +// +// content-type: application/zip +// +// And this header SHOULD NOT be specified: +// +// Authorization: Bearer YOUR_TOKEN +func (c *functionRESTClient) GenerateUploadUrl(ctx context.Context, req *functionspb.GenerateUploadUrlRequest, opts ...gax.CallOption) (*functionspb.GenerateUploadUrlResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/functions:generateUploadUrl", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GenerateUploadUrl[0:len((*c.CallOptions).GenerateUploadUrl):len((*c.CallOptions).GenerateUploadUrl)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &functionspb.GenerateUploadUrlResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GenerateDownloadUrl returns a signed URL for downloading deployed function source code. +// The URL is only valid for a limited period and should be used within +// 30 minutes of generation. +// For more information about the signed URL usage see: +// https://cloud.google.com/storage/docs/access-control/signed-urls (at https://cloud.google.com/storage/docs/access-control/signed-urls) +func (c *functionRESTClient) GenerateDownloadUrl(ctx context.Context, req *functionspb.GenerateDownloadUrlRequest, opts ...gax.CallOption) (*functionspb.GenerateDownloadUrlResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:generateDownloadUrl", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GenerateDownloadUrl[0:len((*c.CallOptions).GenerateDownloadUrl):len((*c.CallOptions).GenerateDownloadUrl)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &functionspb.GenerateDownloadUrlResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListRuntimes returns a list of runtimes that are supported for the requested project. +func (c *functionRESTClient) ListRuntimes(ctx context.Context, req *functionspb.ListRuntimesRequest, opts ...gax.CallOption) (*functionspb.ListRuntimesResponse, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/runtimes", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).ListRuntimes[0:len((*c.CallOptions).ListRuntimes):len((*c.CallOptions).ListRuntimes)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &functionspb.ListRuntimesResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *functionRESTClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetIamPolicy gets the access control policy for a resource. Returns an empty policy +// if the resource exists and does not have a policy set. +func (c *functionRESTClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:getIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetOptions().GetRequestedPolicyVersion() != 0 { + params.Add("options.requestedPolicyVersion", fmt.Sprintf("%v", req.GetOptions().GetRequestedPolicyVersion())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SetIamPolicy sets the access control policy on the specified resource. Replaces +// any existing policy. +// +// Can return NOT_FOUND, INVALID_ARGUMENT, and PERMISSION_DENIED +// errors. +func (c *functionRESTClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:setIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// TestIamPermissions returns permissions that a caller has on the specified resource. If the +// resource does not exist, this will return an empty set of +// permissions, not a NOT_FOUND error. +// +// Note: This operation is designed to be used for building +// permission-aware UIs and command-line tools, not for authorization +// checking. This operation may “fail open” without warning. +func (c *functionRESTClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:testIamPermissions", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.TestIamPermissionsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *functionRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *functionRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CreateFunctionOperation manages a long-running operation from CreateFunction. +type CreateFunctionOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateFunctionOperation returns a new CreateFunctionOperation from a given name. +// The name must be that of a previously created CreateFunctionOperation, possibly from a different process. +func (c *functionGRPCClient) CreateFunctionOperation(name string) *CreateFunctionOperation { + return &CreateFunctionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateFunctionOperation returns a new CreateFunctionOperation from a given name. +// The name must be that of a previously created CreateFunctionOperation, possibly from a different process. +func (c *functionRESTClient) CreateFunctionOperation(name string) *CreateFunctionOperation { + override := fmt.Sprintf("/v2/%s", name) + return &CreateFunctionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CreateFunctionOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*functionspb.Function, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp functionspb.Function + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *CreateFunctionOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*functionspb.Function, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp functionspb.Function + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *CreateFunctionOperation) Metadata() (*functionspb.OperationMetadata, error) { + var meta functionspb.OperationMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *CreateFunctionOperation) Done() bool { + return op.lro.Done() +} + +// 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 *CreateFunctionOperation) Name() string { + return op.lro.Name() +} + +// DeleteFunctionOperation manages a long-running operation from DeleteFunction. +type DeleteFunctionOperation struct { + lro *longrunning.Operation + pollPath string +} + +// DeleteFunctionOperation returns a new DeleteFunctionOperation from a given name. +// The name must be that of a previously created DeleteFunctionOperation, possibly from a different process. +func (c *functionGRPCClient) DeleteFunctionOperation(name string) *DeleteFunctionOperation { + return &DeleteFunctionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// DeleteFunctionOperation returns a new DeleteFunctionOperation from a given name. +// The name must be that of a previously created DeleteFunctionOperation, possibly from a different process. +func (c *functionRESTClient) DeleteFunctionOperation(name string) *DeleteFunctionOperation { + override := fmt.Sprintf("/v2/%s", name) + return &DeleteFunctionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *DeleteFunctionOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *DeleteFunctionOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + return op.lro.Poll(ctx, nil, opts...) +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *DeleteFunctionOperation) Metadata() (*functionspb.OperationMetadata, error) { + var meta functionspb.OperationMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *DeleteFunctionOperation) Done() bool { + return op.lro.Done() +} + +// 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 *DeleteFunctionOperation) Name() string { + return op.lro.Name() +} + +// UpdateFunctionOperation manages a long-running operation from UpdateFunction. +type UpdateFunctionOperation struct { + lro *longrunning.Operation + pollPath string +} + +// UpdateFunctionOperation returns a new UpdateFunctionOperation from a given name. +// The name must be that of a previously created UpdateFunctionOperation, possibly from a different process. +func (c *functionGRPCClient) UpdateFunctionOperation(name string) *UpdateFunctionOperation { + return &UpdateFunctionOperation{ lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } +// UpdateFunctionOperation returns a new UpdateFunctionOperation from a given name. +// The name must be that of a previously created UpdateFunctionOperation, possibly from a different process. +func (c *functionRESTClient) UpdateFunctionOperation(name string) *UpdateFunctionOperation { + override := fmt.Sprintf("/v2/%s", name) + return &UpdateFunctionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateFunctionOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*functionspb.Function, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp functionspb.Function if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -889,6 +2062,7 @@ func (op *UpdateFunctionOperation) Wait(ctx context.Context, opts ...gax.CallOpt // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateFunctionOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*functionspb.Function, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp functionspb.Function if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/functions/apiv2/function_client_example_test.go b/functions/apiv2/function_client_example_test.go index 2710b9a36153..9c0b1f95ccc0 100644 --- a/functions/apiv2/function_client_example_test.go +++ b/functions/apiv2/function_client_example_test.go @@ -44,6 +44,23 @@ func ExampleNewFunctionClient() { _ = c } +func ExampleNewFunctionRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := functions.NewFunctionRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleFunctionClient_GetFunction() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/functions/apiv2/functionspb/functions.pb.go b/functions/apiv2/functionspb/functions.pb.go index 6991688bbe2a..d3f4297ba5e4 100644 --- a/functions/apiv2/functionspb/functions.pb.go +++ b/functions/apiv2/functionspb/functions.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/functions/v2/functions.proto package functionspb @@ -873,7 +873,6 @@ type RepoSource struct { // one of these ways. // // Types that are assignable to Revision: - // // *RepoSource_BranchName // *RepoSource_TagName // *RepoSource_CommitSha @@ -1023,7 +1022,6 @@ type Source struct { // At least one source needs to be provided for the deployment to succeed. // // Types that are assignable to Source: - // // *Source_StorageSource // *Source_RepoSource Source isSource_Source `protobuf_oneof:"source"` @@ -4209,11 +4207,11 @@ type FunctionServiceClient interface { // When uploading source code to the generated signed URL, please follow // these restrictions: // - // - Source file type should be a zip file. - // - No credentials should be attached - the signed URLs provide access to the - // target bucket using internal service identity; if credentials were - // attached, the identity from the credentials would be used, but that - // identity does not have permissions to upload files to the URL. + // * Source file type should be a zip file. + // * No credentials should be attached - the signed URLs provide access to the + // target bucket using internal service identity; if credentials were + // attached, the identity from the credentials would be used, but that + // identity does not have permissions to upload files to the URL. // // When making a HTTP PUT request, these two headers need to be specified: // @@ -4339,11 +4337,11 @@ type FunctionServiceServer interface { // When uploading source code to the generated signed URL, please follow // these restrictions: // - // - Source file type should be a zip file. - // - No credentials should be attached - the signed URLs provide access to the - // target bucket using internal service identity; if credentials were - // attached, the identity from the credentials would be used, but that - // identity does not have permissions to upload files to the URL. + // * Source file type should be a zip file. + // * No credentials should be attached - the signed URLs provide access to the + // target bucket using internal service identity; if credentials were + // attached, the identity from the credentials would be used, but that + // identity does not have permissions to upload files to the URL. // // When making a HTTP PUT request, these two headers need to be specified: // diff --git a/functions/apiv2/gapic_metadata.json b/functions/apiv2/gapic_metadata.json index e19a20c7019f..d560ee58275f 100644 --- a/functions/apiv2/gapic_metadata.json +++ b/functions/apiv2/gapic_metadata.json @@ -81,6 +81,81 @@ ] } } + }, + "rest": { + "libraryClient": "FunctionClient", + "rpcs": { + "CreateFunction": { + "methods": [ + "CreateFunction" + ] + }, + "DeleteFunction": { + "methods": [ + "DeleteFunction" + ] + }, + "GenerateDownloadUrl": { + "methods": [ + "GenerateDownloadUrl" + ] + }, + "GenerateUploadUrl": { + "methods": [ + "GenerateUploadUrl" + ] + }, + "GetFunction": { + "methods": [ + "GetFunction" + ] + }, + "GetIamPolicy": { + "methods": [ + "GetIamPolicy" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ListFunctions": { + "methods": [ + "ListFunctions" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "ListRuntimes": { + "methods": [ + "ListRuntimes" + ] + }, + "SetIamPolicy": { + "methods": [ + "SetIamPolicy" + ] + }, + "TestIamPermissions": { + "methods": [ + "TestIamPermissions" + ] + }, + "UpdateFunction": { + "methods": [ + "UpdateFunction" + ] + } + } } } } diff --git a/functions/apiv2beta/function_client.go b/functions/apiv2beta/function_client.go index 71112c6c39f1..f5adadc823d3 100644 --- a/functions/apiv2beta/function_client.go +++ b/functions/apiv2beta/function_client.go @@ -849,6 +849,11 @@ func (c *functionRESTClient) GetFunction(ctx context.Context, req *functionspb.G } baseUrl.Path += fmt.Sprintf("/v2beta/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -916,6 +921,7 @@ func (c *functionRESTClient) ListFunctions(ctx context.Context, req *functionspb baseUrl.Path += fmt.Sprintf("/v2beta/%v/functions", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1005,6 +1011,7 @@ func (c *functionRESTClient) CreateFunction(ctx context.Context, req *functionsp baseUrl.Path += fmt.Sprintf("/v2beta/%v/functions", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFunctionId() != "" { params.Add("functionId", fmt.Sprintf("%v", req.GetFunctionId())) } @@ -1076,6 +1083,7 @@ func (c *functionRESTClient) UpdateFunction(ctx context.Context, req *functionsp baseUrl.Path += fmt.Sprintf("/v2beta/%v", req.GetFunction().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -1145,6 +1153,11 @@ func (c *functionRESTClient) DeleteFunction(ctx context.Context, req *functionsp } baseUrl.Path += fmt.Sprintf("/v2beta/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1231,6 +1244,11 @@ func (c *functionRESTClient) GenerateUploadUrl(ctx context.Context, req *functio } baseUrl.Path += fmt.Sprintf("/v2beta/%v/functions:generateUploadUrl", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1294,6 +1312,11 @@ func (c *functionRESTClient) GenerateDownloadUrl(ctx context.Context, req *funct } baseUrl.Path += fmt.Sprintf("/v2beta/%v:generateDownloadUrl", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1348,6 +1371,7 @@ func (c *functionRESTClient) ListRuntimes(ctx context.Context, req *functionspb. baseUrl.Path += fmt.Sprintf("/v2beta/%v/runtimes", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1421,6 +1445,7 @@ func (c *functionRESTClient) ListLocations(ctx context.Context, req *locationpb. baseUrl.Path += fmt.Sprintf("/v2beta/%v/locations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1499,6 +1524,7 @@ func (c *functionRESTClient) GetIamPolicy(ctx context.Context, req *iampb.GetIam baseUrl.Path += fmt.Sprintf("/v2beta/%v:getIamPolicy", req.GetResource()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetOptions().GetRequestedPolicyVersion() != 0 { params.Add("options.requestedPolicyVersion", fmt.Sprintf("%v", req.GetOptions().GetRequestedPolicyVersion())) } @@ -1568,6 +1594,11 @@ func (c *functionRESTClient) SetIamPolicy(ctx context.Context, req *iampb.SetIam } baseUrl.Path += fmt.Sprintf("/v2beta/%v:setIamPolicy", req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) @@ -1633,6 +1664,11 @@ func (c *functionRESTClient) TestIamPermissions(ctx context.Context, req *iampb. } baseUrl.Path += fmt.Sprintf("/v2beta/%v:testIamPermissions", req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) @@ -1686,6 +1722,11 @@ func (c *functionRESTClient) GetOperation(ctx context.Context, req *longrunningp } baseUrl.Path += fmt.Sprintf("/v2beta/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1753,6 +1794,7 @@ func (c *functionRESTClient) ListOperations(ctx context.Context, req *longrunnin baseUrl.Path += fmt.Sprintf("/v2beta/%v/operations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/functions/apiv2beta/functionspb/functions.pb.go b/functions/apiv2beta/functionspb/functions.pb.go index e8fbc1ab46d6..0b7b284926a6 100644 --- a/functions/apiv2beta/functionspb/functions.pb.go +++ b/functions/apiv2beta/functionspb/functions.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/functions/v2beta/functions.proto package functionspb @@ -873,7 +873,6 @@ type RepoSource struct { // one of these ways. // // Types that are assignable to Revision: - // // *RepoSource_BranchName // *RepoSource_TagName // *RepoSource_CommitSha @@ -1023,7 +1022,6 @@ type Source struct { // At least one source needs to be provided for the deployment to succeed. // // Types that are assignable to Source: - // // *Source_StorageSource // *Source_RepoSource Source isSource_Source `protobuf_oneof:"source"` @@ -4217,11 +4215,11 @@ type FunctionServiceClient interface { // When uploading source code to the generated signed URL, please follow // these restrictions: // - // - Source file type should be a zip file. - // - No credentials should be attached - the signed URLs provide access to the - // target bucket using internal service identity; if credentials were - // attached, the identity from the credentials would be used, but that - // identity does not have permissions to upload files to the URL. + // * Source file type should be a zip file. + // * No credentials should be attached - the signed URLs provide access to the + // target bucket using internal service identity; if credentials were + // attached, the identity from the credentials would be used, but that + // identity does not have permissions to upload files to the URL. // // When making a HTTP PUT request, these two headers need to be specified: // @@ -4347,11 +4345,11 @@ type FunctionServiceServer interface { // When uploading source code to the generated signed URL, please follow // these restrictions: // - // - Source file type should be a zip file. - // - No credentials should be attached - the signed URLs provide access to the - // target bucket using internal service identity; if credentials were - // attached, the identity from the credentials would be used, but that - // identity does not have permissions to upload files to the URL. + // * Source file type should be a zip file. + // * No credentials should be attached - the signed URLs provide access to the + // target bucket using internal service identity; if credentials were + // attached, the identity from the credentials would be used, but that + // identity does not have permissions to upload files to the URL. // // When making a HTTP PUT request, these two headers need to be specified: // diff --git a/gaming/apiv1/doc.go b/gaming/apiv1/doc.go index dba170f05df3..caa8061b374e 100644 --- a/gaming/apiv1/doc.go +++ b/gaming/apiv1/doc.go @@ -87,6 +87,8 @@ package gaming // import "cloud.google.com/go/gaming/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -175,3 +177,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/gaming/apiv1/game_server_clusters_client.go b/gaming/apiv1/game_server_clusters_client.go index 72dad4f7595e..9d1198037c18 100644 --- a/gaming/apiv1/game_server_clusters_client.go +++ b/gaming/apiv1/game_server_clusters_client.go @@ -17,9 +17,12 @@ package gaming import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,14 +30,17 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -127,6 +133,64 @@ func defaultGameServerClustersCallOptions() *GameServerClustersCallOptions { } } +func defaultGameServerClustersRESTCallOptions() *GameServerClustersCallOptions { + return &GameServerClustersCallOptions{ + ListGameServerClusters: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetGameServerCluster: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateGameServerCluster: []gax.CallOption{}, + PreviewCreateGameServerCluster: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeleteGameServerCluster: []gax.CallOption{}, + PreviewDeleteGameServerCluster: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UpdateGameServerCluster: []gax.CallOption{}, + PreviewUpdateGameServerCluster: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + } +} + // internalGameServerClustersClient is an interface that defines the methods available from Game Services API. type internalGameServerClustersClient interface { Close() error @@ -343,6 +407,90 @@ func (c *gameServerClustersGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gameServerClustersRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing GameServerClustersClient + CallOptions **GameServerClustersCallOptions +} + +// NewGameServerClustersRESTClient creates a new game server clusters service rest client. +// +// The game server cluster maps to Kubernetes clusters running Agones and is +// used to manage fleets within clusters. +func NewGameServerClustersRESTClient(ctx context.Context, opts ...option.ClientOption) (*GameServerClustersClient, error) { + clientOpts := append(defaultGameServerClustersRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultGameServerClustersRESTCallOptions() + c := &gameServerClustersRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &GameServerClustersClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultGameServerClustersRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://gameservices.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://gameservices.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://gameservices.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *gameServerClustersRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gameServerClustersRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *gameServerClustersRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *gameServerClustersGRPCClient) ListGameServerClusters(ctx context.Context, req *gamingpb.ListGameServerClustersRequest, opts ...gax.CallOption) *GameServerClusterIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -548,9 +696,597 @@ func (c *gameServerClustersGRPCClient) PreviewUpdateGameServerCluster(ctx contex return resp, nil } +// ListGameServerClusters lists game server clusters in a given project and location. +func (c *gameServerClustersRESTClient) ListGameServerClusters(ctx context.Context, req *gamingpb.ListGameServerClustersRequest, opts ...gax.CallOption) *GameServerClusterIterator { + it := &GameServerClusterIterator{} + req = proto.Clone(req).(*gamingpb.ListGameServerClustersRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*gamingpb.GameServerCluster, string, error) { + resp := &gamingpb.ListGameServerClustersResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/gameServerClusters", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + if req.GetView() != 0 { + params.Add("view", fmt.Sprintf("%v", req.GetView())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetGameServerClusters(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetGameServerCluster gets details of a single game server cluster. +func (c *gameServerClustersRESTClient) GetGameServerCluster(ctx context.Context, req *gamingpb.GetGameServerClusterRequest, opts ...gax.CallOption) (*gamingpb.GameServerCluster, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetView() != 0 { + params.Add("view", fmt.Sprintf("%v", req.GetView())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetGameServerCluster[0:len((*c.CallOptions).GetGameServerCluster):len((*c.CallOptions).GetGameServerCluster)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &gamingpb.GameServerCluster{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateGameServerCluster creates a new game server cluster in a given project and location. +func (c *gameServerClustersRESTClient) CreateGameServerCluster(ctx context.Context, req *gamingpb.CreateGameServerClusterRequest, opts ...gax.CallOption) (*CreateGameServerClusterOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetGameServerCluster() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/gameServerClusters", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("gameServerClusterId", fmt.Sprintf("%v", req.GetGameServerClusterId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateGameServerClusterOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// PreviewCreateGameServerCluster previews creation of a new game server cluster in a given project and +// location. +func (c *gameServerClustersRESTClient) PreviewCreateGameServerCluster(ctx context.Context, req *gamingpb.PreviewCreateGameServerClusterRequest, opts ...gax.CallOption) (*gamingpb.PreviewCreateGameServerClusterResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetGameServerCluster() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/gameServerClusters:previewCreate", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("gameServerClusterId", fmt.Sprintf("%v", req.GetGameServerClusterId())) + if req.GetPreviewTime() != nil { + previewTime, err := protojson.Marshal(req.GetPreviewTime()) + if err != nil { + return nil, err + } + params.Add("previewTime", string(previewTime)) + } + if req.GetView() != 0 { + params.Add("view", fmt.Sprintf("%v", req.GetView())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).PreviewCreateGameServerCluster[0:len((*c.CallOptions).PreviewCreateGameServerCluster):len((*c.CallOptions).PreviewCreateGameServerCluster)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &gamingpb.PreviewCreateGameServerClusterResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteGameServerCluster deletes a single game server cluster. +func (c *gameServerClustersRESTClient) DeleteGameServerCluster(ctx context.Context, req *gamingpb.DeleteGameServerClusterRequest, opts ...gax.CallOption) (*DeleteGameServerClusterOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteGameServerClusterOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// PreviewDeleteGameServerCluster previews deletion of a single game server cluster. +func (c *gameServerClustersRESTClient) PreviewDeleteGameServerCluster(ctx context.Context, req *gamingpb.PreviewDeleteGameServerClusterRequest, opts ...gax.CallOption) (*gamingpb.PreviewDeleteGameServerClusterResponse, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:previewDelete", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPreviewTime() != nil { + previewTime, err := protojson.Marshal(req.GetPreviewTime()) + if err != nil { + return nil, err + } + params.Add("previewTime", string(previewTime)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).PreviewDeleteGameServerCluster[0:len((*c.CallOptions).PreviewDeleteGameServerCluster):len((*c.CallOptions).PreviewDeleteGameServerCluster)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &gamingpb.PreviewDeleteGameServerClusterResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateGameServerCluster patches a single game server cluster. +func (c *gameServerClustersRESTClient) UpdateGameServerCluster(ctx context.Context, req *gamingpb.UpdateGameServerClusterRequest, opts ...gax.CallOption) (*UpdateGameServerClusterOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetGameServerCluster() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetGameServerCluster().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "game_server_cluster.name", url.QueryEscape(req.GetGameServerCluster().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateGameServerClusterOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// PreviewUpdateGameServerCluster previews updating a GameServerCluster. +func (c *gameServerClustersRESTClient) PreviewUpdateGameServerCluster(ctx context.Context, req *gamingpb.PreviewUpdateGameServerClusterRequest, opts ...gax.CallOption) (*gamingpb.PreviewUpdateGameServerClusterResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetGameServerCluster() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:previewUpdate", req.GetGameServerCluster().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPreviewTime() != nil { + previewTime, err := protojson.Marshal(req.GetPreviewTime()) + if err != nil { + return nil, err + } + params.Add("previewTime", string(previewTime)) + } + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "game_server_cluster.name", url.QueryEscape(req.GetGameServerCluster().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).PreviewUpdateGameServerCluster[0:len((*c.CallOptions).PreviewUpdateGameServerCluster):len((*c.CallOptions).PreviewUpdateGameServerCluster)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &gamingpb.PreviewUpdateGameServerClusterResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + // CreateGameServerClusterOperation manages a long-running operation from CreateGameServerCluster. type CreateGameServerClusterOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateGameServerClusterOperation returns a new CreateGameServerClusterOperation from a given name. @@ -561,10 +1297,21 @@ func (c *gameServerClustersGRPCClient) CreateGameServerClusterOperation(name str } } +// CreateGameServerClusterOperation returns a new CreateGameServerClusterOperation from a given name. +// The name must be that of a previously created CreateGameServerClusterOperation, possibly from a different process. +func (c *gameServerClustersRESTClient) CreateGameServerClusterOperation(name string) *CreateGameServerClusterOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateGameServerClusterOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateGameServerClusterOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*gamingpb.GameServerCluster, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp gamingpb.GameServerCluster if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -582,6 +1329,7 @@ func (op *CreateGameServerClusterOperation) Wait(ctx context.Context, opts ...ga // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateGameServerClusterOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*gamingpb.GameServerCluster, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp gamingpb.GameServerCluster if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -619,7 +1367,8 @@ func (op *CreateGameServerClusterOperation) Name() string { // DeleteGameServerClusterOperation manages a long-running operation from DeleteGameServerCluster. type DeleteGameServerClusterOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteGameServerClusterOperation returns a new DeleteGameServerClusterOperation from a given name. @@ -630,10 +1379,21 @@ func (c *gameServerClustersGRPCClient) DeleteGameServerClusterOperation(name str } } +// DeleteGameServerClusterOperation returns a new DeleteGameServerClusterOperation from a given name. +// The name must be that of a previously created DeleteGameServerClusterOperation, possibly from a different process. +func (c *gameServerClustersRESTClient) DeleteGameServerClusterOperation(name string) *DeleteGameServerClusterOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteGameServerClusterOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteGameServerClusterOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -647,6 +1407,7 @@ func (op *DeleteGameServerClusterOperation) Wait(ctx context.Context, opts ...ga // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteGameServerClusterOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -677,7 +1438,8 @@ func (op *DeleteGameServerClusterOperation) Name() string { // UpdateGameServerClusterOperation manages a long-running operation from UpdateGameServerCluster. type UpdateGameServerClusterOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateGameServerClusterOperation returns a new UpdateGameServerClusterOperation from a given name. @@ -688,10 +1450,21 @@ func (c *gameServerClustersGRPCClient) UpdateGameServerClusterOperation(name str } } +// UpdateGameServerClusterOperation returns a new UpdateGameServerClusterOperation from a given name. +// The name must be that of a previously created UpdateGameServerClusterOperation, possibly from a different process. +func (c *gameServerClustersRESTClient) UpdateGameServerClusterOperation(name string) *UpdateGameServerClusterOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateGameServerClusterOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateGameServerClusterOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*gamingpb.GameServerCluster, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp gamingpb.GameServerCluster if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -709,6 +1482,7 @@ func (op *UpdateGameServerClusterOperation) Wait(ctx context.Context, opts ...ga // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateGameServerClusterOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*gamingpb.GameServerCluster, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp gamingpb.GameServerCluster if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/gaming/apiv1/game_server_clusters_client_example_test.go b/gaming/apiv1/game_server_clusters_client_example_test.go index 85234019ee2a..0cf6422d8c16 100644 --- a/gaming/apiv1/game_server_clusters_client_example_test.go +++ b/gaming/apiv1/game_server_clusters_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewGameServerClustersClient() { _ = c } +func ExampleNewGameServerClustersRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := gaming.NewGameServerClustersRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleGameServerClustersClient_ListGameServerClusters() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/gaming/apiv1/game_server_configs_client.go b/gaming/apiv1/game_server_configs_client.go index b7d8e82d5aef..3194db06330a 100644 --- a/gaming/apiv1/game_server_configs_client.go +++ b/gaming/apiv1/game_server_configs_client.go @@ -17,9 +17,12 @@ package gaming import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,14 +30,17 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -89,6 +95,33 @@ func defaultGameServerConfigsCallOptions() *GameServerConfigsCallOptions { } } +func defaultGameServerConfigsRESTCallOptions() *GameServerConfigsCallOptions { + return &GameServerConfigsCallOptions{ + ListGameServerConfigs: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetGameServerConfig: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateGameServerConfig: []gax.CallOption{}, + DeleteGameServerConfig: []gax.CallOption{}, + } +} + // internalGameServerConfigsClient is an interface that defines the methods available from Game Services API. type internalGameServerConfigsClient interface { Close() error @@ -275,6 +308,89 @@ func (c *gameServerConfigsGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gameServerConfigsRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing GameServerConfigsClient + CallOptions **GameServerConfigsCallOptions +} + +// NewGameServerConfigsRESTClient creates a new game server configs service rest client. +// +// The game server config configures the game servers in an Agones fleet. +func NewGameServerConfigsRESTClient(ctx context.Context, opts ...option.ClientOption) (*GameServerConfigsClient, error) { + clientOpts := append(defaultGameServerConfigsRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultGameServerConfigsRESTCallOptions() + c := &gameServerConfigsRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &GameServerConfigsClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultGameServerConfigsRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://gameservices.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://gameservices.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://gameservices.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *gameServerConfigsRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gameServerConfigsRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *gameServerConfigsRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *gameServerConfigsGRPCClient) ListGameServerConfigs(ctx context.Context, req *gamingpb.ListGameServerConfigsRequest, opts ...gax.CallOption) *GameServerConfigIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -390,9 +506,298 @@ func (c *gameServerConfigsGRPCClient) DeleteGameServerConfig(ctx context.Context }, nil } +// ListGameServerConfigs lists game server configs in a given project, location, and game server +// deployment. +func (c *gameServerConfigsRESTClient) ListGameServerConfigs(ctx context.Context, req *gamingpb.ListGameServerConfigsRequest, opts ...gax.CallOption) *GameServerConfigIterator { + it := &GameServerConfigIterator{} + req = proto.Clone(req).(*gamingpb.ListGameServerConfigsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*gamingpb.GameServerConfig, string, error) { + resp := &gamingpb.ListGameServerConfigsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/configs", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetGameServerConfigs(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetGameServerConfig gets details of a single game server config. +func (c *gameServerConfigsRESTClient) GetGameServerConfig(ctx context.Context, req *gamingpb.GetGameServerConfigRequest, opts ...gax.CallOption) (*gamingpb.GameServerConfig, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetGameServerConfig[0:len((*c.CallOptions).GetGameServerConfig):len((*c.CallOptions).GetGameServerConfig)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &gamingpb.GameServerConfig{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateGameServerConfig creates a new game server config in a given project, location, and game +// server deployment. Game server configs are immutable, and are not applied +// until referenced in the game server deployment rollout resource. +func (c *gameServerConfigsRESTClient) CreateGameServerConfig(ctx context.Context, req *gamingpb.CreateGameServerConfigRequest, opts ...gax.CallOption) (*CreateGameServerConfigOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetGameServerConfig() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/configs", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("configId", fmt.Sprintf("%v", req.GetConfigId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateGameServerConfigOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteGameServerConfig deletes a single game server config. The deletion will fail if the game +// server config is referenced in a game server deployment rollout. +func (c *gameServerConfigsRESTClient) DeleteGameServerConfig(ctx context.Context, req *gamingpb.DeleteGameServerConfigRequest, opts ...gax.CallOption) (*DeleteGameServerConfigOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteGameServerConfigOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + // CreateGameServerConfigOperation manages a long-running operation from CreateGameServerConfig. type CreateGameServerConfigOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateGameServerConfigOperation returns a new CreateGameServerConfigOperation from a given name. @@ -403,10 +808,21 @@ func (c *gameServerConfigsGRPCClient) CreateGameServerConfigOperation(name strin } } +// CreateGameServerConfigOperation returns a new CreateGameServerConfigOperation from a given name. +// The name must be that of a previously created CreateGameServerConfigOperation, possibly from a different process. +func (c *gameServerConfigsRESTClient) CreateGameServerConfigOperation(name string) *CreateGameServerConfigOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateGameServerConfigOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateGameServerConfigOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*gamingpb.GameServerConfig, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp gamingpb.GameServerConfig if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -424,6 +840,7 @@ func (op *CreateGameServerConfigOperation) Wait(ctx context.Context, opts ...gax // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateGameServerConfigOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*gamingpb.GameServerConfig, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp gamingpb.GameServerConfig if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -461,7 +878,8 @@ func (op *CreateGameServerConfigOperation) Name() string { // DeleteGameServerConfigOperation manages a long-running operation from DeleteGameServerConfig. type DeleteGameServerConfigOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteGameServerConfigOperation returns a new DeleteGameServerConfigOperation from a given name. @@ -472,10 +890,21 @@ func (c *gameServerConfigsGRPCClient) DeleteGameServerConfigOperation(name strin } } +// DeleteGameServerConfigOperation returns a new DeleteGameServerConfigOperation from a given name. +// The name must be that of a previously created DeleteGameServerConfigOperation, possibly from a different process. +func (c *gameServerConfigsRESTClient) DeleteGameServerConfigOperation(name string) *DeleteGameServerConfigOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteGameServerConfigOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteGameServerConfigOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -489,6 +918,7 @@ func (op *DeleteGameServerConfigOperation) Wait(ctx context.Context, opts ...gax // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteGameServerConfigOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } diff --git a/gaming/apiv1/game_server_configs_client_example_test.go b/gaming/apiv1/game_server_configs_client_example_test.go index adb2abb69efb..883aadda9ece 100644 --- a/gaming/apiv1/game_server_configs_client_example_test.go +++ b/gaming/apiv1/game_server_configs_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewGameServerConfigsClient() { _ = c } +func ExampleNewGameServerConfigsRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := gaming.NewGameServerConfigsRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleGameServerConfigsClient_ListGameServerConfigs() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/gaming/apiv1/game_server_deployments_client.go b/gaming/apiv1/game_server_deployments_client.go index e39dcb2036e2..5f7a54ef2a5f 100644 --- a/gaming/apiv1/game_server_deployments_client.go +++ b/gaming/apiv1/game_server_deployments_client.go @@ -17,9 +17,12 @@ package gaming import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,14 +30,17 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -129,6 +135,65 @@ func defaultGameServerDeploymentsCallOptions() *GameServerDeploymentsCallOptions } } +func defaultGameServerDeploymentsRESTCallOptions() *GameServerDeploymentsCallOptions { + return &GameServerDeploymentsCallOptions{ + ListGameServerDeployments: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetGameServerDeployment: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateGameServerDeployment: []gax.CallOption{}, + DeleteGameServerDeployment: []gax.CallOption{}, + UpdateGameServerDeployment: []gax.CallOption{}, + GetGameServerDeploymentRollout: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UpdateGameServerDeploymentRollout: []gax.CallOption{}, + PreviewGameServerDeploymentRollout: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + FetchDeploymentState: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + } +} + // internalGameServerDeploymentsClient is an interface that defines the methods available from Game Services API. type internalGameServerDeploymentsClient interface { Close() error @@ -365,6 +430,90 @@ func (c *gameServerDeploymentsGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gameServerDeploymentsRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing GameServerDeploymentsClient + CallOptions **GameServerDeploymentsCallOptions +} + +// NewGameServerDeploymentsRESTClient creates a new game server deployments service rest client. +// +// The game server deployment is used to control the deployment of Agones +// fleets. +func NewGameServerDeploymentsRESTClient(ctx context.Context, opts ...option.ClientOption) (*GameServerDeploymentsClient, error) { + clientOpts := append(defaultGameServerDeploymentsRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultGameServerDeploymentsRESTCallOptions() + c := &gameServerDeploymentsRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &GameServerDeploymentsClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultGameServerDeploymentsRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://gameservices.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://gameservices.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://gameservices.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *gameServerDeploymentsRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gameServerDeploymentsRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *gameServerDeploymentsRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *gameServerDeploymentsGRPCClient) ListGameServerDeployments(ctx context.Context, req *gamingpb.ListGameServerDeploymentsRequest, opts ...gax.CallOption) *GameServerDeploymentIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -594,9 +743,655 @@ func (c *gameServerDeploymentsGRPCClient) FetchDeploymentState(ctx context.Conte return resp, nil } +// ListGameServerDeployments lists game server deployments in a given project and location. +func (c *gameServerDeploymentsRESTClient) ListGameServerDeployments(ctx context.Context, req *gamingpb.ListGameServerDeploymentsRequest, opts ...gax.CallOption) *GameServerDeploymentIterator { + it := &GameServerDeploymentIterator{} + req = proto.Clone(req).(*gamingpb.ListGameServerDeploymentsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*gamingpb.GameServerDeployment, string, error) { + resp := &gamingpb.ListGameServerDeploymentsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/gameServerDeployments", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetGameServerDeployments(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetGameServerDeployment gets details of a single game server deployment. +func (c *gameServerDeploymentsRESTClient) GetGameServerDeployment(ctx context.Context, req *gamingpb.GetGameServerDeploymentRequest, opts ...gax.CallOption) (*gamingpb.GameServerDeployment, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetGameServerDeployment[0:len((*c.CallOptions).GetGameServerDeployment):len((*c.CallOptions).GetGameServerDeployment)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &gamingpb.GameServerDeployment{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateGameServerDeployment creates a new game server deployment in a given project and location. +func (c *gameServerDeploymentsRESTClient) CreateGameServerDeployment(ctx context.Context, req *gamingpb.CreateGameServerDeploymentRequest, opts ...gax.CallOption) (*CreateGameServerDeploymentOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetGameServerDeployment() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/gameServerDeployments", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("deploymentId", fmt.Sprintf("%v", req.GetDeploymentId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateGameServerDeploymentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteGameServerDeployment deletes a single game server deployment. +func (c *gameServerDeploymentsRESTClient) DeleteGameServerDeployment(ctx context.Context, req *gamingpb.DeleteGameServerDeploymentRequest, opts ...gax.CallOption) (*DeleteGameServerDeploymentOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteGameServerDeploymentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateGameServerDeployment patches a game server deployment. +func (c *gameServerDeploymentsRESTClient) UpdateGameServerDeployment(ctx context.Context, req *gamingpb.UpdateGameServerDeploymentRequest, opts ...gax.CallOption) (*UpdateGameServerDeploymentOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetGameServerDeployment() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetGameServerDeployment().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "game_server_deployment.name", url.QueryEscape(req.GetGameServerDeployment().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateGameServerDeploymentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetGameServerDeploymentRollout gets details a single game server deployment rollout. +func (c *gameServerDeploymentsRESTClient) GetGameServerDeploymentRollout(ctx context.Context, req *gamingpb.GetGameServerDeploymentRolloutRequest, opts ...gax.CallOption) (*gamingpb.GameServerDeploymentRollout, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/rollout", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetGameServerDeploymentRollout[0:len((*c.CallOptions).GetGameServerDeploymentRollout):len((*c.CallOptions).GetGameServerDeploymentRollout)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &gamingpb.GameServerDeploymentRollout{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateGameServerDeploymentRollout patches a single game server deployment rollout. +// The method will not return an error if the update does not affect any +// existing realms. For example - if the default_game_server_config is changed +// but all existing realms use the override, that is valid. Similarly, if a +// non existing realm is explicitly called out in game_server_config_overrides +// field, that will also not result in an error. +func (c *gameServerDeploymentsRESTClient) UpdateGameServerDeploymentRollout(ctx context.Context, req *gamingpb.UpdateGameServerDeploymentRolloutRequest, opts ...gax.CallOption) (*UpdateGameServerDeploymentRolloutOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetRollout() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/rollout", req.GetRollout().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "rollout.name", url.QueryEscape(req.GetRollout().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateGameServerDeploymentRolloutOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// PreviewGameServerDeploymentRollout previews the game server deployment rollout. This API does not mutate the +// rollout resource. +func (c *gameServerDeploymentsRESTClient) PreviewGameServerDeploymentRollout(ctx context.Context, req *gamingpb.PreviewGameServerDeploymentRolloutRequest, opts ...gax.CallOption) (*gamingpb.PreviewGameServerDeploymentRolloutResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetRollout() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/rollout:preview", req.GetRollout().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPreviewTime() != nil { + previewTime, err := protojson.Marshal(req.GetPreviewTime()) + if err != nil { + return nil, err + } + params.Add("previewTime", string(previewTime)) + } + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "rollout.name", url.QueryEscape(req.GetRollout().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).PreviewGameServerDeploymentRollout[0:len((*c.CallOptions).PreviewGameServerDeploymentRollout):len((*c.CallOptions).PreviewGameServerDeploymentRollout)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &gamingpb.PreviewGameServerDeploymentRolloutResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// FetchDeploymentState retrieves information about the current state of the game server +// deployment. Gathers all the Agones fleets and Agones autoscalers, +// including fleets running an older version of the game server deployment. +func (c *gameServerDeploymentsRESTClient) FetchDeploymentState(ctx context.Context, req *gamingpb.FetchDeploymentStateRequest, opts ...gax.CallOption) (*gamingpb.FetchDeploymentStateResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:fetchDeploymentState", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).FetchDeploymentState[0:len((*c.CallOptions).FetchDeploymentState):len((*c.CallOptions).FetchDeploymentState)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &gamingpb.FetchDeploymentStateResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + // CreateGameServerDeploymentOperation manages a long-running operation from CreateGameServerDeployment. type CreateGameServerDeploymentOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateGameServerDeploymentOperation returns a new CreateGameServerDeploymentOperation from a given name. @@ -607,10 +1402,21 @@ func (c *gameServerDeploymentsGRPCClient) CreateGameServerDeploymentOperation(na } } +// CreateGameServerDeploymentOperation returns a new CreateGameServerDeploymentOperation from a given name. +// The name must be that of a previously created CreateGameServerDeploymentOperation, possibly from a different process. +func (c *gameServerDeploymentsRESTClient) CreateGameServerDeploymentOperation(name string) *CreateGameServerDeploymentOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateGameServerDeploymentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateGameServerDeploymentOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*gamingpb.GameServerDeployment, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp gamingpb.GameServerDeployment if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -628,6 +1434,7 @@ func (op *CreateGameServerDeploymentOperation) Wait(ctx context.Context, opts .. // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateGameServerDeploymentOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*gamingpb.GameServerDeployment, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp gamingpb.GameServerDeployment if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -665,7 +1472,8 @@ func (op *CreateGameServerDeploymentOperation) Name() string { // DeleteGameServerDeploymentOperation manages a long-running operation from DeleteGameServerDeployment. type DeleteGameServerDeploymentOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteGameServerDeploymentOperation returns a new DeleteGameServerDeploymentOperation from a given name. @@ -676,10 +1484,21 @@ func (c *gameServerDeploymentsGRPCClient) DeleteGameServerDeploymentOperation(na } } +// DeleteGameServerDeploymentOperation returns a new DeleteGameServerDeploymentOperation from a given name. +// The name must be that of a previously created DeleteGameServerDeploymentOperation, possibly from a different process. +func (c *gameServerDeploymentsRESTClient) DeleteGameServerDeploymentOperation(name string) *DeleteGameServerDeploymentOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteGameServerDeploymentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteGameServerDeploymentOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -693,6 +1512,7 @@ func (op *DeleteGameServerDeploymentOperation) Wait(ctx context.Context, opts .. // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteGameServerDeploymentOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -723,7 +1543,8 @@ func (op *DeleteGameServerDeploymentOperation) Name() string { // UpdateGameServerDeploymentOperation manages a long-running operation from UpdateGameServerDeployment. type UpdateGameServerDeploymentOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateGameServerDeploymentOperation returns a new UpdateGameServerDeploymentOperation from a given name. @@ -734,10 +1555,21 @@ func (c *gameServerDeploymentsGRPCClient) UpdateGameServerDeploymentOperation(na } } +// UpdateGameServerDeploymentOperation returns a new UpdateGameServerDeploymentOperation from a given name. +// The name must be that of a previously created UpdateGameServerDeploymentOperation, possibly from a different process. +func (c *gameServerDeploymentsRESTClient) UpdateGameServerDeploymentOperation(name string) *UpdateGameServerDeploymentOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateGameServerDeploymentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateGameServerDeploymentOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*gamingpb.GameServerDeployment, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp gamingpb.GameServerDeployment if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -755,6 +1587,7 @@ func (op *UpdateGameServerDeploymentOperation) Wait(ctx context.Context, opts .. // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateGameServerDeploymentOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*gamingpb.GameServerDeployment, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp gamingpb.GameServerDeployment if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -792,7 +1625,8 @@ func (op *UpdateGameServerDeploymentOperation) Name() string { // UpdateGameServerDeploymentRolloutOperation manages a long-running operation from UpdateGameServerDeploymentRollout. type UpdateGameServerDeploymentRolloutOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateGameServerDeploymentRolloutOperation returns a new UpdateGameServerDeploymentRolloutOperation from a given name. @@ -803,10 +1637,21 @@ func (c *gameServerDeploymentsGRPCClient) UpdateGameServerDeploymentRolloutOpera } } +// UpdateGameServerDeploymentRolloutOperation returns a new UpdateGameServerDeploymentRolloutOperation from a given name. +// The name must be that of a previously created UpdateGameServerDeploymentRolloutOperation, possibly from a different process. +func (c *gameServerDeploymentsRESTClient) UpdateGameServerDeploymentRolloutOperation(name string) *UpdateGameServerDeploymentRolloutOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateGameServerDeploymentRolloutOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateGameServerDeploymentRolloutOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*gamingpb.GameServerDeployment, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp gamingpb.GameServerDeployment if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -824,6 +1669,7 @@ func (op *UpdateGameServerDeploymentRolloutOperation) Wait(ctx context.Context, // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateGameServerDeploymentRolloutOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*gamingpb.GameServerDeployment, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp gamingpb.GameServerDeployment if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/gaming/apiv1/game_server_deployments_client_example_test.go b/gaming/apiv1/game_server_deployments_client_example_test.go index df09c45458c4..f840481bde4f 100644 --- a/gaming/apiv1/game_server_deployments_client_example_test.go +++ b/gaming/apiv1/game_server_deployments_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewGameServerDeploymentsClient() { _ = c } +func ExampleNewGameServerDeploymentsRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := gaming.NewGameServerDeploymentsRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleGameServerDeploymentsClient_ListGameServerDeployments() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/gaming/apiv1/gamingpb/common.pb.go b/gaming/apiv1/gamingpb/common.pb.go index bc916d61c1f7..fb2db3586e2c 100644 --- a/gaming/apiv1/gamingpb/common.pb.go +++ b/gaming/apiv1/gamingpb/common.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/gaming/v1/common.proto package gamingpb diff --git a/gaming/apiv1/gamingpb/game_server_clusters.pb.go b/gaming/apiv1/gamingpb/game_server_clusters.pb.go index 6ee37025971e..746948e0ffe2 100644 --- a/gaming/apiv1/gamingpb/game_server_clusters.pb.go +++ b/gaming/apiv1/gamingpb/game_server_clusters.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/gaming/v1/game_server_clusters.proto package gamingpb @@ -1006,7 +1006,6 @@ type GameServerClusterConnectionInfo struct { // The location of the Kubernetes cluster. // // Types that are assignable to ClusterReference: - // // *GameServerClusterConnectionInfo_GkeClusterReference ClusterReference isGameServerClusterConnectionInfo_ClusterReference `protobuf_oneof:"cluster_reference"` // Namespace designated on the game server cluster where the Agones game @@ -1088,10 +1087,9 @@ type GkeClusterReference struct { // The full or partial name of a GKE cluster, using one of the following // forms: - // - `projects/{project}/locations/{location}/clusters/{cluster}` - // - `locations/{location}/clusters/{cluster}` - // - `{cluster}` - // + // * `projects/{project}/locations/{location}/clusters/{cluster}` + // * `locations/{location}/clusters/{cluster}` + // * `{cluster}` // If project and location are not specified, the project and location of the // GameServerCluster resource are used to generate the full name of the // GKE cluster. diff --git a/gaming/apiv1/gamingpb/game_server_clusters_service.pb.go b/gaming/apiv1/gamingpb/game_server_clusters_service.pb.go index c170772e2d0e..203f968314d0 100644 --- a/gaming/apiv1/gamingpb/game_server_clusters_service.pb.go +++ b/gaming/apiv1/gamingpb/game_server_clusters_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/gaming/v1/game_server_clusters_service.proto package gamingpb diff --git a/gaming/apiv1/gamingpb/game_server_configs.pb.go b/gaming/apiv1/gamingpb/game_server_configs.pb.go index 3fdce805e12a..4b94cad658be 100644 --- a/gaming/apiv1/gamingpb/game_server_configs.pb.go +++ b/gaming/apiv1/gamingpb/game_server_configs.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/gaming/v1/game_server_configs.proto package gamingpb diff --git a/gaming/apiv1/gamingpb/game_server_configs_service.pb.go b/gaming/apiv1/gamingpb/game_server_configs_service.pb.go index 602992b7d9a9..cb3ec38ec668 100644 --- a/gaming/apiv1/gamingpb/game_server_configs_service.pb.go +++ b/gaming/apiv1/gamingpb/game_server_configs_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/gaming/v1/game_server_configs_service.proto package gamingpb diff --git a/gaming/apiv1/gamingpb/game_server_deployments.pb.go b/gaming/apiv1/gamingpb/game_server_deployments.pb.go index d7102ebcf9e2..f96c5cc3ebcb 100644 --- a/gaming/apiv1/gamingpb/game_server_deployments.pb.go +++ b/gaming/apiv1/gamingpb/game_server_deployments.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/gaming/v1/game_server_deployments.proto package gamingpb @@ -756,13 +756,11 @@ type GameServerConfigOverride struct { // Selector chooses the game server config targets. // // Types that are assignable to Selector: - // // *GameServerConfigOverride_RealmsSelector Selector isGameServerConfigOverride_Selector `protobuf_oneof:"selector"` // Selects the game server config and how it should be applied. // // Types that are assignable to Change: - // // *GameServerConfigOverride_ConfigVersion Change isGameServerConfigOverride_Change `protobuf_oneof:"change"` } diff --git a/gaming/apiv1/gamingpb/game_server_deployments_service.pb.go b/gaming/apiv1/gamingpb/game_server_deployments_service.pb.go index 34b3701180be..d849bea7e66d 100644 --- a/gaming/apiv1/gamingpb/game_server_deployments_service.pb.go +++ b/gaming/apiv1/gamingpb/game_server_deployments_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/gaming/v1/game_server_deployments_service.proto package gamingpb diff --git a/gaming/apiv1/gamingpb/realms.pb.go b/gaming/apiv1/gamingpb/realms.pb.go index e737ee3f43f2..76b814e1b06f 100644 --- a/gaming/apiv1/gamingpb/realms.pb.go +++ b/gaming/apiv1/gamingpb/realms.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/gaming/v1/realms.proto package gamingpb diff --git a/gaming/apiv1/gamingpb/realms_service.pb.go b/gaming/apiv1/gamingpb/realms_service.pb.go index 2427ad2dbaaf..4a86f0616437 100644 --- a/gaming/apiv1/gamingpb/realms_service.pb.go +++ b/gaming/apiv1/gamingpb/realms_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/gaming/v1/realms_service.proto package gamingpb diff --git a/gaming/apiv1/gapic_metadata.json b/gaming/apiv1/gapic_metadata.json index a7aa70f78b60..9671bae14f18 100644 --- a/gaming/apiv1/gapic_metadata.json +++ b/gaming/apiv1/gapic_metadata.json @@ -51,6 +51,51 @@ ] } } + }, + "rest": { + "libraryClient": "GameServerClustersClient", + "rpcs": { + "CreateGameServerCluster": { + "methods": [ + "CreateGameServerCluster" + ] + }, + "DeleteGameServerCluster": { + "methods": [ + "DeleteGameServerCluster" + ] + }, + "GetGameServerCluster": { + "methods": [ + "GetGameServerCluster" + ] + }, + "ListGameServerClusters": { + "methods": [ + "ListGameServerClusters" + ] + }, + "PreviewCreateGameServerCluster": { + "methods": [ + "PreviewCreateGameServerCluster" + ] + }, + "PreviewDeleteGameServerCluster": { + "methods": [ + "PreviewDeleteGameServerCluster" + ] + }, + "PreviewUpdateGameServerCluster": { + "methods": [ + "PreviewUpdateGameServerCluster" + ] + }, + "UpdateGameServerCluster": { + "methods": [ + "UpdateGameServerCluster" + ] + } + } } } }, @@ -80,6 +125,31 @@ ] } } + }, + "rest": { + "libraryClient": "GameServerConfigsClient", + "rpcs": { + "CreateGameServerConfig": { + "methods": [ + "CreateGameServerConfig" + ] + }, + "DeleteGameServerConfig": { + "methods": [ + "DeleteGameServerConfig" + ] + }, + "GetGameServerConfig": { + "methods": [ + "GetGameServerConfig" + ] + }, + "ListGameServerConfigs": { + "methods": [ + "ListGameServerConfigs" + ] + } + } } } }, @@ -134,6 +204,56 @@ ] } } + }, + "rest": { + "libraryClient": "GameServerDeploymentsClient", + "rpcs": { + "CreateGameServerDeployment": { + "methods": [ + "CreateGameServerDeployment" + ] + }, + "DeleteGameServerDeployment": { + "methods": [ + "DeleteGameServerDeployment" + ] + }, + "FetchDeploymentState": { + "methods": [ + "FetchDeploymentState" + ] + }, + "GetGameServerDeployment": { + "methods": [ + "GetGameServerDeployment" + ] + }, + "GetGameServerDeploymentRollout": { + "methods": [ + "GetGameServerDeploymentRollout" + ] + }, + "ListGameServerDeployments": { + "methods": [ + "ListGameServerDeployments" + ] + }, + "PreviewGameServerDeploymentRollout": { + "methods": [ + "PreviewGameServerDeploymentRollout" + ] + }, + "UpdateGameServerDeployment": { + "methods": [ + "UpdateGameServerDeployment" + ] + }, + "UpdateGameServerDeploymentRollout": { + "methods": [ + "UpdateGameServerDeploymentRollout" + ] + } + } } } }, @@ -173,6 +293,41 @@ ] } } + }, + "rest": { + "libraryClient": "RealmsClient", + "rpcs": { + "CreateRealm": { + "methods": [ + "CreateRealm" + ] + }, + "DeleteRealm": { + "methods": [ + "DeleteRealm" + ] + }, + "GetRealm": { + "methods": [ + "GetRealm" + ] + }, + "ListRealms": { + "methods": [ + "ListRealms" + ] + }, + "PreviewRealmUpdate": { + "methods": [ + "PreviewRealmUpdate" + ] + }, + "UpdateRealm": { + "methods": [ + "UpdateRealm" + ] + } + } } } } diff --git a/gaming/apiv1/realms_client.go b/gaming/apiv1/realms_client.go index 2d4596296412..40bc81f45c53 100644 --- a/gaming/apiv1/realms_client.go +++ b/gaming/apiv1/realms_client.go @@ -17,9 +17,12 @@ package gaming import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,14 +30,17 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -103,6 +109,44 @@ func defaultRealmsCallOptions() *RealmsCallOptions { } } +func defaultRealmsRESTCallOptions() *RealmsCallOptions { + return &RealmsCallOptions{ + ListRealms: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetRealm: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateRealm: []gax.CallOption{}, + DeleteRealm: []gax.CallOption{}, + UpdateRealm: []gax.CallOption{}, + PreviewRealmUpdate: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + } +} + // internalRealmsClient is an interface that defines the methods available from Game Services API. type internalRealmsClient interface { Close() error @@ -306,6 +350,90 @@ func (c *realmsGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type realmsRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing RealmsClient + CallOptions **RealmsCallOptions +} + +// NewRealmsRESTClient creates a new realms service rest client. +// +// A realm is a grouping of game server clusters that are considered +// interchangeable. +func NewRealmsRESTClient(ctx context.Context, opts ...option.ClientOption) (*RealmsClient, error) { + clientOpts := append(defaultRealmsRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRealmsRESTCallOptions() + c := &realmsRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &RealmsClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRealmsRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://gameservices.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://gameservices.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://gameservices.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *realmsRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *realmsRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *realmsRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *realmsGRPCClient) ListRealms(ctx context.Context, req *gamingpb.ListRealmsRequest, opts ...gax.CallOption) *RealmIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -467,9 +595,449 @@ func (c *realmsGRPCClient) PreviewRealmUpdate(ctx context.Context, req *gamingpb return resp, nil } +// ListRealms lists realms in a given project and location. +func (c *realmsRESTClient) ListRealms(ctx context.Context, req *gamingpb.ListRealmsRequest, opts ...gax.CallOption) *RealmIterator { + it := &RealmIterator{} + req = proto.Clone(req).(*gamingpb.ListRealmsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*gamingpb.Realm, string, error) { + resp := &gamingpb.ListRealmsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/realms", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetRealms(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetRealm gets details of a single realm. +func (c *realmsRESTClient) GetRealm(ctx context.Context, req *gamingpb.GetRealmRequest, opts ...gax.CallOption) (*gamingpb.Realm, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetRealm[0:len((*c.CallOptions).GetRealm):len((*c.CallOptions).GetRealm)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &gamingpb.Realm{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateRealm creates a new realm in a given project and location. +func (c *realmsRESTClient) CreateRealm(ctx context.Context, req *gamingpb.CreateRealmRequest, opts ...gax.CallOption) (*CreateRealmOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetRealm() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/realms", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("realmId", fmt.Sprintf("%v", req.GetRealmId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateRealmOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteRealm deletes a single realm. +func (c *realmsRESTClient) DeleteRealm(ctx context.Context, req *gamingpb.DeleteRealmRequest, opts ...gax.CallOption) (*DeleteRealmOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteRealmOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateRealm patches a single realm. +func (c *realmsRESTClient) UpdateRealm(ctx context.Context, req *gamingpb.UpdateRealmRequest, opts ...gax.CallOption) (*UpdateRealmOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetRealm() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetRealm().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "realm.name", url.QueryEscape(req.GetRealm().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateRealmOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// PreviewRealmUpdate previews patches to a single realm. +func (c *realmsRESTClient) PreviewRealmUpdate(ctx context.Context, req *gamingpb.PreviewRealmUpdateRequest, opts ...gax.CallOption) (*gamingpb.PreviewRealmUpdateResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetRealm() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:previewUpdate", req.GetRealm().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPreviewTime() != nil { + previewTime, err := protojson.Marshal(req.GetPreviewTime()) + if err != nil { + return nil, err + } + params.Add("previewTime", string(previewTime)) + } + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "realm.name", url.QueryEscape(req.GetRealm().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).PreviewRealmUpdate[0:len((*c.CallOptions).PreviewRealmUpdate):len((*c.CallOptions).PreviewRealmUpdate)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &gamingpb.PreviewRealmUpdateResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + // CreateRealmOperation manages a long-running operation from CreateRealm. type CreateRealmOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateRealmOperation returns a new CreateRealmOperation from a given name. @@ -480,10 +1048,21 @@ func (c *realmsGRPCClient) CreateRealmOperation(name string) *CreateRealmOperati } } +// CreateRealmOperation returns a new CreateRealmOperation from a given name. +// The name must be that of a previously created CreateRealmOperation, possibly from a different process. +func (c *realmsRESTClient) CreateRealmOperation(name string) *CreateRealmOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateRealmOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateRealmOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*gamingpb.Realm, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp gamingpb.Realm if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -501,6 +1080,7 @@ func (op *CreateRealmOperation) Wait(ctx context.Context, opts ...gax.CallOption // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateRealmOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*gamingpb.Realm, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp gamingpb.Realm if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -538,7 +1118,8 @@ func (op *CreateRealmOperation) Name() string { // DeleteRealmOperation manages a long-running operation from DeleteRealm. type DeleteRealmOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteRealmOperation returns a new DeleteRealmOperation from a given name. @@ -549,10 +1130,21 @@ func (c *realmsGRPCClient) DeleteRealmOperation(name string) *DeleteRealmOperati } } +// DeleteRealmOperation returns a new DeleteRealmOperation from a given name. +// The name must be that of a previously created DeleteRealmOperation, possibly from a different process. +func (c *realmsRESTClient) DeleteRealmOperation(name string) *DeleteRealmOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteRealmOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteRealmOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -566,6 +1158,7 @@ func (op *DeleteRealmOperation) Wait(ctx context.Context, opts ...gax.CallOption // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteRealmOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -596,7 +1189,8 @@ func (op *DeleteRealmOperation) Name() string { // UpdateRealmOperation manages a long-running operation from UpdateRealm. type UpdateRealmOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateRealmOperation returns a new UpdateRealmOperation from a given name. @@ -607,10 +1201,21 @@ func (c *realmsGRPCClient) UpdateRealmOperation(name string) *UpdateRealmOperati } } +// UpdateRealmOperation returns a new UpdateRealmOperation from a given name. +// The name must be that of a previously created UpdateRealmOperation, possibly from a different process. +func (c *realmsRESTClient) UpdateRealmOperation(name string) *UpdateRealmOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateRealmOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateRealmOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*gamingpb.Realm, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp gamingpb.Realm if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -628,6 +1233,7 @@ func (op *UpdateRealmOperation) Wait(ctx context.Context, opts ...gax.CallOption // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateRealmOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*gamingpb.Realm, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp gamingpb.Realm if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/gaming/apiv1/realms_client_example_test.go b/gaming/apiv1/realms_client_example_test.go index 2cf727811a2e..61cc55b215f2 100644 --- a/gaming/apiv1/realms_client_example_test.go +++ b/gaming/apiv1/realms_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewRealmsClient() { _ = c } +func ExampleNewRealmsRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := gaming.NewRealmsRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleRealmsClient_ListRealms() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/gaming/apiv1beta/game_server_clusters_client.go b/gaming/apiv1beta/game_server_clusters_client.go index 47cbd6af0de7..3f91e02b45f8 100644 --- a/gaming/apiv1beta/game_server_clusters_client.go +++ b/gaming/apiv1beta/game_server_clusters_client.go @@ -718,6 +718,7 @@ func (c *gameServerClustersRESTClient) ListGameServerClusters(ctx context.Contex baseUrl.Path += fmt.Sprintf("/v1beta/%v/gameServerClusters", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -797,6 +798,11 @@ func (c *gameServerClustersRESTClient) GetGameServerCluster(ctx context.Context, } baseUrl.Path += fmt.Sprintf("/v1beta/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -858,6 +864,7 @@ func (c *gameServerClustersRESTClient) CreateGameServerCluster(ctx context.Conte baseUrl.Path += fmt.Sprintf("/v1beta/%v/gameServerClusters", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("gameServerClusterId", fmt.Sprintf("%v", req.GetGameServerClusterId())) baseUrl.RawQuery = params.Encode() @@ -928,6 +935,7 @@ func (c *gameServerClustersRESTClient) PreviewCreateGameServerCluster(ctx contex baseUrl.Path += fmt.Sprintf("/v1beta/%v/gameServerClusters:previewCreate", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("gameServerClusterId", fmt.Sprintf("%v", req.GetGameServerClusterId())) if req.GetPreviewTime() != nil { previewTime, err := protojson.Marshal(req.GetPreviewTime()) @@ -992,6 +1000,11 @@ func (c *gameServerClustersRESTClient) DeleteGameServerCluster(ctx context.Conte } baseUrl.Path += fmt.Sprintf("/v1beta/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1050,6 +1063,7 @@ func (c *gameServerClustersRESTClient) PreviewDeleteGameServerCluster(ctx contex baseUrl.Path += fmt.Sprintf("/v1beta/%v:previewDelete", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPreviewTime() != nil { previewTime, err := protojson.Marshal(req.GetPreviewTime()) if err != nil { @@ -1121,6 +1135,7 @@ func (c *gameServerClustersRESTClient) UpdateGameServerCluster(ctx context.Conte baseUrl.Path += fmt.Sprintf("/v1beta/%v", req.GetGameServerCluster().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -1196,6 +1211,7 @@ func (c *gameServerClustersRESTClient) PreviewUpdateGameServerCluster(ctx contex baseUrl.Path += fmt.Sprintf("/v1beta/%v:previewUpdate", req.GetGameServerCluster().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPreviewTime() != nil { previewTime, err := protojson.Marshal(req.GetPreviewTime()) if err != nil { diff --git a/gaming/apiv1beta/game_server_configs_client.go b/gaming/apiv1beta/game_server_configs_client.go index 426285a35c0b..0bc9e4a47358 100644 --- a/gaming/apiv1beta/game_server_configs_client.go +++ b/gaming/apiv1beta/game_server_configs_client.go @@ -529,6 +529,7 @@ func (c *gameServerConfigsRESTClient) ListGameServerConfigs(ctx context.Context, baseUrl.Path += fmt.Sprintf("/v1beta/%v/configs", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -608,6 +609,11 @@ func (c *gameServerConfigsRESTClient) GetGameServerConfig(ctx context.Context, r } baseUrl.Path += fmt.Sprintf("/v1beta/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -671,6 +677,7 @@ func (c *gameServerConfigsRESTClient) CreateGameServerConfig(ctx context.Context baseUrl.Path += fmt.Sprintf("/v1beta/%v/configs", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("configId", fmt.Sprintf("%v", req.GetConfigId())) baseUrl.RawQuery = params.Encode() @@ -733,6 +740,11 @@ func (c *gameServerConfigsRESTClient) DeleteGameServerConfig(ctx context.Context } baseUrl.Path += fmt.Sprintf("/v1beta/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) diff --git a/gaming/apiv1beta/game_server_deployments_client.go b/gaming/apiv1beta/game_server_deployments_client.go index 303f0c0af464..849254eccd9a 100644 --- a/gaming/apiv1beta/game_server_deployments_client.go +++ b/gaming/apiv1beta/game_server_deployments_client.go @@ -765,6 +765,7 @@ func (c *gameServerDeploymentsRESTClient) ListGameServerDeployments(ctx context. baseUrl.Path += fmt.Sprintf("/v1beta/%v/gameServerDeployments", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -844,6 +845,11 @@ func (c *gameServerDeploymentsRESTClient) GetGameServerDeployment(ctx context.Co } baseUrl.Path += fmt.Sprintf("/v1beta/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -905,6 +911,7 @@ func (c *gameServerDeploymentsRESTClient) CreateGameServerDeployment(ctx context baseUrl.Path += fmt.Sprintf("/v1beta/%v/gameServerDeployments", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("deploymentId", fmt.Sprintf("%v", req.GetDeploymentId())) baseUrl.RawQuery = params.Encode() @@ -966,6 +973,11 @@ func (c *gameServerDeploymentsRESTClient) DeleteGameServerDeployment(ctx context } baseUrl.Path += fmt.Sprintf("/v1beta/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1031,6 +1043,7 @@ func (c *gameServerDeploymentsRESTClient) UpdateGameServerDeployment(ctx context baseUrl.Path += fmt.Sprintf("/v1beta/%v", req.GetGameServerDeployment().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -1098,6 +1111,11 @@ func (c *gameServerDeploymentsRESTClient) GetGameServerDeploymentRollout(ctx con } baseUrl.Path += fmt.Sprintf("/v1beta/%v/rollout", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1164,6 +1182,7 @@ func (c *gameServerDeploymentsRESTClient) UpdateGameServerDeploymentRollout(ctx baseUrl.Path += fmt.Sprintf("/v1beta/%v/rollout", req.GetRollout().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -1240,6 +1259,7 @@ func (c *gameServerDeploymentsRESTClient) PreviewGameServerDeploymentRollout(ctx baseUrl.Path += fmt.Sprintf("/v1beta/%v/rollout:preview", req.GetRollout().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPreviewTime() != nil { previewTime, err := protojson.Marshal(req.GetPreviewTime()) if err != nil { @@ -1318,6 +1338,11 @@ func (c *gameServerDeploymentsRESTClient) FetchDeploymentState(ctx context.Conte } baseUrl.Path += fmt.Sprintf("/v1beta/%v:fetchDeploymentState", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) diff --git a/gaming/apiv1beta/gamingpb/common.pb.go b/gaming/apiv1beta/gamingpb/common.pb.go index 1c091ab2fb50..e0c7145081d3 100644 --- a/gaming/apiv1beta/gamingpb/common.pb.go +++ b/gaming/apiv1beta/gamingpb/common.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/gaming/v1beta/common.proto package gamingpb diff --git a/gaming/apiv1beta/gamingpb/game_server_clusters.pb.go b/gaming/apiv1beta/gamingpb/game_server_clusters.pb.go index 17caa4f8d37a..88a92c825e41 100644 --- a/gaming/apiv1beta/gamingpb/game_server_clusters.pb.go +++ b/gaming/apiv1beta/gamingpb/game_server_clusters.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/gaming/v1beta/game_server_clusters.proto package gamingpb @@ -825,7 +825,6 @@ type GameServerClusterConnectionInfo struct { // The location of the Kubernetes cluster. // // Types that are assignable to ClusterReference: - // // *GameServerClusterConnectionInfo_GkeClusterReference ClusterReference isGameServerClusterConnectionInfo_ClusterReference `protobuf_oneof:"cluster_reference"` // Namespace designated on the game server cluster where the Agones game @@ -907,10 +906,9 @@ type GkeClusterReference struct { // The full or partial name of a GKE cluster, using one of the following // forms: - // - `projects/{project}/locations/{location}/clusters/{cluster}` - // - `locations/{location}/clusters/{cluster}` - // - `{cluster}` - // + // * `projects/{project}/locations/{location}/clusters/{cluster}` + // * `locations/{location}/clusters/{cluster}` + // * `{cluster}` // If project and location are not specified, the project and location of the // GameServerCluster resource are used to generate the full name of the // GKE cluster. diff --git a/gaming/apiv1beta/gamingpb/game_server_clusters_service.pb.go b/gaming/apiv1beta/gamingpb/game_server_clusters_service.pb.go index 9f4587aed7f7..3c81878262b4 100644 --- a/gaming/apiv1beta/gamingpb/game_server_clusters_service.pb.go +++ b/gaming/apiv1beta/gamingpb/game_server_clusters_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/gaming/v1beta/game_server_clusters_service.proto package gamingpb diff --git a/gaming/apiv1beta/gamingpb/game_server_configs.pb.go b/gaming/apiv1beta/gamingpb/game_server_configs.pb.go index b21f33ff4cbb..0f3d971cdf2a 100644 --- a/gaming/apiv1beta/gamingpb/game_server_configs.pb.go +++ b/gaming/apiv1beta/gamingpb/game_server_configs.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/gaming/v1beta/game_server_configs.proto package gamingpb diff --git a/gaming/apiv1beta/gamingpb/game_server_configs_service.pb.go b/gaming/apiv1beta/gamingpb/game_server_configs_service.pb.go index a6aa146e908d..0a180dbdd806 100644 --- a/gaming/apiv1beta/gamingpb/game_server_configs_service.pb.go +++ b/gaming/apiv1beta/gamingpb/game_server_configs_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/gaming/v1beta/game_server_configs_service.proto package gamingpb diff --git a/gaming/apiv1beta/gamingpb/game_server_deployments.pb.go b/gaming/apiv1beta/gamingpb/game_server_deployments.pb.go index fd73b27bfbbe..2405c277e591 100644 --- a/gaming/apiv1beta/gamingpb/game_server_deployments.pb.go +++ b/gaming/apiv1beta/gamingpb/game_server_deployments.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/gaming/v1beta/game_server_deployments.proto package gamingpb @@ -770,13 +770,11 @@ type GameServerConfigOverride struct { // Selector chooses the game server config targets. // // Types that are assignable to Selector: - // // *GameServerConfigOverride_RealmsSelector Selector isGameServerConfigOverride_Selector `protobuf_oneof:"selector"` // Selects the game server config and how it should be applied. // // Types that are assignable to Change: - // // *GameServerConfigOverride_ConfigVersion Change isGameServerConfigOverride_Change `protobuf_oneof:"change"` } diff --git a/gaming/apiv1beta/gamingpb/game_server_deployments_service.pb.go b/gaming/apiv1beta/gamingpb/game_server_deployments_service.pb.go index 1407dbb42b2f..43fdc588eeb0 100644 --- a/gaming/apiv1beta/gamingpb/game_server_deployments_service.pb.go +++ b/gaming/apiv1beta/gamingpb/game_server_deployments_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/gaming/v1beta/game_server_deployments_service.proto package gamingpb diff --git a/gaming/apiv1beta/gamingpb/realms.pb.go b/gaming/apiv1beta/gamingpb/realms.pb.go index 35187e0b8b41..0a5df03b4d1d 100644 --- a/gaming/apiv1beta/gamingpb/realms.pb.go +++ b/gaming/apiv1beta/gamingpb/realms.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/gaming/v1beta/realms.proto package gamingpb diff --git a/gaming/apiv1beta/gamingpb/realms_service.pb.go b/gaming/apiv1beta/gamingpb/realms_service.pb.go index f33a50789f77..d9637518957c 100644 --- a/gaming/apiv1beta/gamingpb/realms_service.pb.go +++ b/gaming/apiv1beta/gamingpb/realms_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/gaming/v1beta/realms_service.proto package gamingpb diff --git a/gaming/apiv1beta/realms_client.go b/gaming/apiv1beta/realms_client.go index 1f8a143594ba..969b28105e31 100644 --- a/gaming/apiv1beta/realms_client.go +++ b/gaming/apiv1beta/realms_client.go @@ -617,6 +617,7 @@ func (c *realmsRESTClient) ListRealms(ctx context.Context, req *gamingpb.ListRea baseUrl.Path += fmt.Sprintf("/v1beta/%v/realms", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -696,6 +697,11 @@ func (c *realmsRESTClient) GetRealm(ctx context.Context, req *gamingpb.GetRealmR } baseUrl.Path += fmt.Sprintf("/v1beta/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -757,6 +763,7 @@ func (c *realmsRESTClient) CreateRealm(ctx context.Context, req *gamingpb.Create baseUrl.Path += fmt.Sprintf("/v1beta/%v/realms", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("realmId", fmt.Sprintf("%v", req.GetRealmId())) baseUrl.RawQuery = params.Encode() @@ -818,6 +825,11 @@ func (c *realmsRESTClient) DeleteRealm(ctx context.Context, req *gamingpb.Delete } baseUrl.Path += fmt.Sprintf("/v1beta/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -883,6 +895,7 @@ func (c *realmsRESTClient) UpdateRealm(ctx context.Context, req *gamingpb.Update baseUrl.Path += fmt.Sprintf("/v1beta/%v", req.GetRealm().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -958,6 +971,7 @@ func (c *realmsRESTClient) PreviewRealmUpdate(ctx context.Context, req *gamingpb baseUrl.Path += fmt.Sprintf("/v1beta/%v:previewUpdate", req.GetRealm().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPreviewTime() != nil { previewTime, err := protojson.Marshal(req.GetPreviewTime()) if err != nil { diff --git a/gkebackup/apiv1/backup_forgke_client.go b/gkebackup/apiv1/backup_forgke_client.go index 250fcbf635c0..121790ec0165 100644 --- a/gkebackup/apiv1/backup_forgke_client.go +++ b/gkebackup/apiv1/backup_forgke_client.go @@ -17,9 +17,12 @@ package gkebackup import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,14 +30,17 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -229,6 +235,143 @@ func defaultBackupForGKECallOptions() *BackupForGKECallOptions { } } +func defaultBackupForGKERESTCallOptions() *BackupForGKECallOptions { + return &BackupForGKECallOptions{ + CreateBackupPlan: []gax.CallOption{}, + ListBackupPlans: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetBackupPlan: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UpdateBackupPlan: []gax.CallOption{}, + DeleteBackupPlan: []gax.CallOption{}, + CreateBackup: []gax.CallOption{}, + ListBackups: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetBackup: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UpdateBackup: []gax.CallOption{}, + DeleteBackup: []gax.CallOption{}, + ListVolumeBackups: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetVolumeBackup: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateRestorePlan: []gax.CallOption{}, + ListRestorePlans: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetRestorePlan: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UpdateRestorePlan: []gax.CallOption{}, + DeleteRestorePlan: []gax.CallOption{}, + CreateRestore: []gax.CallOption{}, + ListRestores: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetRestore: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UpdateRestore: []gax.CallOption{}, + DeleteRestore: []gax.CallOption{}, + ListVolumeRestores: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetVolumeRestore: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + } +} + // internalBackupForGKEClient is an interface that defines the methods available from Backup for GKE API. type internalBackupForGKEClient interface { Close() error @@ -603,6 +746,90 @@ func (c *backupForGKEGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type backupForGKERESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing BackupForGKEClient + CallOptions **BackupForGKECallOptions +} + +// NewBackupForGKERESTClient creates a new backup forgke rest client. +// +// BackupForGKE allows Kubernetes administrators to configure, execute, and +// manage backup and restore operations for their GKE clusters. +func NewBackupForGKERESTClient(ctx context.Context, opts ...option.ClientOption) (*BackupForGKEClient, error) { + clientOpts := append(defaultBackupForGKERESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultBackupForGKERESTCallOptions() + c := &backupForGKERESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &BackupForGKEClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultBackupForGKERESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://gkebackup.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://gkebackup.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://gkebackup.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *backupForGKERESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *backupForGKERESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *backupForGKERESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *backupForGKEGRPCClient) CreateBackupPlan(ctx context.Context, req *gkebackuppb.CreateBackupPlanRequest, opts ...gax.CallOption) (*CreateBackupPlanOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 300000*time.Millisecond) @@ -1293,102 +1520,1894 @@ func (c *backupForGKEGRPCClient) GetVolumeRestore(ctx context.Context, req *gkeb return resp, nil } -// CreateBackupOperation manages a long-running operation from CreateBackup. -type CreateBackupOperation struct { - lro *longrunning.Operation -} - -// CreateBackupOperation returns a new CreateBackupOperation from a given name. -// The name must be that of a previously created CreateBackupOperation, possibly from a different process. -func (c *backupForGKEGRPCClient) CreateBackupOperation(name string) *CreateBackupOperation { - return &CreateBackupOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} - -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *CreateBackupOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*gkebackuppb.Backup, error) { - var resp gkebackuppb.Backup - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { +// CreateBackupPlan creates a new BackupPlan in a given location. +func (c *backupForGKERESTClient) CreateBackupPlan(ctx context.Context, req *gkebackuppb.CreateBackupPlanRequest, opts ...gax.CallOption) (*CreateBackupPlanOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetBackupPlan() + jsonReq, err := m.Marshal(body) + if err != nil { return nil, err } - return &resp, nil -} -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *CreateBackupOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*gkebackuppb.Backup, error) { - var resp gkebackuppb.Backup - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - if !op.Done() { - return nil, nil - } - return &resp, nil -} + baseUrl.Path += fmt.Sprintf("/v1/%v/backupPlans", req.GetParent()) -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *CreateBackupOperation) Metadata() (*gkebackuppb.OperationMetadata, error) { - var meta gkebackuppb.OperationMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { - return nil, err - } - return &meta, nil -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("backupPlanId", fmt.Sprintf("%v", req.GetBackupPlanId())) -// Done reports whether the long-running operation has completed. -func (op *CreateBackupOperation) Done() bool { - return op.lro.Done() -} + baseUrl.RawQuery = params.Encode() -// 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 *CreateBackupOperation) Name() string { - return op.lro.Name() -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) -// CreateBackupPlanOperation manages a long-running operation from CreateBackupPlan. -type CreateBackupPlanOperation struct { - lro *longrunning.Operation -} + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers -// CreateBackupPlanOperation returns a new CreateBackupPlanOperation from a given name. -// The name must be that of a previously created CreateBackupPlanOperation, possibly from a different process. -func (c *backupForGKEGRPCClient) CreateBackupPlanOperation(name string) *CreateBackupPlanOperation { - return &CreateBackupPlanOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *CreateBackupPlanOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*gkebackuppb.BackupPlan, error) { - var resp gkebackuppb.BackupPlan - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { - return nil, err + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e } - return &resp, nil + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateBackupPlanOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil } -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// ListBackupPlans lists BackupPlans in a given location. +func (c *backupForGKERESTClient) ListBackupPlans(ctx context.Context, req *gkebackuppb.ListBackupPlansRequest, opts ...gax.CallOption) *BackupPlanIterator { + it := &BackupPlanIterator{} + req = proto.Clone(req).(*gkebackuppb.ListBackupPlansRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*gkebackuppb.BackupPlan, string, error) { + resp := &gkebackuppb.ListBackupPlansResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/backupPlans", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetBackupPlans(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetBackupPlan retrieve the details of a single BackupPlan. +func (c *backupForGKERESTClient) GetBackupPlan(ctx context.Context, req *gkebackuppb.GetBackupPlanRequest, opts ...gax.CallOption) (*gkebackuppb.BackupPlan, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetBackupPlan[0:len((*c.CallOptions).GetBackupPlan):len((*c.CallOptions).GetBackupPlan)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &gkebackuppb.BackupPlan{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateBackupPlan update a BackupPlan. +func (c *backupForGKERESTClient) UpdateBackupPlan(ctx context.Context, req *gkebackuppb.UpdateBackupPlanRequest, opts ...gax.CallOption) (*UpdateBackupPlanOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetBackupPlan() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetBackupPlan().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "backup_plan.name", url.QueryEscape(req.GetBackupPlan().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateBackupPlanOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteBackupPlan deletes an existing BackupPlan. +func (c *backupForGKERESTClient) DeleteBackupPlan(ctx context.Context, req *gkebackuppb.DeleteBackupPlanRequest, opts ...gax.CallOption) (*DeleteBackupPlanOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetEtag() != "" { + params.Add("etag", fmt.Sprintf("%v", req.GetEtag())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteBackupPlanOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// CreateBackup creates a Backup for the given BackupPlan. +func (c *backupForGKERESTClient) CreateBackup(ctx context.Context, req *gkebackuppb.CreateBackupRequest, opts ...gax.CallOption) (*CreateBackupOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetBackup() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/backups", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetBackupId() != "" { + params.Add("backupId", fmt.Sprintf("%v", req.GetBackupId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateBackupOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListBackups lists the Backups for a given BackupPlan. +func (c *backupForGKERESTClient) ListBackups(ctx context.Context, req *gkebackuppb.ListBackupsRequest, opts ...gax.CallOption) *BackupIterator { + it := &BackupIterator{} + req = proto.Clone(req).(*gkebackuppb.ListBackupsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*gkebackuppb.Backup, string, error) { + resp := &gkebackuppb.ListBackupsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/backups", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetBackups(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetBackup retrieve the details of a single Backup. +func (c *backupForGKERESTClient) GetBackup(ctx context.Context, req *gkebackuppb.GetBackupRequest, opts ...gax.CallOption) (*gkebackuppb.Backup, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetBackup[0:len((*c.CallOptions).GetBackup):len((*c.CallOptions).GetBackup)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &gkebackuppb.Backup{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateBackup update a Backup. +func (c *backupForGKERESTClient) UpdateBackup(ctx context.Context, req *gkebackuppb.UpdateBackupRequest, opts ...gax.CallOption) (*UpdateBackupOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetBackup() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetBackup().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "backup.name", url.QueryEscape(req.GetBackup().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateBackupOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteBackup deletes an existing Backup. +func (c *backupForGKERESTClient) DeleteBackup(ctx context.Context, req *gkebackuppb.DeleteBackupRequest, opts ...gax.CallOption) (*DeleteBackupOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetEtag() != "" { + params.Add("etag", fmt.Sprintf("%v", req.GetEtag())) + } + if req.GetForce() { + params.Add("force", fmt.Sprintf("%v", req.GetForce())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteBackupOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListVolumeBackups lists the VolumeBackups for a given Backup. +func (c *backupForGKERESTClient) ListVolumeBackups(ctx context.Context, req *gkebackuppb.ListVolumeBackupsRequest, opts ...gax.CallOption) *VolumeBackupIterator { + it := &VolumeBackupIterator{} + req = proto.Clone(req).(*gkebackuppb.ListVolumeBackupsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*gkebackuppb.VolumeBackup, string, error) { + resp := &gkebackuppb.ListVolumeBackupsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/volumeBackups", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetVolumeBackups(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetVolumeBackup retrieve the details of a single VolumeBackup. +func (c *backupForGKERESTClient) GetVolumeBackup(ctx context.Context, req *gkebackuppb.GetVolumeBackupRequest, opts ...gax.CallOption) (*gkebackuppb.VolumeBackup, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetVolumeBackup[0:len((*c.CallOptions).GetVolumeBackup):len((*c.CallOptions).GetVolumeBackup)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &gkebackuppb.VolumeBackup{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateRestorePlan creates a new RestorePlan in a given location. +func (c *backupForGKERESTClient) CreateRestorePlan(ctx context.Context, req *gkebackuppb.CreateRestorePlanRequest, opts ...gax.CallOption) (*CreateRestorePlanOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetRestorePlan() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/restorePlans", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("restorePlanId", fmt.Sprintf("%v", req.GetRestorePlanId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateRestorePlanOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListRestorePlans lists RestorePlans in a given location. +func (c *backupForGKERESTClient) ListRestorePlans(ctx context.Context, req *gkebackuppb.ListRestorePlansRequest, opts ...gax.CallOption) *RestorePlanIterator { + it := &RestorePlanIterator{} + req = proto.Clone(req).(*gkebackuppb.ListRestorePlansRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*gkebackuppb.RestorePlan, string, error) { + resp := &gkebackuppb.ListRestorePlansResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/restorePlans", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetRestorePlans(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetRestorePlan retrieve the details of a single RestorePlan. +func (c *backupForGKERESTClient) GetRestorePlan(ctx context.Context, req *gkebackuppb.GetRestorePlanRequest, opts ...gax.CallOption) (*gkebackuppb.RestorePlan, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetRestorePlan[0:len((*c.CallOptions).GetRestorePlan):len((*c.CallOptions).GetRestorePlan)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &gkebackuppb.RestorePlan{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateRestorePlan update a RestorePlan. +func (c *backupForGKERESTClient) UpdateRestorePlan(ctx context.Context, req *gkebackuppb.UpdateRestorePlanRequest, opts ...gax.CallOption) (*UpdateRestorePlanOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetRestorePlan() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetRestorePlan().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "restore_plan.name", url.QueryEscape(req.GetRestorePlan().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateRestorePlanOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteRestorePlan deletes an existing RestorePlan. +func (c *backupForGKERESTClient) DeleteRestorePlan(ctx context.Context, req *gkebackuppb.DeleteRestorePlanRequest, opts ...gax.CallOption) (*DeleteRestorePlanOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetEtag() != "" { + params.Add("etag", fmt.Sprintf("%v", req.GetEtag())) + } + if req.GetForce() { + params.Add("force", fmt.Sprintf("%v", req.GetForce())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteRestorePlanOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// CreateRestore creates a new Restore for the given RestorePlan. +func (c *backupForGKERESTClient) CreateRestore(ctx context.Context, req *gkebackuppb.CreateRestoreRequest, opts ...gax.CallOption) (*CreateRestoreOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetRestore() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/restores", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("restoreId", fmt.Sprintf("%v", req.GetRestoreId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateRestoreOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListRestores lists the Restores for a given RestorePlan. +func (c *backupForGKERESTClient) ListRestores(ctx context.Context, req *gkebackuppb.ListRestoresRequest, opts ...gax.CallOption) *RestoreIterator { + it := &RestoreIterator{} + req = proto.Clone(req).(*gkebackuppb.ListRestoresRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*gkebackuppb.Restore, string, error) { + resp := &gkebackuppb.ListRestoresResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/restores", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetRestores(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetRestore retrieves the details of a single Restore. +func (c *backupForGKERESTClient) GetRestore(ctx context.Context, req *gkebackuppb.GetRestoreRequest, opts ...gax.CallOption) (*gkebackuppb.Restore, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetRestore[0:len((*c.CallOptions).GetRestore):len((*c.CallOptions).GetRestore)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &gkebackuppb.Restore{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateRestore update a Restore. +func (c *backupForGKERESTClient) UpdateRestore(ctx context.Context, req *gkebackuppb.UpdateRestoreRequest, opts ...gax.CallOption) (*UpdateRestoreOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetRestore() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetRestore().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "restore.name", url.QueryEscape(req.GetRestore().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateRestoreOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteRestore deletes an existing Restore. +func (c *backupForGKERESTClient) DeleteRestore(ctx context.Context, req *gkebackuppb.DeleteRestoreRequest, opts ...gax.CallOption) (*DeleteRestoreOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetEtag() != "" { + params.Add("etag", fmt.Sprintf("%v", req.GetEtag())) + } + if req.GetForce() { + params.Add("force", fmt.Sprintf("%v", req.GetForce())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteRestoreOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListVolumeRestores lists the VolumeRestores for a given Restore. +func (c *backupForGKERESTClient) ListVolumeRestores(ctx context.Context, req *gkebackuppb.ListVolumeRestoresRequest, opts ...gax.CallOption) *VolumeRestoreIterator { + it := &VolumeRestoreIterator{} + req = proto.Clone(req).(*gkebackuppb.ListVolumeRestoresRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*gkebackuppb.VolumeRestore, string, error) { + resp := &gkebackuppb.ListVolumeRestoresResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/volumeRestores", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetVolumeRestores(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetVolumeRestore retrieve the details of a single VolumeRestore. +func (c *backupForGKERESTClient) GetVolumeRestore(ctx context.Context, req *gkebackuppb.GetVolumeRestoreRequest, opts ...gax.CallOption) (*gkebackuppb.VolumeRestore, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetVolumeRestore[0:len((*c.CallOptions).GetVolumeRestore):len((*c.CallOptions).GetVolumeRestore)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &gkebackuppb.VolumeRestore{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateBackupOperation manages a long-running operation from CreateBackup. +type CreateBackupOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateBackupOperation returns a new CreateBackupOperation from a given name. +// The name must be that of a previously created CreateBackupOperation, possibly from a different process. +func (c *backupForGKEGRPCClient) CreateBackupOperation(name string) *CreateBackupOperation { + return &CreateBackupOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateBackupOperation returns a new CreateBackupOperation from a given name. +// The name must be that of a previously created CreateBackupOperation, possibly from a different process. +func (c *backupForGKERESTClient) CreateBackupOperation(name string) *CreateBackupOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateBackupOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CreateBackupOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*gkebackuppb.Backup, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp gkebackuppb.Backup + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *CreateBackupOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*gkebackuppb.Backup, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp gkebackuppb.Backup + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *CreateBackupOperation) Metadata() (*gkebackuppb.OperationMetadata, error) { + var meta gkebackuppb.OperationMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *CreateBackupOperation) Done() bool { + return op.lro.Done() +} + +// 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 *CreateBackupOperation) Name() string { + return op.lro.Name() +} + +// CreateBackupPlanOperation manages a long-running operation from CreateBackupPlan. +type CreateBackupPlanOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateBackupPlanOperation returns a new CreateBackupPlanOperation from a given name. +// The name must be that of a previously created CreateBackupPlanOperation, possibly from a different process. +func (c *backupForGKEGRPCClient) CreateBackupPlanOperation(name string) *CreateBackupPlanOperation { + return &CreateBackupPlanOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateBackupPlanOperation returns a new CreateBackupPlanOperation from a given name. +// The name must be that of a previously created CreateBackupPlanOperation, possibly from a different process. +func (c *backupForGKERESTClient) CreateBackupPlanOperation(name string) *CreateBackupPlanOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateBackupPlanOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CreateBackupPlanOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*gkebackuppb.BackupPlan, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp gkebackuppb.BackupPlan + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. // // 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. @@ -1396,6 +3415,7 @@ func (op *CreateBackupPlanOperation) Wait(ctx context.Context, opts ...gax.CallO // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateBackupPlanOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*gkebackuppb.BackupPlan, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp gkebackuppb.BackupPlan if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1433,7 +3453,8 @@ func (op *CreateBackupPlanOperation) Name() string { // CreateRestoreOperation manages a long-running operation from CreateRestore. type CreateRestoreOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateRestoreOperation returns a new CreateRestoreOperation from a given name. @@ -1444,10 +3465,21 @@ func (c *backupForGKEGRPCClient) CreateRestoreOperation(name string) *CreateRest } } +// CreateRestoreOperation returns a new CreateRestoreOperation from a given name. +// The name must be that of a previously created CreateRestoreOperation, possibly from a different process. +func (c *backupForGKERESTClient) CreateRestoreOperation(name string) *CreateRestoreOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateRestoreOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateRestoreOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*gkebackuppb.Restore, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp gkebackuppb.Restore if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1465,6 +3497,7 @@ func (op *CreateRestoreOperation) Wait(ctx context.Context, opts ...gax.CallOpti // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateRestoreOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*gkebackuppb.Restore, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp gkebackuppb.Restore if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1502,7 +3535,8 @@ func (op *CreateRestoreOperation) Name() string { // CreateRestorePlanOperation manages a long-running operation from CreateRestorePlan. type CreateRestorePlanOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateRestorePlanOperation returns a new CreateRestorePlanOperation from a given name. @@ -1513,10 +3547,21 @@ func (c *backupForGKEGRPCClient) CreateRestorePlanOperation(name string) *Create } } +// CreateRestorePlanOperation returns a new CreateRestorePlanOperation from a given name. +// The name must be that of a previously created CreateRestorePlanOperation, possibly from a different process. +func (c *backupForGKERESTClient) CreateRestorePlanOperation(name string) *CreateRestorePlanOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateRestorePlanOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateRestorePlanOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*gkebackuppb.RestorePlan, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp gkebackuppb.RestorePlan if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1534,6 +3579,7 @@ func (op *CreateRestorePlanOperation) Wait(ctx context.Context, opts ...gax.Call // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateRestorePlanOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*gkebackuppb.RestorePlan, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp gkebackuppb.RestorePlan if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1571,7 +3617,8 @@ func (op *CreateRestorePlanOperation) Name() string { // DeleteBackupOperation manages a long-running operation from DeleteBackup. type DeleteBackupOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteBackupOperation returns a new DeleteBackupOperation from a given name. @@ -1582,10 +3629,21 @@ func (c *backupForGKEGRPCClient) DeleteBackupOperation(name string) *DeleteBacku } } +// DeleteBackupOperation returns a new DeleteBackupOperation from a given name. +// The name must be that of a previously created DeleteBackupOperation, possibly from a different process. +func (c *backupForGKERESTClient) DeleteBackupOperation(name string) *DeleteBackupOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteBackupOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteBackupOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -1599,6 +3657,7 @@ func (op *DeleteBackupOperation) Wait(ctx context.Context, opts ...gax.CallOptio // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteBackupOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -1629,7 +3688,8 @@ func (op *DeleteBackupOperation) Name() string { // DeleteBackupPlanOperation manages a long-running operation from DeleteBackupPlan. type DeleteBackupPlanOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteBackupPlanOperation returns a new DeleteBackupPlanOperation from a given name. @@ -1640,10 +3700,21 @@ func (c *backupForGKEGRPCClient) DeleteBackupPlanOperation(name string) *DeleteB } } +// DeleteBackupPlanOperation returns a new DeleteBackupPlanOperation from a given name. +// The name must be that of a previously created DeleteBackupPlanOperation, possibly from a different process. +func (c *backupForGKERESTClient) DeleteBackupPlanOperation(name string) *DeleteBackupPlanOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteBackupPlanOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteBackupPlanOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -1657,6 +3728,7 @@ func (op *DeleteBackupPlanOperation) Wait(ctx context.Context, opts ...gax.CallO // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteBackupPlanOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -1687,7 +3759,8 @@ func (op *DeleteBackupPlanOperation) Name() string { // DeleteRestoreOperation manages a long-running operation from DeleteRestore. type DeleteRestoreOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteRestoreOperation returns a new DeleteRestoreOperation from a given name. @@ -1698,10 +3771,21 @@ func (c *backupForGKEGRPCClient) DeleteRestoreOperation(name string) *DeleteRest } } +// DeleteRestoreOperation returns a new DeleteRestoreOperation from a given name. +// The name must be that of a previously created DeleteRestoreOperation, possibly from a different process. +func (c *backupForGKERESTClient) DeleteRestoreOperation(name string) *DeleteRestoreOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteRestoreOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteRestoreOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -1715,6 +3799,7 @@ func (op *DeleteRestoreOperation) Wait(ctx context.Context, opts ...gax.CallOpti // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteRestoreOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -1745,7 +3830,8 @@ func (op *DeleteRestoreOperation) Name() string { // DeleteRestorePlanOperation manages a long-running operation from DeleteRestorePlan. type DeleteRestorePlanOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteRestorePlanOperation returns a new DeleteRestorePlanOperation from a given name. @@ -1756,10 +3842,21 @@ func (c *backupForGKEGRPCClient) DeleteRestorePlanOperation(name string) *Delete } } +// DeleteRestorePlanOperation returns a new DeleteRestorePlanOperation from a given name. +// The name must be that of a previously created DeleteRestorePlanOperation, possibly from a different process. +func (c *backupForGKERESTClient) DeleteRestorePlanOperation(name string) *DeleteRestorePlanOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteRestorePlanOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteRestorePlanOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -1773,6 +3870,7 @@ func (op *DeleteRestorePlanOperation) Wait(ctx context.Context, opts ...gax.Call // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteRestorePlanOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -1803,7 +3901,8 @@ func (op *DeleteRestorePlanOperation) Name() string { // UpdateBackupOperation manages a long-running operation from UpdateBackup. type UpdateBackupOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateBackupOperation returns a new UpdateBackupOperation from a given name. @@ -1814,10 +3913,21 @@ func (c *backupForGKEGRPCClient) UpdateBackupOperation(name string) *UpdateBacku } } +// UpdateBackupOperation returns a new UpdateBackupOperation from a given name. +// The name must be that of a previously created UpdateBackupOperation, possibly from a different process. +func (c *backupForGKERESTClient) UpdateBackupOperation(name string) *UpdateBackupOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateBackupOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateBackupOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*gkebackuppb.Backup, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp gkebackuppb.Backup if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1835,6 +3945,7 @@ func (op *UpdateBackupOperation) Wait(ctx context.Context, opts ...gax.CallOptio // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateBackupOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*gkebackuppb.Backup, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp gkebackuppb.Backup if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1872,7 +3983,8 @@ func (op *UpdateBackupOperation) Name() string { // UpdateBackupPlanOperation manages a long-running operation from UpdateBackupPlan. type UpdateBackupPlanOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateBackupPlanOperation returns a new UpdateBackupPlanOperation from a given name. @@ -1883,10 +3995,21 @@ func (c *backupForGKEGRPCClient) UpdateBackupPlanOperation(name string) *UpdateB } } +// UpdateBackupPlanOperation returns a new UpdateBackupPlanOperation from a given name. +// The name must be that of a previously created UpdateBackupPlanOperation, possibly from a different process. +func (c *backupForGKERESTClient) UpdateBackupPlanOperation(name string) *UpdateBackupPlanOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateBackupPlanOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateBackupPlanOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*gkebackuppb.BackupPlan, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp gkebackuppb.BackupPlan if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1904,6 +4027,7 @@ func (op *UpdateBackupPlanOperation) Wait(ctx context.Context, opts ...gax.CallO // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateBackupPlanOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*gkebackuppb.BackupPlan, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp gkebackuppb.BackupPlan if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1941,7 +4065,8 @@ func (op *UpdateBackupPlanOperation) Name() string { // UpdateRestoreOperation manages a long-running operation from UpdateRestore. type UpdateRestoreOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateRestoreOperation returns a new UpdateRestoreOperation from a given name. @@ -1952,10 +4077,21 @@ func (c *backupForGKEGRPCClient) UpdateRestoreOperation(name string) *UpdateRest } } +// UpdateRestoreOperation returns a new UpdateRestoreOperation from a given name. +// The name must be that of a previously created UpdateRestoreOperation, possibly from a different process. +func (c *backupForGKERESTClient) UpdateRestoreOperation(name string) *UpdateRestoreOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateRestoreOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateRestoreOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*gkebackuppb.Restore, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp gkebackuppb.Restore if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1973,6 +4109,7 @@ func (op *UpdateRestoreOperation) Wait(ctx context.Context, opts ...gax.CallOpti // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateRestoreOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*gkebackuppb.Restore, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp gkebackuppb.Restore if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2010,7 +4147,8 @@ func (op *UpdateRestoreOperation) Name() string { // UpdateRestorePlanOperation manages a long-running operation from UpdateRestorePlan. type UpdateRestorePlanOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateRestorePlanOperation returns a new UpdateRestorePlanOperation from a given name. @@ -2021,10 +4159,21 @@ func (c *backupForGKEGRPCClient) UpdateRestorePlanOperation(name string) *Update } } +// UpdateRestorePlanOperation returns a new UpdateRestorePlanOperation from a given name. +// The name must be that of a previously created UpdateRestorePlanOperation, possibly from a different process. +func (c *backupForGKERESTClient) UpdateRestorePlanOperation(name string) *UpdateRestorePlanOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateRestorePlanOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateRestorePlanOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*gkebackuppb.RestorePlan, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp gkebackuppb.RestorePlan if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2042,6 +4191,7 @@ func (op *UpdateRestorePlanOperation) Wait(ctx context.Context, opts ...gax.Call // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateRestorePlanOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*gkebackuppb.RestorePlan, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp gkebackuppb.RestorePlan if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/gkebackup/apiv1/backup_forgke_client_example_test.go b/gkebackup/apiv1/backup_forgke_client_example_test.go index 6a0d1f98935d..7b6ed21a5b63 100644 --- a/gkebackup/apiv1/backup_forgke_client_example_test.go +++ b/gkebackup/apiv1/backup_forgke_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewBackupForGKEClient() { _ = c } +func ExampleNewBackupForGKERESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := gkebackup.NewBackupForGKERESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleBackupForGKEClient_CreateBackupPlan() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/gkebackup/apiv1/doc.go b/gkebackup/apiv1/doc.go index 7818566e9840..35651a155648 100644 --- a/gkebackup/apiv1/doc.go +++ b/gkebackup/apiv1/doc.go @@ -88,6 +88,8 @@ package gkebackup // import "cloud.google.com/go/gkebackup/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -176,3 +178,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/gkebackup/apiv1/gapic_metadata.json b/gkebackup/apiv1/gapic_metadata.json index ebed74dfe482..c2f033fa9585 100644 --- a/gkebackup/apiv1/gapic_metadata.json +++ b/gkebackup/apiv1/gapic_metadata.json @@ -131,6 +131,131 @@ ] } } + }, + "rest": { + "libraryClient": "BackupForGKEClient", + "rpcs": { + "CreateBackup": { + "methods": [ + "CreateBackup" + ] + }, + "CreateBackupPlan": { + "methods": [ + "CreateBackupPlan" + ] + }, + "CreateRestore": { + "methods": [ + "CreateRestore" + ] + }, + "CreateRestorePlan": { + "methods": [ + "CreateRestorePlan" + ] + }, + "DeleteBackup": { + "methods": [ + "DeleteBackup" + ] + }, + "DeleteBackupPlan": { + "methods": [ + "DeleteBackupPlan" + ] + }, + "DeleteRestore": { + "methods": [ + "DeleteRestore" + ] + }, + "DeleteRestorePlan": { + "methods": [ + "DeleteRestorePlan" + ] + }, + "GetBackup": { + "methods": [ + "GetBackup" + ] + }, + "GetBackupPlan": { + "methods": [ + "GetBackupPlan" + ] + }, + "GetRestore": { + "methods": [ + "GetRestore" + ] + }, + "GetRestorePlan": { + "methods": [ + "GetRestorePlan" + ] + }, + "GetVolumeBackup": { + "methods": [ + "GetVolumeBackup" + ] + }, + "GetVolumeRestore": { + "methods": [ + "GetVolumeRestore" + ] + }, + "ListBackupPlans": { + "methods": [ + "ListBackupPlans" + ] + }, + "ListBackups": { + "methods": [ + "ListBackups" + ] + }, + "ListRestorePlans": { + "methods": [ + "ListRestorePlans" + ] + }, + "ListRestores": { + "methods": [ + "ListRestores" + ] + }, + "ListVolumeBackups": { + "methods": [ + "ListVolumeBackups" + ] + }, + "ListVolumeRestores": { + "methods": [ + "ListVolumeRestores" + ] + }, + "UpdateBackup": { + "methods": [ + "UpdateBackup" + ] + }, + "UpdateBackupPlan": { + "methods": [ + "UpdateBackupPlan" + ] + }, + "UpdateRestore": { + "methods": [ + "UpdateRestore" + ] + }, + "UpdateRestorePlan": { + "methods": [ + "UpdateRestorePlan" + ] + } + } } } } diff --git a/gkebackup/apiv1/gkebackuppb/backup.pb.go b/gkebackup/apiv1/gkebackuppb/backup.pb.go index 70a8222ac3aa..acaa84dcd827 100644 --- a/gkebackup/apiv1/gkebackuppb/backup.pb.go +++ b/gkebackup/apiv1/gkebackuppb/backup.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/gkebackup/v1/backup.proto package gkebackuppb @@ -168,7 +168,6 @@ type Backup struct { // BackupPlan's [backup_scope][google.cloud.gkebackup.v1.BackupPlan.BackupConfig.backup_scope] value. // // Types that are assignable to BackupScope: - // // *Backup_AllNamespaces // *Backup_SelectedNamespaces // *Backup_SelectedApplications @@ -489,7 +488,6 @@ type Backup_ClusterMetadata struct { // Platform-specific version // // Types that are assignable to PlatformVersion: - // // *Backup_ClusterMetadata_GkeVersion // *Backup_ClusterMetadata_AnthosVersion PlatformVersion isBackup_ClusterMetadata_PlatformVersion `protobuf_oneof:"platform_version"` diff --git a/gkebackup/apiv1/gkebackuppb/backup_plan.pb.go b/gkebackup/apiv1/gkebackuppb/backup_plan.pb.go index 13333ae3df02..e250a13cff16 100644 --- a/gkebackup/apiv1/gkebackuppb/backup_plan.pb.go +++ b/gkebackup/apiv1/gkebackuppb/backup_plan.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/gkebackup/v1/backup_plan.proto package gkebackuppb @@ -384,7 +384,6 @@ type BackupPlan_BackupConfig struct { // Exactly one of the fields of backup_scope MUST be specified. // // Types that are assignable to BackupScope: - // // *BackupPlan_BackupConfig_AllNamespaces // *BackupPlan_BackupConfig_SelectedNamespaces // *BackupPlan_BackupConfig_SelectedApplications diff --git a/gkebackup/apiv1/gkebackuppb/common.pb.go b/gkebackup/apiv1/gkebackuppb/common.pb.go index 966913a7b1c5..fa65fbaafd44 100644 --- a/gkebackup/apiv1/gkebackuppb/common.pb.go +++ b/gkebackup/apiv1/gkebackuppb/common.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/gkebackup/v1/common.proto package gkebackuppb diff --git a/gkebackup/apiv1/gkebackuppb/gkebackup.pb.go b/gkebackup/apiv1/gkebackuppb/gkebackup.pb.go index ab6ff7081739..62f691faab50 100644 --- a/gkebackup/apiv1/gkebackuppb/gkebackup.pb.go +++ b/gkebackup/apiv1/gkebackuppb/gkebackup.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/gkebackup/v1/gkebackup.proto package gkebackuppb @@ -583,11 +583,11 @@ type CreateBackupRequest struct { // The client-provided short name for the Backup resource. // This name must: // - // - be between 1 and 63 characters long (inclusive) - // - consist of only lower-case ASCII letters, numbers, and dashes - // - start with a lower-case letter - // - end with a lower-case letter or number - // - be unique within the set of Backups in this BackupPlan + // - be between 1 and 63 characters long (inclusive) + // - consist of only lower-case ASCII letters, numbers, and dashes + // - start with a lower-case letter + // - end with a lower-case letter or number + // - be unique within the set of Backups in this BackupPlan BackupId string `protobuf:"bytes,3,opt,name=backup_id,json=backupId,proto3" json:"backup_id,omitempty"` } @@ -1210,11 +1210,11 @@ type CreateRestorePlanRequest struct { // Required. The client-provided short name for the RestorePlan resource. // This name must: // - // - be between 1 and 63 characters long (inclusive) - // - consist of only lower-case ASCII letters, numbers, and dashes - // - start with a lower-case letter - // - end with a lower-case letter or number - // - be unique within the set of RestorePlans in this location + // - be between 1 and 63 characters long (inclusive) + // - consist of only lower-case ASCII letters, numbers, and dashes + // - start with a lower-case letter + // - end with a lower-case letter or number + // - be unique within the set of RestorePlans in this location RestorePlanId string `protobuf:"bytes,3,opt,name=restore_plan_id,json=restorePlanId,proto3" json:"restore_plan_id,omitempty"` } @@ -1640,11 +1640,11 @@ type CreateRestoreRequest struct { // Required. The client-provided short name for the Restore resource. // This name must: // - // - be between 1 and 63 characters long (inclusive) - // - consist of only lower-case ASCII letters, numbers, and dashes - // - start with a lower-case letter - // - end with a lower-case letter or number - // - be unique within the set of Restores in this RestorePlan. + // - be between 1 and 63 characters long (inclusive) + // - consist of only lower-case ASCII letters, numbers, and dashes + // - start with a lower-case letter + // - end with a lower-case letter or number + // - be unique within the set of Restores in this RestorePlan. RestoreId string `protobuf:"bytes,3,opt,name=restore_id,json=restoreId,proto3" json:"restore_id,omitempty"` } diff --git a/gkebackup/apiv1/gkebackuppb/restore.pb.go b/gkebackup/apiv1/gkebackuppb/restore.pb.go index f863d4a2873e..e67108ab937b 100644 --- a/gkebackup/apiv1/gkebackuppb/restore.pb.go +++ b/gkebackup/apiv1/gkebackuppb/restore.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/gkebackup/v1/restore.proto package gkebackuppb @@ -534,7 +534,6 @@ type RestoreConfig struct { // resources will be restored. // // Types that are assignable to NamespacedResourceRestoreScope: - // // *RestoreConfig_AllNamespaces // *RestoreConfig_SelectedNamespaces // *RestoreConfig_SelectedApplications diff --git a/gkebackup/apiv1/gkebackuppb/restore_plan.pb.go b/gkebackup/apiv1/gkebackuppb/restore_plan.pb.go index da89ba54c9cc..c539944fdfef 100644 --- a/gkebackup/apiv1/gkebackuppb/restore_plan.pb.go +++ b/gkebackup/apiv1/gkebackuppb/restore_plan.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/gkebackup/v1/restore_plan.proto package gkebackuppb diff --git a/gkebackup/apiv1/gkebackuppb/volume.pb.go b/gkebackup/apiv1/gkebackuppb/volume.pb.go index 776f5c22d6ac..3328091df23c 100644 --- a/gkebackup/apiv1/gkebackuppb/volume.pb.go +++ b/gkebackup/apiv1/gkebackuppb/volume.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/gkebackup/v1/volume.proto package gkebackuppb diff --git a/gkeconnect/gateway/apiv1beta1/gateway_client.go b/gkeconnect/gateway/apiv1beta1/gateway_client.go index 67d85cefee9f..944daa4f3210 100644 --- a/gkeconnect/gateway/apiv1beta1/gateway_client.go +++ b/gkeconnect/gateway/apiv1beta1/gateway_client.go @@ -396,6 +396,7 @@ func (c *restClient) GetResource(ctx context.Context, req *httpbodypb.HttpBody, baseUrl.Path += fmt.Sprintf("/v1beta1/**") params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetContentType() != "" { params.Add("contentType", fmt.Sprintf("%v", req.GetContentType())) } @@ -457,6 +458,7 @@ func (c *restClient) PostResource(ctx context.Context, req *httpbodypb.HttpBody, baseUrl.Path += fmt.Sprintf("/v1beta1/**") params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetContentType() != "" { params.Add("contentType", fmt.Sprintf("%v", req.GetContentType())) } @@ -518,6 +520,7 @@ func (c *restClient) DeleteResource(ctx context.Context, req *httpbodypb.HttpBod baseUrl.Path += fmt.Sprintf("/v1beta1/**") params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetContentType() != "" { params.Add("contentType", fmt.Sprintf("%v", req.GetContentType())) } @@ -579,6 +582,7 @@ func (c *restClient) PutResource(ctx context.Context, req *httpbodypb.HttpBody, baseUrl.Path += fmt.Sprintf("/v1beta1/**") params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetContentType() != "" { params.Add("contentType", fmt.Sprintf("%v", req.GetContentType())) } @@ -640,6 +644,7 @@ func (c *restClient) PatchResource(ctx context.Context, req *httpbodypb.HttpBody baseUrl.Path += fmt.Sprintf("/v1beta1/**") params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetContentType() != "" { params.Add("contentType", fmt.Sprintf("%v", req.GetContentType())) } diff --git a/gkeconnect/gateway/apiv1beta1/gatewaypb/gateway.pb.go b/gkeconnect/gateway/apiv1beta1/gatewaypb/gateway.pb.go index 54045ebdd645..c23e092301ce 100644 --- a/gkeconnect/gateway/apiv1beta1/gatewaypb/gateway.pb.go +++ b/gkeconnect/gateway/apiv1beta1/gatewaypb/gateway.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/gkeconnect/gateway/v1beta1/gateway.proto package gatewaypb diff --git a/gkehub/apiv1beta1/gke_hub_membership_client.go b/gkehub/apiv1beta1/gke_hub_membership_client.go index fa504ec57c05..4fe7233958a5 100644 --- a/gkehub/apiv1beta1/gke_hub_membership_client.go +++ b/gkehub/apiv1beta1/gke_hub_membership_client.go @@ -1119,6 +1119,7 @@ func (c *gkeHubMembershipRESTClient) ListMemberships(ctx context.Context, req *g baseUrl.Path += fmt.Sprintf("/v1beta1/%v/memberships", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1198,6 +1199,11 @@ func (c *gkeHubMembershipRESTClient) GetMembership(ctx context.Context, req *gke } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1263,6 +1269,7 @@ func (c *gkeHubMembershipRESTClient) CreateMembership(ctx context.Context, req * baseUrl.Path += fmt.Sprintf("/v1beta1/%v/memberships", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("membershipId", fmt.Sprintf("%v", req.GetMembershipId())) if req.GetRequestId() != "" { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) @@ -1332,6 +1339,7 @@ func (c *gkeHubMembershipRESTClient) DeleteMembership(ctx context.Context, req * baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetRequestId() != "" { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -1403,6 +1411,7 @@ func (c *gkeHubMembershipRESTClient) UpdateMembership(ctx context.Context, req * baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetRequestId() != "" { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -1477,6 +1486,7 @@ func (c *gkeHubMembershipRESTClient) GenerateConnectManifest(ctx context.Context baseUrl.Path += fmt.Sprintf("/v1beta1/%v:generateConnectManifest", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetConnectAgent().GetName() != "" { params.Add("connectAgent.name", fmt.Sprintf("%v", req.GetConnectAgent().GetName())) } @@ -1556,6 +1566,7 @@ func (c *gkeHubMembershipRESTClient) ValidateExclusivity(ctx context.Context, re baseUrl.Path += fmt.Sprintf("/v1beta1/%v/memberships:validateExclusivity", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetCrManifest() != "" { params.Add("crManifest", fmt.Sprintf("%v", req.GetCrManifest())) } @@ -1628,6 +1639,7 @@ func (c *gkeHubMembershipRESTClient) GenerateExclusivityManifest(ctx context.Con baseUrl.Path += fmt.Sprintf("/v1beta1/%v:generateExclusivityManifest", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetCrManifest() != "" { params.Add("crManifest", fmt.Sprintf("%v", req.GetCrManifest())) } @@ -1690,6 +1702,11 @@ func (c *gkeHubMembershipRESTClient) GetLocation(ctx context.Context, req *locat } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1757,6 +1774,7 @@ func (c *gkeHubMembershipRESTClient) ListLocations(ctx context.Context, req *loc baseUrl.Path += fmt.Sprintf("/v1beta1/%v/locations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1835,6 +1853,7 @@ func (c *gkeHubMembershipRESTClient) GetIamPolicy(ctx context.Context, req *iamp baseUrl.Path += fmt.Sprintf("/v1beta1/%v:getIamPolicy", req.GetResource()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetOptions().GetRequestedPolicyVersion() != 0 { params.Add("options.requestedPolicyVersion", fmt.Sprintf("%v", req.GetOptions().GetRequestedPolicyVersion())) } @@ -1904,6 +1923,11 @@ func (c *gkeHubMembershipRESTClient) SetIamPolicy(ctx context.Context, req *iamp } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:setIamPolicy", req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) @@ -1969,6 +1993,11 @@ func (c *gkeHubMembershipRESTClient) TestIamPermissions(ctx context.Context, req } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:testIamPermissions", req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) @@ -2028,6 +2057,11 @@ func (c *gkeHubMembershipRESTClient) CancelOperation(ctx context.Context, req *l } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:cancel", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2063,6 +2097,11 @@ func (c *gkeHubMembershipRESTClient) DeleteOperation(ctx context.Context, req *l } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2098,6 +2137,11 @@ func (c *gkeHubMembershipRESTClient) GetOperation(ctx context.Context, req *long } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2165,6 +2209,7 @@ func (c *gkeHubMembershipRESTClient) ListOperations(ctx context.Context, req *lo baseUrl.Path += fmt.Sprintf("/v1beta1/%v/operations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/gkehub/apiv1beta1/gkehubpb/membership.pb.go b/gkehub/apiv1beta1/gkehubpb/membership.pb.go index bbe92b196d44..d472740e4301 100644 --- a/gkehub/apiv1beta1/gkehubpb/membership.pb.go +++ b/gkehub/apiv1beta1/gkehubpb/membership.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/gkehub/v1beta1/membership.proto package gkehubpb @@ -241,9 +241,9 @@ type Membership struct { // // `membership_id` must be a valid RFC 1123 compliant DNS label: // - // 1. At most 63 characters in length - // 2. It must consist of lower case alphanumeric characters or `-` - // 3. It must start and end with an alphanumeric character + // 1. At most 63 characters in length + // 2. It must consist of lower case alphanumeric characters or `-` + // 3. It must start and end with an alphanumeric character // // Which can be expressed as the regex: `[a-z0-9]([-a-z0-9]*[a-z0-9])?`, // with a maximum length of 63 characters. @@ -256,7 +256,6 @@ type Membership struct { // Type of resource represented by this Membership // // Types that are assignable to Type: - // // *Membership_Endpoint Type isMembership_Type `protobuf_oneof:"type"` // Output only. State of the Membership resource. @@ -444,7 +443,6 @@ type MembershipEndpoint struct { // Cluster information of the registered cluster. // // Types that are assignable to Type: - // // *MembershipEndpoint_GkeCluster // *MembershipEndpoint_OnPremCluster // *MembershipEndpoint_MultiCloudCluster @@ -456,11 +454,11 @@ type MembershipEndpoint struct { // Optional. The in-cluster Kubernetes Resources that should be applied for a correctly // registered cluster, in the steady state. These resources: // - // - Ensure that the cluster is exclusively registered to one and only one + // * Ensure that the cluster is exclusively registered to one and only one // Hub Membership. - // - Propagate Workload Pool Information available in the Membership + // * Propagate Workload Pool Information available in the Membership // Authority field. - // - Ensure proper initial configuration of default Hub Features. + // * Ensure proper initial configuration of default Hub Features. KubernetesResource *KubernetesResource `protobuf:"bytes,6,opt,name=kubernetes_resource,json=kubernetesResource,proto3" json:"kubernetes_resource,omitempty"` } @@ -835,7 +833,7 @@ type GkeCluster struct { // Immutable. Self-link of the GCP resource for the GKE cluster. For example: // - // //container.googleapis.com/projects/my-project/locations/us-west1-a/clusters/my-cluster + // //container.googleapis.com/projects/my-project/locations/us-west1-a/clusters/my-cluster // // Zonal clusters are also supported. ResourceLink string `protobuf:"bytes,1,opt,name=resource_link,json=resourceLink,proto3" json:"resource_link,omitempty"` @@ -898,8 +896,8 @@ type OnPremCluster struct { // Immutable. Self-link of the GCP resource for the GKE On-Prem cluster. For example: // - // //gkeonprem.googleapis.com/projects/my-project/locations/us-west1-a/vmwareClusters/my-cluster - // //gkeonprem.googleapis.com/projects/my-project/locations/us-west1-a/bareMetalClusters/my-cluster + // //gkeonprem.googleapis.com/projects/my-project/locations/us-west1-a/vmwareClusters/my-cluster + // //gkeonprem.googleapis.com/projects/my-project/locations/us-west1-a/bareMetalClusters/my-cluster ResourceLink string `protobuf:"bytes,1,opt,name=resource_link,json=resourceLink,proto3" json:"resource_link,omitempty"` // Output only. If cluster_missing is set then it denotes that // API(gkeonprem.googleapis.com) resource for this GKE On-Prem cluster no @@ -980,8 +978,8 @@ type MultiCloudCluster struct { // Immutable. Self-link of the GCP resource for the GKE Multi-Cloud cluster. For // example: // - // //gkemulticloud.googleapis.com/projects/my-project/locations/us-west1-a/awsClusters/my-cluster - // //gkemulticloud.googleapis.com/projects/my-project/locations/us-west1-a/azureClusters/my-cluster + // //gkemulticloud.googleapis.com/projects/my-project/locations/us-west1-a/awsClusters/my-cluster + // //gkemulticloud.googleapis.com/projects/my-project/locations/us-west1-a/azureClusters/my-cluster ResourceLink string `protobuf:"bytes,1,opt,name=resource_link,json=resourceLink,proto3" json:"resource_link,omitempty"` // Output only. If cluster_missing is set then it denotes that // API(gkemulticloud.googleapis.com) resource for this GKE Multi-Cloud cluster @@ -1435,19 +1433,19 @@ type ListMembershipsRequest struct { // // - Name is `bar` in project `foo-proj` and location `global`: // - // name = "projects/foo-proj/locations/global/membership/bar" + // name = "projects/foo-proj/locations/global/membership/bar" // // - Memberships that have a label called `foo`: // - // labels.foo:* + // labels.foo:* // // - Memberships that have a label called `foo` whose value is `bar`: // - // labels.foo = bar + // labels.foo = bar // // - Memberships in the CREATING state: // - // state = CREATING + // state = CREATING Filter string `protobuf:"bytes,4,opt,name=filter,proto3" json:"filter,omitempty"` // Optional. One or more fields to compare and use to sort the output. // See https://google.aip.dev/132#ordering. @@ -1652,9 +1650,9 @@ type CreateMembershipRequest struct { // Required. Client chosen ID for the membership. `membership_id` must be a valid RFC // 1123 compliant DNS label: // - // 1. At most 63 characters in length - // 2. It must consist of lower case alphanumeric characters or `-` - // 3. It must start and end with an alphanumeric character + // 1. At most 63 characters in length + // 2. It must consist of lower case alphanumeric characters or `-` + // 3. It must start and end with an alphanumeric character // // Which can be expressed as the regex: `[a-z0-9]([-a-z0-9]*[a-z0-9])?`, // with a maximum length of 63 characters. @@ -2330,10 +2328,10 @@ type ValidateExclusivityResponse struct { // The validation result. // - // - `OK` means that exclusivity is validated, assuming the manifest produced - // by GenerateExclusivityManifest is successfully applied. - // - `ALREADY_EXISTS` means that the Membership CRD is already owned by - // another Hub. See `status.message` for more information. + // * `OK` means that exclusivity is validated, assuming the manifest produced + // by GenerateExclusivityManifest is successfully applied. + // * `ALREADY_EXISTS` means that the Membership CRD is already owned by + // another Hub. See `status.message` for more information. Status *status.Status `protobuf:"bytes,1,opt,name=status,proto3" json:"status,omitempty"` } diff --git a/gkemulticloud/apiv1/aws_clusters_client.go b/gkemulticloud/apiv1/aws_clusters_client.go index fd7f2aefcd07..1a4aaa6d4125 100644 --- a/gkemulticloud/apiv1/aws_clusters_client.go +++ b/gkemulticloud/apiv1/aws_clusters_client.go @@ -17,9 +17,12 @@ package gkemulticloud import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,14 +30,17 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -145,6 +151,77 @@ func defaultAwsClustersCallOptions() *AwsClustersCallOptions { } } +func defaultAwsClustersRESTCallOptions() *AwsClustersCallOptions { + return &AwsClustersCallOptions{ + CreateAwsCluster: []gax.CallOption{}, + UpdateAwsCluster: []gax.CallOption{}, + GetAwsCluster: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListAwsClusters: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeleteAwsCluster: []gax.CallOption{}, + GenerateAwsAccessToken: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateAwsNodePool: []gax.CallOption{}, + UpdateAwsNodePool: []gax.CallOption{}, + GetAwsNodePool: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListAwsNodePools: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeleteAwsNodePool: []gax.CallOption{}, + GetAwsServerConfig: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + } +} + // internalAwsClustersClient is an interface that defines the methods available from Anthos Multi-Cloud API. type internalAwsClustersClient interface { Close() error @@ -427,6 +504,90 @@ func (c *awsClustersGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type awsClustersRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing AwsClustersClient + CallOptions **AwsClustersCallOptions +} + +// NewAwsClustersRESTClient creates a new aws clusters rest client. +// +// The AwsClusters API provides a single centrally managed service +// to create and manage Anthos clusters that run on AWS infrastructure. +func NewAwsClustersRESTClient(ctx context.Context, opts ...option.ClientOption) (*AwsClustersClient, error) { + clientOpts := append(defaultAwsClustersRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultAwsClustersRESTCallOptions() + c := &awsClustersRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &AwsClustersClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultAwsClustersRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://gkemulticloud.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://gkemulticloud.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://gkemulticloud.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *awsClustersRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *awsClustersRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *awsClustersRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *awsClustersGRPCClient) CreateAwsCluster(ctx context.Context, req *gkemulticloudpb.CreateAwsClusterRequest, opts ...gax.CallOption) (*CreateAwsClusterOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) @@ -749,150 +910,1025 @@ func (c *awsClustersGRPCClient) GetAwsServerConfig(ctx context.Context, req *gke return resp, nil } -// CreateAwsClusterOperation manages a long-running operation from CreateAwsCluster. -type CreateAwsClusterOperation struct { - lro *longrunning.Operation -} - -// CreateAwsClusterOperation returns a new CreateAwsClusterOperation from a given name. -// The name must be that of a previously created CreateAwsClusterOperation, possibly from a different process. -func (c *awsClustersGRPCClient) CreateAwsClusterOperation(name string) *CreateAwsClusterOperation { - return &CreateAwsClusterOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} - -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// CreateAwsCluster creates a new AwsCluster resource on a given GCP project and region. // -// See documentation of Poll for error-handling information. -func (op *CreateAwsClusterOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*gkemulticloudpb.AwsCluster, error) { - var resp gkemulticloudpb.AwsCluster - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { +// If successful, the response contains a newly created +// Operation resource that can be +// described to track the status of the operation. +func (c *awsClustersRESTClient) CreateAwsCluster(ctx context.Context, req *gkemulticloudpb.CreateAwsClusterRequest, opts ...gax.CallOption) (*CreateAwsClusterOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetAwsCluster() + jsonReq, err := m.Marshal(body) + if err != nil { return nil, err } - return &resp, nil -} -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *CreateAwsClusterOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*gkemulticloudpb.AwsCluster, error) { - var resp gkemulticloudpb.AwsCluster - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - if !op.Done() { - return nil, nil - } - return &resp, nil -} + baseUrl.Path += fmt.Sprintf("/v1/%v/awsClusters", req.GetParent()) -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *CreateAwsClusterOperation) Metadata() (*gkemulticloudpb.OperationMetadata, error) { - var meta gkemulticloudpb.OperationMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { - return nil, err + params := url.Values{} + params.Add("awsClusterId", fmt.Sprintf("%v", req.GetAwsClusterId())) + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) } - return &meta, nil -} -// Done reports whether the long-running operation has completed. -func (op *CreateAwsClusterOperation) Done() bool { - return op.lro.Done() -} + baseUrl.RawQuery = params.Encode() -// 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 *CreateAwsClusterOperation) Name() string { - return op.lro.Name() -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) -// CreateAwsNodePoolOperation manages a long-running operation from CreateAwsNodePool. -type CreateAwsNodePoolOperation struct { - lro *longrunning.Operation -} + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers -// CreateAwsNodePoolOperation returns a new CreateAwsNodePoolOperation from a given name. -// The name must be that of a previously created CreateAwsNodePoolOperation, possibly from a different process. -func (c *awsClustersGRPCClient) CreateAwsNodePoolOperation(name string) *CreateAwsNodePoolOperation { - return &CreateAwsNodePoolOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *CreateAwsNodePoolOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*gkemulticloudpb.AwsNodePool, error) { - var resp gkemulticloudpb.AwsNodePool - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { - return nil, err + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e } - return &resp, nil + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateAwsClusterOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil } -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *CreateAwsNodePoolOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*gkemulticloudpb.AwsNodePool, error) { - var resp gkemulticloudpb.AwsNodePool - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { +// UpdateAwsCluster updates an AwsCluster. +func (c *awsClustersRESTClient) UpdateAwsCluster(ctx context.Context, req *gkemulticloudpb.UpdateAwsClusterRequest, opts ...gax.CallOption) (*UpdateAwsClusterOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetAwsCluster() + jsonReq, err := m.Marshal(body) + if err != nil { return nil, err } - if !op.Done() { - return nil, nil - } - return &resp, nil -} -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *CreateAwsNodePoolOperation) Metadata() (*gkemulticloudpb.OperationMetadata, error) { - var meta gkemulticloudpb.OperationMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - return &meta, nil -} + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetAwsCluster().GetName()) -// Done reports whether the long-running operation has completed. -func (op *CreateAwsNodePoolOperation) Done() bool { - return op.lro.Done() -} + params := url.Values{} + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } -// 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 *CreateAwsNodePoolOperation) Name() string { - return op.lro.Name() -} + baseUrl.RawQuery = params.Encode() -// DeleteAwsClusterOperation manages a long-running operation from DeleteAwsCluster. -type DeleteAwsClusterOperation struct { - lro *longrunning.Operation -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "aws_cluster.name", url.QueryEscape(req.GetAwsCluster().GetName()))) -// DeleteAwsClusterOperation returns a new DeleteAwsClusterOperation from a given name. + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateAwsClusterOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetAwsCluster describes a specific AwsCluster resource. +func (c *awsClustersRESTClient) GetAwsCluster(ctx context.Context, req *gkemulticloudpb.GetAwsClusterRequest, opts ...gax.CallOption) (*gkemulticloudpb.AwsCluster, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetAwsCluster[0:len((*c.CallOptions).GetAwsCluster):len((*c.CallOptions).GetAwsCluster)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &gkemulticloudpb.AwsCluster{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListAwsClusters lists all AwsCluster resources on a given Google Cloud project and +// region. +func (c *awsClustersRESTClient) ListAwsClusters(ctx context.Context, req *gkemulticloudpb.ListAwsClustersRequest, opts ...gax.CallOption) *AwsClusterIterator { + it := &AwsClusterIterator{} + req = proto.Clone(req).(*gkemulticloudpb.ListAwsClustersRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*gkemulticloudpb.AwsCluster, string, error) { + resp := &gkemulticloudpb.ListAwsClustersResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/awsClusters", req.GetParent()) + + params := url.Values{} + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetAwsClusters(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// DeleteAwsCluster deletes a specific AwsCluster resource. +// +// Fails if the cluster has one or more associated AwsNodePool +// resources. +// +// If successful, the response contains a newly created +// Operation resource that can be +// described to track the status of the operation. +func (c *awsClustersRESTClient) DeleteAwsCluster(ctx context.Context, req *gkemulticloudpb.DeleteAwsClusterRequest, opts ...gax.CallOption) (*DeleteAwsClusterOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + if req.GetAllowMissing() { + params.Add("allowMissing", fmt.Sprintf("%v", req.GetAllowMissing())) + } + if req.GetEtag() != "" { + params.Add("etag", fmt.Sprintf("%v", req.GetEtag())) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteAwsClusterOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GenerateAwsAccessToken generates a short-lived access token to authenticate to a given +// AwsCluster resource. +func (c *awsClustersRESTClient) GenerateAwsAccessToken(ctx context.Context, req *gkemulticloudpb.GenerateAwsAccessTokenRequest, opts ...gax.CallOption) (*gkemulticloudpb.GenerateAwsAccessTokenResponse, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:generateAwsAccessToken", req.GetAwsCluster()) + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "aws_cluster", url.QueryEscape(req.GetAwsCluster()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GenerateAwsAccessToken[0:len((*c.CallOptions).GenerateAwsAccessToken):len((*c.CallOptions).GenerateAwsAccessToken)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &gkemulticloudpb.GenerateAwsAccessTokenResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateAwsNodePool creates a new AwsNodePool, attached to a given AwsCluster. +// +// If successful, the response contains a newly created +// Operation resource that can be +// described to track the status of the operation. +func (c *awsClustersRESTClient) CreateAwsNodePool(ctx context.Context, req *gkemulticloudpb.CreateAwsNodePoolRequest, opts ...gax.CallOption) (*CreateAwsNodePoolOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetAwsNodePool() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/awsNodePools", req.GetParent()) + + params := url.Values{} + params.Add("awsNodePoolId", fmt.Sprintf("%v", req.GetAwsNodePoolId())) + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateAwsNodePoolOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateAwsNodePool updates an AwsNodePool. +func (c *awsClustersRESTClient) UpdateAwsNodePool(ctx context.Context, req *gkemulticloudpb.UpdateAwsNodePoolRequest, opts ...gax.CallOption) (*UpdateAwsNodePoolOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetAwsNodePool() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetAwsNodePool().GetName()) + + params := url.Values{} + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "aws_node_pool.name", url.QueryEscape(req.GetAwsNodePool().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateAwsNodePoolOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetAwsNodePool describes a specific AwsNodePool resource. +func (c *awsClustersRESTClient) GetAwsNodePool(ctx context.Context, req *gkemulticloudpb.GetAwsNodePoolRequest, opts ...gax.CallOption) (*gkemulticloudpb.AwsNodePool, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetAwsNodePool[0:len((*c.CallOptions).GetAwsNodePool):len((*c.CallOptions).GetAwsNodePool)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &gkemulticloudpb.AwsNodePool{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListAwsNodePools lists all AwsNodePool resources on a given AwsCluster. +func (c *awsClustersRESTClient) ListAwsNodePools(ctx context.Context, req *gkemulticloudpb.ListAwsNodePoolsRequest, opts ...gax.CallOption) *AwsNodePoolIterator { + it := &AwsNodePoolIterator{} + req = proto.Clone(req).(*gkemulticloudpb.ListAwsNodePoolsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*gkemulticloudpb.AwsNodePool, string, error) { + resp := &gkemulticloudpb.ListAwsNodePoolsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/awsNodePools", req.GetParent()) + + params := url.Values{} + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetAwsNodePools(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// DeleteAwsNodePool deletes a specific AwsNodePool resource. +// +// If successful, the response contains a newly created +// Operation resource that can be +// described to track the status of the operation. +func (c *awsClustersRESTClient) DeleteAwsNodePool(ctx context.Context, req *gkemulticloudpb.DeleteAwsNodePoolRequest, opts ...gax.CallOption) (*DeleteAwsNodePoolOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + if req.GetAllowMissing() { + params.Add("allowMissing", fmt.Sprintf("%v", req.GetAllowMissing())) + } + if req.GetEtag() != "" { + params.Add("etag", fmt.Sprintf("%v", req.GetEtag())) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteAwsNodePoolOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetAwsServerConfig returns information, such as supported AWS regions and Kubernetes +// versions, on a given Google Cloud location. +func (c *awsClustersRESTClient) GetAwsServerConfig(ctx context.Context, req *gkemulticloudpb.GetAwsServerConfigRequest, opts ...gax.CallOption) (*gkemulticloudpb.AwsServerConfig, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetAwsServerConfig[0:len((*c.CallOptions).GetAwsServerConfig):len((*c.CallOptions).GetAwsServerConfig)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &gkemulticloudpb.AwsServerConfig{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateAwsClusterOperation manages a long-running operation from CreateAwsCluster. +type CreateAwsClusterOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateAwsClusterOperation returns a new CreateAwsClusterOperation from a given name. +// The name must be that of a previously created CreateAwsClusterOperation, possibly from a different process. +func (c *awsClustersGRPCClient) CreateAwsClusterOperation(name string) *CreateAwsClusterOperation { + return &CreateAwsClusterOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateAwsClusterOperation returns a new CreateAwsClusterOperation from a given name. +// The name must be that of a previously created CreateAwsClusterOperation, possibly from a different process. +func (c *awsClustersRESTClient) CreateAwsClusterOperation(name string) *CreateAwsClusterOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateAwsClusterOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CreateAwsClusterOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*gkemulticloudpb.AwsCluster, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp gkemulticloudpb.AwsCluster + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *CreateAwsClusterOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*gkemulticloudpb.AwsCluster, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp gkemulticloudpb.AwsCluster + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *CreateAwsClusterOperation) Metadata() (*gkemulticloudpb.OperationMetadata, error) { + var meta gkemulticloudpb.OperationMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *CreateAwsClusterOperation) Done() bool { + return op.lro.Done() +} + +// 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 *CreateAwsClusterOperation) Name() string { + return op.lro.Name() +} + +// CreateAwsNodePoolOperation manages a long-running operation from CreateAwsNodePool. +type CreateAwsNodePoolOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateAwsNodePoolOperation returns a new CreateAwsNodePoolOperation from a given name. +// The name must be that of a previously created CreateAwsNodePoolOperation, possibly from a different process. +func (c *awsClustersGRPCClient) CreateAwsNodePoolOperation(name string) *CreateAwsNodePoolOperation { + return &CreateAwsNodePoolOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateAwsNodePoolOperation returns a new CreateAwsNodePoolOperation from a given name. +// The name must be that of a previously created CreateAwsNodePoolOperation, possibly from a different process. +func (c *awsClustersRESTClient) CreateAwsNodePoolOperation(name string) *CreateAwsNodePoolOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateAwsNodePoolOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CreateAwsNodePoolOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*gkemulticloudpb.AwsNodePool, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp gkemulticloudpb.AwsNodePool + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *CreateAwsNodePoolOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*gkemulticloudpb.AwsNodePool, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp gkemulticloudpb.AwsNodePool + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *CreateAwsNodePoolOperation) Metadata() (*gkemulticloudpb.OperationMetadata, error) { + var meta gkemulticloudpb.OperationMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *CreateAwsNodePoolOperation) Done() bool { + return op.lro.Done() +} + +// 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 *CreateAwsNodePoolOperation) Name() string { + return op.lro.Name() +} + +// DeleteAwsClusterOperation manages a long-running operation from DeleteAwsCluster. +type DeleteAwsClusterOperation struct { + lro *longrunning.Operation + pollPath string +} + +// DeleteAwsClusterOperation returns a new DeleteAwsClusterOperation from a given name. // The name must be that of a previously created DeleteAwsClusterOperation, possibly from a different process. func (c *awsClustersGRPCClient) DeleteAwsClusterOperation(name string) *DeleteAwsClusterOperation { return &DeleteAwsClusterOperation{ @@ -900,10 +1936,21 @@ func (c *awsClustersGRPCClient) DeleteAwsClusterOperation(name string) *DeleteAw } } +// DeleteAwsClusterOperation returns a new DeleteAwsClusterOperation from a given name. +// The name must be that of a previously created DeleteAwsClusterOperation, possibly from a different process. +func (c *awsClustersRESTClient) DeleteAwsClusterOperation(name string) *DeleteAwsClusterOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteAwsClusterOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteAwsClusterOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -917,6 +1964,7 @@ func (op *DeleteAwsClusterOperation) Wait(ctx context.Context, opts ...gax.CallO // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteAwsClusterOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -947,7 +1995,8 @@ func (op *DeleteAwsClusterOperation) Name() string { // DeleteAwsNodePoolOperation manages a long-running operation from DeleteAwsNodePool. type DeleteAwsNodePoolOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteAwsNodePoolOperation returns a new DeleteAwsNodePoolOperation from a given name. @@ -958,10 +2007,21 @@ func (c *awsClustersGRPCClient) DeleteAwsNodePoolOperation(name string) *DeleteA } } +// DeleteAwsNodePoolOperation returns a new DeleteAwsNodePoolOperation from a given name. +// The name must be that of a previously created DeleteAwsNodePoolOperation, possibly from a different process. +func (c *awsClustersRESTClient) DeleteAwsNodePoolOperation(name string) *DeleteAwsNodePoolOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteAwsNodePoolOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteAwsNodePoolOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -975,6 +2035,7 @@ func (op *DeleteAwsNodePoolOperation) Wait(ctx context.Context, opts ...gax.Call // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteAwsNodePoolOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -1005,7 +2066,8 @@ func (op *DeleteAwsNodePoolOperation) Name() string { // UpdateAwsClusterOperation manages a long-running operation from UpdateAwsCluster. type UpdateAwsClusterOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateAwsClusterOperation returns a new UpdateAwsClusterOperation from a given name. @@ -1016,10 +2078,21 @@ func (c *awsClustersGRPCClient) UpdateAwsClusterOperation(name string) *UpdateAw } } +// UpdateAwsClusterOperation returns a new UpdateAwsClusterOperation from a given name. +// The name must be that of a previously created UpdateAwsClusterOperation, possibly from a different process. +func (c *awsClustersRESTClient) UpdateAwsClusterOperation(name string) *UpdateAwsClusterOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateAwsClusterOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateAwsClusterOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*gkemulticloudpb.AwsCluster, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp gkemulticloudpb.AwsCluster if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1037,6 +2110,7 @@ func (op *UpdateAwsClusterOperation) Wait(ctx context.Context, opts ...gax.CallO // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateAwsClusterOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*gkemulticloudpb.AwsCluster, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp gkemulticloudpb.AwsCluster if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1074,7 +2148,8 @@ func (op *UpdateAwsClusterOperation) Name() string { // UpdateAwsNodePoolOperation manages a long-running operation from UpdateAwsNodePool. type UpdateAwsNodePoolOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateAwsNodePoolOperation returns a new UpdateAwsNodePoolOperation from a given name. @@ -1085,10 +2160,21 @@ func (c *awsClustersGRPCClient) UpdateAwsNodePoolOperation(name string) *UpdateA } } +// UpdateAwsNodePoolOperation returns a new UpdateAwsNodePoolOperation from a given name. +// The name must be that of a previously created UpdateAwsNodePoolOperation, possibly from a different process. +func (c *awsClustersRESTClient) UpdateAwsNodePoolOperation(name string) *UpdateAwsNodePoolOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateAwsNodePoolOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateAwsNodePoolOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*gkemulticloudpb.AwsNodePool, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp gkemulticloudpb.AwsNodePool if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1106,6 +2192,7 @@ func (op *UpdateAwsNodePoolOperation) Wait(ctx context.Context, opts ...gax.Call // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateAwsNodePoolOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*gkemulticloudpb.AwsNodePool, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp gkemulticloudpb.AwsNodePool if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/gkemulticloud/apiv1/aws_clusters_client_example_test.go b/gkemulticloud/apiv1/aws_clusters_client_example_test.go index 10203a5fb428..39b52e8fe5f9 100644 --- a/gkemulticloud/apiv1/aws_clusters_client_example_test.go +++ b/gkemulticloud/apiv1/aws_clusters_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewAwsClustersClient() { _ = c } +func ExampleNewAwsClustersRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := gkemulticloud.NewAwsClustersRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleAwsClustersClient_CreateAwsCluster() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/gkemulticloud/apiv1/azure_clusters_client.go b/gkemulticloud/apiv1/azure_clusters_client.go index db7c18e666dd..33e5efc067eb 100644 --- a/gkemulticloud/apiv1/azure_clusters_client.go +++ b/gkemulticloud/apiv1/azure_clusters_client.go @@ -17,9 +17,12 @@ package gkemulticloud import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,14 +30,17 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -173,6 +179,99 @@ func defaultAzureClustersCallOptions() *AzureClustersCallOptions { } } +func defaultAzureClustersRESTCallOptions() *AzureClustersCallOptions { + return &AzureClustersCallOptions{ + CreateAzureClient: []gax.CallOption{}, + GetAzureClient: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListAzureClients: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeleteAzureClient: []gax.CallOption{}, + CreateAzureCluster: []gax.CallOption{}, + UpdateAzureCluster: []gax.CallOption{}, + GetAzureCluster: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListAzureClusters: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeleteAzureCluster: []gax.CallOption{}, + GenerateAzureAccessToken: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateAzureNodePool: []gax.CallOption{}, + UpdateAzureNodePool: []gax.CallOption{}, + GetAzureNodePool: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListAzureNodePools: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeleteAzureNodePool: []gax.CallOption{}, + GetAzureServerConfig: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + } +} + // internalAzureClustersClient is an interface that defines the methods available from Anthos Multi-Cloud API. type internalAzureClustersClient interface { Close() error @@ -510,6 +609,90 @@ func (c *azureClustersGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type azureClustersRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing AzureClustersClient + CallOptions **AzureClustersCallOptions +} + +// NewAzureClustersRESTClient creates a new azure clusters rest client. +// +// The AzureClusters API provides a single centrally managed service +// to create and manage Anthos clusters that run on Azure infrastructure. +func NewAzureClustersRESTClient(ctx context.Context, opts ...option.ClientOption) (*AzureClustersClient, error) { + clientOpts := append(defaultAzureClustersRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultAzureClustersRESTCallOptions() + c := &azureClustersRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &AzureClustersClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultAzureClustersRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://gkemulticloud.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://gkemulticloud.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://gkemulticloud.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *azureClustersRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *azureClustersRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *azureClustersRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *azureClustersGRPCClient) CreateAzureClient(ctx context.Context, req *gkemulticloudpb.CreateAzureClientRequest, opts ...gax.CallOption) (*CreateAzureClientOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) @@ -947,128 +1130,1298 @@ func (c *azureClustersGRPCClient) GetAzureServerConfig(ctx context.Context, req return resp, nil } -// CreateAzureClientOperation manages a long-running operation from CreateAzureClient. -type CreateAzureClientOperation struct { - lro *longrunning.Operation -} - -// CreateAzureClientOperation returns a new CreateAzureClientOperation from a given name. -// The name must be that of a previously created CreateAzureClientOperation, possibly from a different process. -func (c *azureClustersGRPCClient) CreateAzureClientOperation(name string) *CreateAzureClientOperation { - return &CreateAzureClientOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} - -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// CreateAzureClient creates a new AzureClient resource on a given Google Cloud project +// and region. // -// See documentation of Poll for error-handling information. -func (op *CreateAzureClientOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*gkemulticloudpb.AzureClient, error) { - var resp gkemulticloudpb.AzureClient - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { +// AzureClient resources hold client authentication +// information needed by the Anthos Multicloud API to manage Azure resources +// on your Azure subscription on your behalf. +// +// If successful, the response contains a newly created +// Operation resource that can be +// described to track the status of the operation. +func (c *azureClustersRESTClient) CreateAzureClient(ctx context.Context, req *gkemulticloudpb.CreateAzureClientRequest, opts ...gax.CallOption) (*CreateAzureClientOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetAzureClient() + jsonReq, err := m.Marshal(body) + if err != nil { return nil, err } - return &resp, nil -} -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *CreateAzureClientOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*gkemulticloudpb.AzureClient, error) { - var resp gkemulticloudpb.AzureClient - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - if !op.Done() { - return nil, nil - } - return &resp, nil -} + baseUrl.Path += fmt.Sprintf("/v1/%v/azureClients", req.GetParent()) -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *CreateAzureClientOperation) Metadata() (*gkemulticloudpb.OperationMetadata, error) { - var meta gkemulticloudpb.OperationMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { - return nil, err + params := url.Values{} + params.Add("azureClientId", fmt.Sprintf("%v", req.GetAzureClientId())) + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) } - return &meta, nil -} -// Done reports whether the long-running operation has completed. -func (op *CreateAzureClientOperation) Done() bool { - return op.lro.Done() -} + baseUrl.RawQuery = params.Encode() -// 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 *CreateAzureClientOperation) Name() string { - return op.lro.Name() -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) -// CreateAzureClusterOperation manages a long-running operation from CreateAzureCluster. -type CreateAzureClusterOperation struct { - lro *longrunning.Operation -} + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers -// CreateAzureClusterOperation returns a new CreateAzureClusterOperation from a given name. -// The name must be that of a previously created CreateAzureClusterOperation, possibly from a different process. -func (c *azureClustersGRPCClient) CreateAzureClusterOperation(name string) *CreateAzureClusterOperation { - return &CreateAzureClusterOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *CreateAzureClusterOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*gkemulticloudpb.AzureCluster, error) { - var resp gkemulticloudpb.AzureCluster - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { - return nil, err - } - return &resp, nil -} + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *CreateAzureClusterOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*gkemulticloudpb.AzureCluster, error) { - var resp gkemulticloudpb.AzureCluster - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { - return nil, err - } - if !op.Done() { - return nil, nil + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e } - return &resp, nil + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateAzureClientOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil } -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *CreateAzureClusterOperation) Metadata() (*gkemulticloudpb.OperationMetadata, error) { - var meta gkemulticloudpb.OperationMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { +// GetAzureClient describes a specific AzureClient resource. +func (c *azureClustersRESTClient) GetAzureClient(ctx context.Context, req *gkemulticloudpb.GetAzureClientRequest, opts ...gax.CallOption) (*gkemulticloudpb.AzureClient, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetAzureClient[0:len((*c.CallOptions).GetAzureClient):len((*c.CallOptions).GetAzureClient)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &gkemulticloudpb.AzureClient{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListAzureClients lists all AzureClient resources on a given Google Cloud project and +// region. +func (c *azureClustersRESTClient) ListAzureClients(ctx context.Context, req *gkemulticloudpb.ListAzureClientsRequest, opts ...gax.CallOption) *AzureClientIterator { + it := &AzureClientIterator{} + req = proto.Clone(req).(*gkemulticloudpb.ListAzureClientsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*gkemulticloudpb.AzureClient, string, error) { + resp := &gkemulticloudpb.ListAzureClientsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/azureClients", req.GetParent()) + + params := url.Values{} + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetAzureClients(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// DeleteAzureClient deletes a specific AzureClient resource. +// +// If the client is used by one or more clusters, deletion will +// fail and a FAILED_PRECONDITION error will be returned. +// +// If successful, the response contains a newly created +// Operation resource that can be +// described to track the status of the operation. +func (c *azureClustersRESTClient) DeleteAzureClient(ctx context.Context, req *gkemulticloudpb.DeleteAzureClientRequest, opts ...gax.CallOption) (*DeleteAzureClientOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + if req.GetAllowMissing() { + params.Add("allowMissing", fmt.Sprintf("%v", req.GetAllowMissing())) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteAzureClientOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// CreateAzureCluster creates a new AzureCluster resource on a given GCP project and region. +// +// If successful, the response contains a newly created +// Operation resource that can be +// described to track the status of the operation. +func (c *azureClustersRESTClient) CreateAzureCluster(ctx context.Context, req *gkemulticloudpb.CreateAzureClusterRequest, opts ...gax.CallOption) (*CreateAzureClusterOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetAzureCluster() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/azureClusters", req.GetParent()) + + params := url.Values{} + params.Add("azureClusterId", fmt.Sprintf("%v", req.GetAzureClusterId())) + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateAzureClusterOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateAzureCluster updates an AzureCluster. +func (c *azureClustersRESTClient) UpdateAzureCluster(ctx context.Context, req *gkemulticloudpb.UpdateAzureClusterRequest, opts ...gax.CallOption) (*UpdateAzureClusterOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetAzureCluster() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetAzureCluster().GetName()) + + params := url.Values{} + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "azure_cluster.name", url.QueryEscape(req.GetAzureCluster().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateAzureClusterOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetAzureCluster describes a specific AzureCluster resource. +func (c *azureClustersRESTClient) GetAzureCluster(ctx context.Context, req *gkemulticloudpb.GetAzureClusterRequest, opts ...gax.CallOption) (*gkemulticloudpb.AzureCluster, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetAzureCluster[0:len((*c.CallOptions).GetAzureCluster):len((*c.CallOptions).GetAzureCluster)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &gkemulticloudpb.AzureCluster{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListAzureClusters lists all AzureCluster resources on a given Google Cloud project and +// region. +func (c *azureClustersRESTClient) ListAzureClusters(ctx context.Context, req *gkemulticloudpb.ListAzureClustersRequest, opts ...gax.CallOption) *AzureClusterIterator { + it := &AzureClusterIterator{} + req = proto.Clone(req).(*gkemulticloudpb.ListAzureClustersRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*gkemulticloudpb.AzureCluster, string, error) { + resp := &gkemulticloudpb.ListAzureClustersResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/azureClusters", req.GetParent()) + + params := url.Values{} + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetAzureClusters(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// DeleteAzureCluster deletes a specific AzureCluster resource. +// +// Fails if the cluster has one or more associated AzureNodePool +// resources. +// +// If successful, the response contains a newly created +// Operation resource that can be +// described to track the status of the operation. +func (c *azureClustersRESTClient) DeleteAzureCluster(ctx context.Context, req *gkemulticloudpb.DeleteAzureClusterRequest, opts ...gax.CallOption) (*DeleteAzureClusterOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + if req.GetAllowMissing() { + params.Add("allowMissing", fmt.Sprintf("%v", req.GetAllowMissing())) + } + if req.GetEtag() != "" { + params.Add("etag", fmt.Sprintf("%v", req.GetEtag())) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteAzureClusterOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GenerateAzureAccessToken generates a short-lived access token to authenticate to a given +// AzureCluster resource. +func (c *azureClustersRESTClient) GenerateAzureAccessToken(ctx context.Context, req *gkemulticloudpb.GenerateAzureAccessTokenRequest, opts ...gax.CallOption) (*gkemulticloudpb.GenerateAzureAccessTokenResponse, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:generateAzureAccessToken", req.GetAzureCluster()) + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "azure_cluster", url.QueryEscape(req.GetAzureCluster()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GenerateAzureAccessToken[0:len((*c.CallOptions).GenerateAzureAccessToken):len((*c.CallOptions).GenerateAzureAccessToken)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &gkemulticloudpb.GenerateAzureAccessTokenResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateAzureNodePool creates a new AzureNodePool, attached to a given AzureCluster. +// +// If successful, the response contains a newly created +// Operation resource that can be +// described to track the status of the operation. +func (c *azureClustersRESTClient) CreateAzureNodePool(ctx context.Context, req *gkemulticloudpb.CreateAzureNodePoolRequest, opts ...gax.CallOption) (*CreateAzureNodePoolOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetAzureNodePool() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/azureNodePools", req.GetParent()) + + params := url.Values{} + params.Add("azureNodePoolId", fmt.Sprintf("%v", req.GetAzureNodePoolId())) + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateAzureNodePoolOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateAzureNodePool updates an AzureNodePool. +func (c *azureClustersRESTClient) UpdateAzureNodePool(ctx context.Context, req *gkemulticloudpb.UpdateAzureNodePoolRequest, opts ...gax.CallOption) (*UpdateAzureNodePoolOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetAzureNodePool() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetAzureNodePool().GetName()) + + params := url.Values{} + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "azure_node_pool.name", url.QueryEscape(req.GetAzureNodePool().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateAzureNodePoolOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetAzureNodePool describes a specific AzureNodePool resource. +func (c *azureClustersRESTClient) GetAzureNodePool(ctx context.Context, req *gkemulticloudpb.GetAzureNodePoolRequest, opts ...gax.CallOption) (*gkemulticloudpb.AzureNodePool, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetAzureNodePool[0:len((*c.CallOptions).GetAzureNodePool):len((*c.CallOptions).GetAzureNodePool)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &gkemulticloudpb.AzureNodePool{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListAzureNodePools lists all AzureNodePool resources on a given AzureCluster. +func (c *azureClustersRESTClient) ListAzureNodePools(ctx context.Context, req *gkemulticloudpb.ListAzureNodePoolsRequest, opts ...gax.CallOption) *AzureNodePoolIterator { + it := &AzureNodePoolIterator{} + req = proto.Clone(req).(*gkemulticloudpb.ListAzureNodePoolsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*gkemulticloudpb.AzureNodePool, string, error) { + resp := &gkemulticloudpb.ListAzureNodePoolsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/azureNodePools", req.GetParent()) + + params := url.Values{} + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetAzureNodePools(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// DeleteAzureNodePool deletes a specific AzureNodePool resource. +// +// If successful, the response contains a newly created +// Operation resource that can be +// described to track the status of the operation. +func (c *azureClustersRESTClient) DeleteAzureNodePool(ctx context.Context, req *gkemulticloudpb.DeleteAzureNodePoolRequest, opts ...gax.CallOption) (*DeleteAzureNodePoolOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + if req.GetAllowMissing() { + params.Add("allowMissing", fmt.Sprintf("%v", req.GetAllowMissing())) + } + if req.GetEtag() != "" { + params.Add("etag", fmt.Sprintf("%v", req.GetEtag())) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteAzureNodePoolOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetAzureServerConfig returns information, such as supported Azure regions and Kubernetes +// versions, on a given Google Cloud location. +func (c *azureClustersRESTClient) GetAzureServerConfig(ctx context.Context, req *gkemulticloudpb.GetAzureServerConfigRequest, opts ...gax.CallOption) (*gkemulticloudpb.AzureServerConfig, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetAzureServerConfig[0:len((*c.CallOptions).GetAzureServerConfig):len((*c.CallOptions).GetAzureServerConfig)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &gkemulticloudpb.AzureServerConfig{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateAzureClientOperation manages a long-running operation from CreateAzureClient. +type CreateAzureClientOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateAzureClientOperation returns a new CreateAzureClientOperation from a given name. +// The name must be that of a previously created CreateAzureClientOperation, possibly from a different process. +func (c *azureClustersGRPCClient) CreateAzureClientOperation(name string) *CreateAzureClientOperation { + return &CreateAzureClientOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateAzureClientOperation returns a new CreateAzureClientOperation from a given name. +// The name must be that of a previously created CreateAzureClientOperation, possibly from a different process. +func (c *azureClustersRESTClient) CreateAzureClientOperation(name string) *CreateAzureClientOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateAzureClientOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CreateAzureClientOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*gkemulticloudpb.AzureClient, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp gkemulticloudpb.AzureClient + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *CreateAzureClientOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*gkemulticloudpb.AzureClient, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp gkemulticloudpb.AzureClient + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *CreateAzureClientOperation) Metadata() (*gkemulticloudpb.OperationMetadata, error) { + var meta gkemulticloudpb.OperationMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *CreateAzureClientOperation) Done() bool { + return op.lro.Done() +} + +// 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 *CreateAzureClientOperation) Name() string { + return op.lro.Name() +} + +// CreateAzureClusterOperation manages a long-running operation from CreateAzureCluster. +type CreateAzureClusterOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateAzureClusterOperation returns a new CreateAzureClusterOperation from a given name. +// The name must be that of a previously created CreateAzureClusterOperation, possibly from a different process. +func (c *azureClustersGRPCClient) CreateAzureClusterOperation(name string) *CreateAzureClusterOperation { + return &CreateAzureClusterOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateAzureClusterOperation returns a new CreateAzureClusterOperation from a given name. +// The name must be that of a previously created CreateAzureClusterOperation, possibly from a different process. +func (c *azureClustersRESTClient) CreateAzureClusterOperation(name string) *CreateAzureClusterOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateAzureClusterOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CreateAzureClusterOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*gkemulticloudpb.AzureCluster, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp gkemulticloudpb.AzureCluster + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *CreateAzureClusterOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*gkemulticloudpb.AzureCluster, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp gkemulticloudpb.AzureCluster + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *CreateAzureClusterOperation) Metadata() (*gkemulticloudpb.OperationMetadata, error) { + var meta gkemulticloudpb.OperationMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { return nil, err } return &meta, nil @@ -1087,7 +2440,8 @@ func (op *CreateAzureClusterOperation) Name() string { // CreateAzureNodePoolOperation manages a long-running operation from CreateAzureNodePool. type CreateAzureNodePoolOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateAzureNodePoolOperation returns a new CreateAzureNodePoolOperation from a given name. @@ -1098,10 +2452,21 @@ func (c *azureClustersGRPCClient) CreateAzureNodePoolOperation(name string) *Cre } } +// CreateAzureNodePoolOperation returns a new CreateAzureNodePoolOperation from a given name. +// The name must be that of a previously created CreateAzureNodePoolOperation, possibly from a different process. +func (c *azureClustersRESTClient) CreateAzureNodePoolOperation(name string) *CreateAzureNodePoolOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateAzureNodePoolOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateAzureNodePoolOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*gkemulticloudpb.AzureNodePool, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp gkemulticloudpb.AzureNodePool if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1119,6 +2484,7 @@ func (op *CreateAzureNodePoolOperation) Wait(ctx context.Context, opts ...gax.Ca // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateAzureNodePoolOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*gkemulticloudpb.AzureNodePool, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp gkemulticloudpb.AzureNodePool if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1156,7 +2522,8 @@ func (op *CreateAzureNodePoolOperation) Name() string { // DeleteAzureClientOperation manages a long-running operation from DeleteAzureClient. type DeleteAzureClientOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteAzureClientOperation returns a new DeleteAzureClientOperation from a given name. @@ -1167,10 +2534,21 @@ func (c *azureClustersGRPCClient) DeleteAzureClientOperation(name string) *Delet } } +// DeleteAzureClientOperation returns a new DeleteAzureClientOperation from a given name. +// The name must be that of a previously created DeleteAzureClientOperation, possibly from a different process. +func (c *azureClustersRESTClient) DeleteAzureClientOperation(name string) *DeleteAzureClientOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteAzureClientOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteAzureClientOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -1184,6 +2562,7 @@ func (op *DeleteAzureClientOperation) Wait(ctx context.Context, opts ...gax.Call // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteAzureClientOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -1214,7 +2593,8 @@ func (op *DeleteAzureClientOperation) Name() string { // DeleteAzureClusterOperation manages a long-running operation from DeleteAzureCluster. type DeleteAzureClusterOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteAzureClusterOperation returns a new DeleteAzureClusterOperation from a given name. @@ -1225,10 +2605,21 @@ func (c *azureClustersGRPCClient) DeleteAzureClusterOperation(name string) *Dele } } +// DeleteAzureClusterOperation returns a new DeleteAzureClusterOperation from a given name. +// The name must be that of a previously created DeleteAzureClusterOperation, possibly from a different process. +func (c *azureClustersRESTClient) DeleteAzureClusterOperation(name string) *DeleteAzureClusterOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteAzureClusterOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteAzureClusterOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -1242,6 +2633,7 @@ func (op *DeleteAzureClusterOperation) Wait(ctx context.Context, opts ...gax.Cal // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteAzureClusterOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -1272,7 +2664,8 @@ func (op *DeleteAzureClusterOperation) Name() string { // DeleteAzureNodePoolOperation manages a long-running operation from DeleteAzureNodePool. type DeleteAzureNodePoolOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteAzureNodePoolOperation returns a new DeleteAzureNodePoolOperation from a given name. @@ -1283,10 +2676,21 @@ func (c *azureClustersGRPCClient) DeleteAzureNodePoolOperation(name string) *Del } } +// DeleteAzureNodePoolOperation returns a new DeleteAzureNodePoolOperation from a given name. +// The name must be that of a previously created DeleteAzureNodePoolOperation, possibly from a different process. +func (c *azureClustersRESTClient) DeleteAzureNodePoolOperation(name string) *DeleteAzureNodePoolOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteAzureNodePoolOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteAzureNodePoolOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -1300,6 +2704,7 @@ func (op *DeleteAzureNodePoolOperation) Wait(ctx context.Context, opts ...gax.Ca // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteAzureNodePoolOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -1330,7 +2735,8 @@ func (op *DeleteAzureNodePoolOperation) Name() string { // UpdateAzureClusterOperation manages a long-running operation from UpdateAzureCluster. type UpdateAzureClusterOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateAzureClusterOperation returns a new UpdateAzureClusterOperation from a given name. @@ -1341,10 +2747,21 @@ func (c *azureClustersGRPCClient) UpdateAzureClusterOperation(name string) *Upda } } +// UpdateAzureClusterOperation returns a new UpdateAzureClusterOperation from a given name. +// The name must be that of a previously created UpdateAzureClusterOperation, possibly from a different process. +func (c *azureClustersRESTClient) UpdateAzureClusterOperation(name string) *UpdateAzureClusterOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateAzureClusterOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateAzureClusterOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*gkemulticloudpb.AzureCluster, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp gkemulticloudpb.AzureCluster if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1362,6 +2779,7 @@ func (op *UpdateAzureClusterOperation) Wait(ctx context.Context, opts ...gax.Cal // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateAzureClusterOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*gkemulticloudpb.AzureCluster, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp gkemulticloudpb.AzureCluster if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1399,7 +2817,8 @@ func (op *UpdateAzureClusterOperation) Name() string { // UpdateAzureNodePoolOperation manages a long-running operation from UpdateAzureNodePool. type UpdateAzureNodePoolOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateAzureNodePoolOperation returns a new UpdateAzureNodePoolOperation from a given name. @@ -1410,10 +2829,21 @@ func (c *azureClustersGRPCClient) UpdateAzureNodePoolOperation(name string) *Upd } } +// UpdateAzureNodePoolOperation returns a new UpdateAzureNodePoolOperation from a given name. +// The name must be that of a previously created UpdateAzureNodePoolOperation, possibly from a different process. +func (c *azureClustersRESTClient) UpdateAzureNodePoolOperation(name string) *UpdateAzureNodePoolOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateAzureNodePoolOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateAzureNodePoolOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*gkemulticloudpb.AzureNodePool, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp gkemulticloudpb.AzureNodePool if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1431,6 +2861,7 @@ func (op *UpdateAzureNodePoolOperation) Wait(ctx context.Context, opts ...gax.Ca // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateAzureNodePoolOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*gkemulticloudpb.AzureNodePool, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp gkemulticloudpb.AzureNodePool if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/gkemulticloud/apiv1/azure_clusters_client_example_test.go b/gkemulticloud/apiv1/azure_clusters_client_example_test.go index 4f02de31bda5..096e23c6a06a 100644 --- a/gkemulticloud/apiv1/azure_clusters_client_example_test.go +++ b/gkemulticloud/apiv1/azure_clusters_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewAzureClustersClient() { _ = c } +func ExampleNewAzureClustersRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := gkemulticloud.NewAzureClustersRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleAzureClustersClient_CreateAzureClient() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/gkemulticloud/apiv1/doc.go b/gkemulticloud/apiv1/doc.go index 958043ce7991..a6db31c4c781 100644 --- a/gkemulticloud/apiv1/doc.go +++ b/gkemulticloud/apiv1/doc.go @@ -93,6 +93,8 @@ package gkemulticloud // import "cloud.google.com/go/gkemulticloud/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -181,3 +183,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/gkemulticloud/apiv1/gapic_metadata.json b/gkemulticloud/apiv1/gapic_metadata.json index 1575e3436abf..aa48f9b47dd7 100644 --- a/gkemulticloud/apiv1/gapic_metadata.json +++ b/gkemulticloud/apiv1/gapic_metadata.json @@ -71,6 +71,71 @@ ] } } + }, + "rest": { + "libraryClient": "AwsClustersClient", + "rpcs": { + "CreateAwsCluster": { + "methods": [ + "CreateAwsCluster" + ] + }, + "CreateAwsNodePool": { + "methods": [ + "CreateAwsNodePool" + ] + }, + "DeleteAwsCluster": { + "methods": [ + "DeleteAwsCluster" + ] + }, + "DeleteAwsNodePool": { + "methods": [ + "DeleteAwsNodePool" + ] + }, + "GenerateAwsAccessToken": { + "methods": [ + "GenerateAwsAccessToken" + ] + }, + "GetAwsCluster": { + "methods": [ + "GetAwsCluster" + ] + }, + "GetAwsNodePool": { + "methods": [ + "GetAwsNodePool" + ] + }, + "GetAwsServerConfig": { + "methods": [ + "GetAwsServerConfig" + ] + }, + "ListAwsClusters": { + "methods": [ + "ListAwsClusters" + ] + }, + "ListAwsNodePools": { + "methods": [ + "ListAwsNodePools" + ] + }, + "UpdateAwsCluster": { + "methods": [ + "UpdateAwsCluster" + ] + }, + "UpdateAwsNodePool": { + "methods": [ + "UpdateAwsNodePool" + ] + } + } } } }, @@ -160,6 +225,91 @@ ] } } + }, + "rest": { + "libraryClient": "AzureClustersClient", + "rpcs": { + "CreateAzureClient": { + "methods": [ + "CreateAzureClient" + ] + }, + "CreateAzureCluster": { + "methods": [ + "CreateAzureCluster" + ] + }, + "CreateAzureNodePool": { + "methods": [ + "CreateAzureNodePool" + ] + }, + "DeleteAzureClient": { + "methods": [ + "DeleteAzureClient" + ] + }, + "DeleteAzureCluster": { + "methods": [ + "DeleteAzureCluster" + ] + }, + "DeleteAzureNodePool": { + "methods": [ + "DeleteAzureNodePool" + ] + }, + "GenerateAzureAccessToken": { + "methods": [ + "GenerateAzureAccessToken" + ] + }, + "GetAzureClient": { + "methods": [ + "GetAzureClient" + ] + }, + "GetAzureCluster": { + "methods": [ + "GetAzureCluster" + ] + }, + "GetAzureNodePool": { + "methods": [ + "GetAzureNodePool" + ] + }, + "GetAzureServerConfig": { + "methods": [ + "GetAzureServerConfig" + ] + }, + "ListAzureClients": { + "methods": [ + "ListAzureClients" + ] + }, + "ListAzureClusters": { + "methods": [ + "ListAzureClusters" + ] + }, + "ListAzureNodePools": { + "methods": [ + "ListAzureNodePools" + ] + }, + "UpdateAzureCluster": { + "methods": [ + "UpdateAzureCluster" + ] + }, + "UpdateAzureNodePool": { + "methods": [ + "UpdateAzureNodePool" + ] + } + } } } } diff --git a/gkemulticloud/apiv1/gkemulticloudpb/aws_resources.pb.go b/gkemulticloud/apiv1/gkemulticloudpb/aws_resources.pb.go index a74a141eceb4..b4aea11c154a 100644 --- a/gkemulticloud/apiv1/gkemulticloudpb/aws_resources.pb.go +++ b/gkemulticloud/apiv1/gkemulticloudpb/aws_resources.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/gkemulticloud/v1/aws_resources.proto package gkemulticloudpb diff --git a/gkemulticloud/apiv1/gkemulticloudpb/aws_service.pb.go b/gkemulticloud/apiv1/gkemulticloudpb/aws_service.pb.go index 229d1cd3473d..4ff3b1cb8776 100644 --- a/gkemulticloud/apiv1/gkemulticloudpb/aws_service.pb.go +++ b/gkemulticloud/apiv1/gkemulticloudpb/aws_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/gkemulticloud/v1/aws_service.proto package gkemulticloudpb @@ -146,26 +146,26 @@ type UpdateAwsClusterRequest struct { // this field. The elements of the repeated paths field can only include these // fields from [AwsCluster][google.cloud.gkemulticloud.v1.AwsCluster]: // - // - `description`. - // - `annotations`. - // - `control_plane.version`. - // - `authorization.admin_users`. - // - `control_plane.aws_services_authentication.role_arn`. - // - `control_plane.aws_services_authentication.role_session_name`. - // - `control_plane.config_encryption.kms_key_arn`. - // - `control_plane.instance_type`. - // - `control_plane.security_group_ids`. - // - `control_plane.proxy_config`. - // - `control_plane.proxy_config.secret_arn`. - // - `control_plane.proxy_config.secret_version`. - // - `control_plane.root_volume.iops`. - // - `control_plane.root_volume.kms_key_arn`. - // - `control_plane.root_volume.volume_type`. - // - `control_plane.root_volume.size_gib`. - // - `control_plane.ssh_config`. - // - `control_plane.ssh_config.ec2_key_pair`. - // - `control_plane.instance_placement.tenancy`. - // - `logging_config`. + // * `description`. + // * `annotations`. + // * `control_plane.version`. + // * `authorization.admin_users`. + // * `control_plane.aws_services_authentication.role_arn`. + // * `control_plane.aws_services_authentication.role_session_name`. + // * `control_plane.config_encryption.kms_key_arn`. + // * `control_plane.instance_type`. + // * `control_plane.security_group_ids`. + // * `control_plane.proxy_config`. + // * `control_plane.proxy_config.secret_arn`. + // * `control_plane.proxy_config.secret_version`. + // * `control_plane.root_volume.iops`. + // * `control_plane.root_volume.kms_key_arn`. + // * `control_plane.root_volume.volume_type`. + // * `control_plane.root_volume.size_gib`. + // * `control_plane.ssh_config`. + // * `control_plane.ssh_config.ec2_key_pair`. + // * `control_plane.instance_placement.tenancy`. + // * `logging_config`. UpdateMask *fieldmaskpb.FieldMask `protobuf:"bytes,4,opt,name=update_mask,json=updateMask,proto3" json:"update_mask,omitempty"` } @@ -612,21 +612,21 @@ type UpdateAwsNodePoolRequest struct { // this field. The elements of the repeated paths field can only include these // fields from [AwsNodePool][google.cloud.gkemulticloud.v1.AwsNodePool]: // - // - `annotations`. - // - `version`. - // - `autoscaling.min_node_count`. - // - `autoscaling.max_node_count`. - // - `config.config_encryption.kms_key_arn`. - // - `config.security_group_ids`. - // - `config.root_volume.iops`. - // - `config.root_volume.kms_key_arn`. - // - `config.root_volume.volume_type`. - // - `config.root_volume.size_gib`. - // - `config.proxy_config`. - // - `config.proxy_config.secret_arn`. - // - `config.proxy_config.secret_version`. - // - `config.ssh_config`. - // - `config.ssh_config.ec2_key_pair`. + // * `annotations`. + // * `version`. + // * `autoscaling.min_node_count`. + // * `autoscaling.max_node_count`. + // * `config.config_encryption.kms_key_arn`. + // * `config.security_group_ids`. + // * `config.root_volume.iops`. + // * `config.root_volume.kms_key_arn`. + // * `config.root_volume.volume_type`. + // * `config.root_volume.size_gib`. + // * `config.proxy_config`. + // * `config.proxy_config.secret_arn`. + // * `config.proxy_config.secret_version`. + // * `config.ssh_config`. + // * `config.ssh_config.ec2_key_pair`. UpdateMask *fieldmaskpb.FieldMask `protobuf:"bytes,3,opt,name=update_mask,json=updateMask,proto3" json:"update_mask,omitempty"` } diff --git a/gkemulticloud/apiv1/gkemulticloudpb/azure_resources.pb.go b/gkemulticloud/apiv1/gkemulticloudpb/azure_resources.pb.go index 8a21dbd4d137..e8db47f0a9ef 100644 --- a/gkemulticloud/apiv1/gkemulticloudpb/azure_resources.pb.go +++ b/gkemulticloud/apiv1/gkemulticloudpb/azure_resources.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/gkemulticloud/v1/azure_resources.proto package gkemulticloudpb diff --git a/gkemulticloud/apiv1/gkemulticloudpb/azure_service.pb.go b/gkemulticloud/apiv1/gkemulticloudpb/azure_service.pb.go index fc40012e0dcb..0646c8974c41 100644 --- a/gkemulticloud/apiv1/gkemulticloudpb/azure_service.pb.go +++ b/gkemulticloud/apiv1/gkemulticloudpb/azure_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/gkemulticloud/v1/azure_service.proto package gkemulticloudpb @@ -146,14 +146,14 @@ type UpdateAzureClusterRequest struct { // this field. The elements of the repeated paths field can only include these // fields from [AzureCluster][google.cloud.gkemulticloud.v1.AzureCluster]: // - // - `description`. - // - `annotations`. - // - `azureClient`. - // - `control_plane.version`. - // - `control_plane.vm_size`. - // - `authorization.admin_users`. - // - `control_plane.root_volume.size_gib`. - // - `logging_config` + // * `description`. + // * `annotations`. + // * `azureClient`. + // * `control_plane.version`. + // * `control_plane.vm_size`. + // * `authorization.admin_users`. + // * `control_plane.root_volume.size_gib`. + // * `logging_config` UpdateMask *fieldmaskpb.FieldMask `protobuf:"bytes,4,opt,name=update_mask,json=updateMask,proto3" json:"update_mask,omitempty"` } @@ -599,11 +599,11 @@ type UpdateAzureNodePoolRequest struct { // this field. The elements of the repeated paths field can only include these // fields from [AzureNodePool][google.cloud.gkemulticloud.v1.AzureNodePool]: // - // *. `annotations`. - // * `version`. - // * `autoscaling.min_node_count`. - // * `autoscaling.max_node_count`. - // * `config.vm_size`. + // *. `annotations`. + // * `version`. + // * `autoscaling.min_node_count`. + // * `autoscaling.max_node_count`. + // * `config.vm_size`. UpdateMask *fieldmaskpb.FieldMask `protobuf:"bytes,3,opt,name=update_mask,json=updateMask,proto3" json:"update_mask,omitempty"` } diff --git a/gkemulticloud/apiv1/gkemulticloudpb/common_resources.pb.go b/gkemulticloud/apiv1/gkemulticloudpb/common_resources.pb.go index 161583e72379..acef4a481278 100644 --- a/gkemulticloud/apiv1/gkemulticloudpb/common_resources.pb.go +++ b/gkemulticloud/apiv1/gkemulticloudpb/common_resources.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/gkemulticloud/v1/common_resources.proto package gkemulticloudpb diff --git a/gsuiteaddons/apiv1/doc.go b/gsuiteaddons/apiv1/doc.go index 6b5360132f5b..fef3f6c0bda0 100644 --- a/gsuiteaddons/apiv1/doc.go +++ b/gsuiteaddons/apiv1/doc.go @@ -78,6 +78,8 @@ package gsuiteaddons // import "cloud.google.com/go/gsuiteaddons/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -166,3 +168,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/gsuiteaddons/apiv1/g_suite_add_ons_client.go b/gsuiteaddons/apiv1/g_suite_add_ons_client.go index 1fccb1a073bb..065e67ee3a0e 100644 --- a/gsuiteaddons/apiv1/g_suite_add_ons_client.go +++ b/gsuiteaddons/apiv1/g_suite_add_ons_client.go @@ -17,21 +17,27 @@ package gsuiteaddons import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" gsuiteaddonspb "cloud.google.com/go/gsuiteaddons/apiv1/gsuiteaddonspb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -142,6 +148,80 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + GetAuthorization: []gax.CallOption{}, + CreateDeployment: []gax.CallOption{}, + ReplaceDeployment: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusInternalServerError) + }), + }, + GetDeployment: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusInternalServerError) + }), + }, + ListDeployments: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusInternalServerError) + }), + }, + DeleteDeployment: []gax.CallOption{}, + InstallDeployment: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusInternalServerError) + }), + }, + UninstallDeployment: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusInternalServerError) + }), + }, + GetInstallStatus: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusInternalServerError) + }), + }, + } +} + // internalClient is an interface that defines the methods available from Google Workspace Add-ons API. type internalClient interface { Close() error @@ -377,6 +457,101 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new g suite add ons rest client. +// +// A service for managing Google Workspace Add-ons deployments. +// +// A Google Workspace Add-on is a third-party embedded component that can be +// installed in Google Workspace Applications like Gmail, Calendar, Drive, and +// the Google Docs, Sheets, and Slides editors. Google Workspace Add-ons can +// display UI cards, receive contextual information from the host application, +// and perform actions in the host application (See: +// https://developers.google.com/gsuite/add-ons/overview (at https://developers.google.com/gsuite/add-ons/overview) for more information). +// +// A Google Workspace Add-on deployment resource specifies metadata about the +// add-on, including a specification of the entry points in the host application +// that trigger add-on executions (see: +// https://developers.google.com/gsuite/add-ons/concepts/gsuite-manifests (at https://developers.google.com/gsuite/add-ons/concepts/gsuite-manifests)). +// Add-on deployments defined via the Google Workspace Add-ons API define their +// entrypoints using HTTPS URLs (See: +// https://developers.google.com/gsuite/add-ons/guides/alternate-runtimes (at https://developers.google.com/gsuite/add-ons/guides/alternate-runtimes)), +// +// A Google Workspace Add-on deployment can be installed in developer mode, +// which allows an add-on developer to test the experience an end-user would see +// when installing and running the add-on in their G Suite applications. When +// running in developer mode, more detailed error messages are exposed in the +// add-on UI to aid in debugging. +// +// A Google Workspace Add-on deployment can be published to Google Workspace +// Marketplace, which allows other Google Workspace users to discover and +// install the add-on. See: +// https://developers.google.com/gsuite/add-ons/how-tos/publish-add-on-overview (at https://developers.google.com/gsuite/add-ons/how-tos/publish-add-on-overview) +// for details. +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://gsuiteaddons.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://gsuiteaddons.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://gsuiteaddons.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) GetAuthorization(ctx context.Context, req *gsuiteaddonspb.GetAuthorizationRequest, opts ...gax.CallOption) (*gsuiteaddonspb.Authorization, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 120000*time.Millisecond) @@ -586,6 +761,538 @@ func (c *gRPCClient) GetInstallStatus(ctx context.Context, req *gsuiteaddonspb.G return resp, nil } +// GetAuthorization gets the authorization information for deployments in a given project. +func (c *restClient) GetAuthorization(ctx context.Context, req *gsuiteaddonspb.GetAuthorizationRequest, opts ...gax.CallOption) (*gsuiteaddonspb.Authorization, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetAuthorization[0:len((*c.CallOptions).GetAuthorization):len((*c.CallOptions).GetAuthorization)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &gsuiteaddonspb.Authorization{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateDeployment creates a deployment with the specified name and configuration. +func (c *restClient) CreateDeployment(ctx context.Context, req *gsuiteaddonspb.CreateDeploymentRequest, opts ...gax.CallOption) (*gsuiteaddonspb.Deployment, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetDeployment() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/deployments", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("deploymentId", fmt.Sprintf("%v", req.GetDeploymentId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateDeployment[0:len((*c.CallOptions).CreateDeployment):len((*c.CallOptions).CreateDeployment)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &gsuiteaddonspb.Deployment{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ReplaceDeployment creates or replaces a deployment with the specified name. +func (c *restClient) ReplaceDeployment(ctx context.Context, req *gsuiteaddonspb.ReplaceDeploymentRequest, opts ...gax.CallOption) (*gsuiteaddonspb.Deployment, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetDeployment() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetDeployment().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "deployment.name", url.QueryEscape(req.GetDeployment().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).ReplaceDeployment[0:len((*c.CallOptions).ReplaceDeployment):len((*c.CallOptions).ReplaceDeployment)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &gsuiteaddonspb.Deployment{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PUT", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetDeployment gets the deployment with the specified name. +func (c *restClient) GetDeployment(ctx context.Context, req *gsuiteaddonspb.GetDeploymentRequest, opts ...gax.CallOption) (*gsuiteaddonspb.Deployment, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetDeployment[0:len((*c.CallOptions).GetDeployment):len((*c.CallOptions).GetDeployment)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &gsuiteaddonspb.Deployment{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListDeployments lists all deployments in a particular project. +func (c *restClient) ListDeployments(ctx context.Context, req *gsuiteaddonspb.ListDeploymentsRequest, opts ...gax.CallOption) *DeploymentIterator { + it := &DeploymentIterator{} + req = proto.Clone(req).(*gsuiteaddonspb.ListDeploymentsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*gsuiteaddonspb.Deployment, string, error) { + resp := &gsuiteaddonspb.ListDeploymentsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/deployments", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetDeployments(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// DeleteDeployment deletes the deployment with the given name. +func (c *restClient) DeleteDeployment(ctx context.Context, req *gsuiteaddonspb.DeleteDeploymentRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetEtag() != "" { + params.Add("etag", fmt.Sprintf("%v", req.GetEtag())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// InstallDeployment installs a deployment in developer mode. +// See: +// https://developers.google.com/gsuite/add-ons/how-tos/testing-gsuite-addons (at https://developers.google.com/gsuite/add-ons/how-tos/testing-gsuite-addons). +func (c *restClient) InstallDeployment(ctx context.Context, req *gsuiteaddonspb.InstallDeploymentRequest, opts ...gax.CallOption) error { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:install", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// UninstallDeployment uninstalls a developer mode deployment. +// See: +// https://developers.google.com/gsuite/add-ons/how-tos/testing-gsuite-addons (at https://developers.google.com/gsuite/add-ons/how-tos/testing-gsuite-addons). +func (c *restClient) UninstallDeployment(ctx context.Context, req *gsuiteaddonspb.UninstallDeploymentRequest, opts ...gax.CallOption) error { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:uninstall", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetInstallStatus fetches the install status of a developer mode deployment. +func (c *restClient) GetInstallStatus(ctx context.Context, req *gsuiteaddonspb.GetInstallStatusRequest, opts ...gax.CallOption) (*gsuiteaddonspb.InstallStatus, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetInstallStatus[0:len((*c.CallOptions).GetInstallStatus):len((*c.CallOptions).GetInstallStatus)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &gsuiteaddonspb.InstallStatus{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + // DeploymentIterator manages a stream of *gsuiteaddonspb.Deployment. type DeploymentIterator struct { items []*gsuiteaddonspb.Deployment diff --git a/gsuiteaddons/apiv1/g_suite_add_ons_client_example_test.go b/gsuiteaddons/apiv1/g_suite_add_ons_client_example_test.go index 4d217d0a1da9..a99f48bfcdfe 100644 --- a/gsuiteaddons/apiv1/g_suite_add_ons_client_example_test.go +++ b/gsuiteaddons/apiv1/g_suite_add_ons_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := gsuiteaddons.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_GetAuthorization() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/gsuiteaddons/apiv1/gapic_metadata.json b/gsuiteaddons/apiv1/gapic_metadata.json index 178d0b85085d..35340bd428dc 100644 --- a/gsuiteaddons/apiv1/gapic_metadata.json +++ b/gsuiteaddons/apiv1/gapic_metadata.json @@ -56,6 +56,56 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "CreateDeployment": { + "methods": [ + "CreateDeployment" + ] + }, + "DeleteDeployment": { + "methods": [ + "DeleteDeployment" + ] + }, + "GetAuthorization": { + "methods": [ + "GetAuthorization" + ] + }, + "GetDeployment": { + "methods": [ + "GetDeployment" + ] + }, + "GetInstallStatus": { + "methods": [ + "GetInstallStatus" + ] + }, + "InstallDeployment": { + "methods": [ + "InstallDeployment" + ] + }, + "ListDeployments": { + "methods": [ + "ListDeployments" + ] + }, + "ReplaceDeployment": { + "methods": [ + "ReplaceDeployment" + ] + }, + "UninstallDeployment": { + "methods": [ + "UninstallDeployment" + ] + } + } } } } diff --git a/gsuiteaddons/apiv1/gsuiteaddonspb/gsuiteaddons.pb.go b/gsuiteaddons/apiv1/gsuiteaddonspb/gsuiteaddons.pb.go index b41dcd716511..bdebc5ffd2b5 100644 --- a/gsuiteaddons/apiv1/gsuiteaddonspb/gsuiteaddons.pb.go +++ b/gsuiteaddons/apiv1/gsuiteaddonspb/gsuiteaddons.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/gsuiteaddons/v1/gsuiteaddons.proto package gsuiteaddonspb diff --git a/iam/apiv1/doc.go b/iam/apiv1/doc.go index da846bc69328..2b97d607b707 100644 --- a/iam/apiv1/doc.go +++ b/iam/apiv1/doc.go @@ -82,6 +82,8 @@ package iam // import "cloud.google.com/go/iam/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -170,3 +172,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/iam/apiv1/gapic_metadata.json b/iam/apiv1/gapic_metadata.json index 2b30ed51aebb..17281b520f73 100644 --- a/iam/apiv1/gapic_metadata.json +++ b/iam/apiv1/gapic_metadata.json @@ -26,6 +26,26 @@ ] } } + }, + "rest": { + "libraryClient": "IamPolicyClient", + "rpcs": { + "GetIamPolicy": { + "methods": [ + "GetIamPolicy" + ] + }, + "SetIamPolicy": { + "methods": [ + "SetIamPolicy" + ] + }, + "TestIamPermissions": { + "methods": [ + "TestIamPermissions" + ] + } + } } } } diff --git a/iam/apiv1/iam_policy_client.go b/iam/apiv1/iam_policy_client.go index 1179d8a60c00..3951ec09d678 100644 --- a/iam/apiv1/iam_policy_client.go +++ b/iam/apiv1/iam_policy_client.go @@ -17,18 +17,24 @@ package iam import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" iampb "cloud.google.com/go/iam/apiv1/iampb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" ) var newIamPolicyClientHook clientHook @@ -60,6 +66,14 @@ func defaultIamPolicyCallOptions() *IamPolicyCallOptions { } } +func defaultIamPolicyRESTCallOptions() *IamPolicyCallOptions { + return &IamPolicyCallOptions{ + SetIamPolicy: []gax.CallOption{}, + GetIamPolicy: []gax.CallOption{}, + TestIamPermissions: []gax.CallOption{}, + } +} + // internalIamPolicyClient is an interface that defines the methods available from IAM Meta API. type internalIamPolicyClient interface { Close() error @@ -252,6 +266,94 @@ func (c *iamPolicyGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type iamPolicyRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing IamPolicyClient + CallOptions **IamPolicyCallOptions +} + +// NewIamPolicyRESTClient creates a new iam policy rest client. +// +// # API Overview +// +// Manages Identity and Access Management (IAM) policies. +// +// Any implementation of an API that offers access control features +// implements the google.iam.v1.IAMPolicy interface. +// +// Data modelAccess control is applied when a principal (user or service account), takes +// some action on a resource exposed by a service. Resources, identified by +// URI-like names, are the unit of access control specification. Service +// implementations can choose the granularity of access control and the +// supported permissions for their resources. +// For example one database service may allow access control to be +// specified only at the Table level, whereas another might allow access control +// to also be specified at the Column level. +// +// # Policy StructureSee google.iam.v1.Policy +// +// This is intentionally not a CRUD style API because access control policies +// are created and deleted implicitly with the resources to which they are +// attached. +func NewIamPolicyRESTClient(ctx context.Context, opts ...option.ClientOption) (*IamPolicyClient, error) { + clientOpts := append(defaultIamPolicyRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultIamPolicyRESTCallOptions() + c := &iamPolicyRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &IamPolicyClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultIamPolicyRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://iam-meta-api.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://iam-meta-api.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://iam-meta-api.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *iamPolicyRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *iamPolicyRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *iamPolicyRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *iamPolicyGRPCClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) @@ -302,3 +404,206 @@ func (c *iamPolicyGRPCClient) TestIamPermissions(ctx context.Context, req *iampb } return resp, nil } + +// SetIamPolicy sets the access control policy on the specified resource. Replaces any +// existing policy. +// +// Can return NOT_FOUND, INVALID_ARGUMENT, and PERMISSION_DENIED errors. +func (c *iamPolicyRESTClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:setIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetIamPolicy gets the access control policy for a resource. +// Returns an empty policy if the resource exists and does not have a policy +// set. +func (c *iamPolicyRESTClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:getIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// TestIamPermissions returns permissions that a caller has on the specified resource. +// If the resource does not exist, this will return an empty set of +// permissions, not a NOT_FOUND error. +// +// Note: This operation is designed to be used for building permission-aware +// UIs and command-line tools, not for authorization checking. This operation +// may “fail open” without warning. +func (c *iamPolicyRESTClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:testIamPermissions", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.TestIamPermissionsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} diff --git a/iam/apiv1/iam_policy_client_example_test.go b/iam/apiv1/iam_policy_client_example_test.go index 853e470156ca..234570ea7192 100644 --- a/iam/apiv1/iam_policy_client_example_test.go +++ b/iam/apiv1/iam_policy_client_example_test.go @@ -40,6 +40,23 @@ func ExampleNewIamPolicyClient() { _ = c } +func ExampleNewIamPolicyRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := iam.NewIamPolicyRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleIamPolicyClient_SetIamPolicy() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/iam/apiv1/iampb/iam_policy.pb.go b/iam/apiv1/iampb/iam_policy.pb.go index 21079f65c3bb..348254e01ca0 100644 --- a/iam/apiv1/iampb/iam_policy.pb.go +++ b/iam/apiv1/iampb/iam_policy.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/iam/v1/iam_policy.proto package iampb diff --git a/iam/apiv1/iampb/options.pb.go b/iam/apiv1/iampb/options.pb.go index e8a2aca9c7da..ed82cca26548 100644 --- a/iam/apiv1/iampb/options.pb.go +++ b/iam/apiv1/iampb/options.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/iam/v1/options.proto package iampb diff --git a/iam/apiv1/iampb/policy.pb.go b/iam/apiv1/iampb/policy.pb.go index e521db60fa52..80024a6b4210 100644 --- a/iam/apiv1/iampb/policy.pb.go +++ b/iam/apiv1/iampb/policy.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/iam/v1/policy.proto package iampb @@ -279,11 +279,11 @@ type Policy struct { // Any operation that affects conditional role bindings must specify version // `3`. This requirement applies to the following operations: // - // - Getting a policy that includes a conditional role binding - // - Adding a conditional role binding to a policy - // - Changing a conditional role binding in a policy - // - Removing any role binding, with or without a condition, from a policy - // that includes conditions + // * Getting a policy that includes a conditional role binding + // * Adding a conditional role binding to a policy + // * Changing a conditional role binding in a policy + // * Removing any role binding, with or without a condition, from a policy + // that includes conditions // // **Important:** If you use IAM Conditions, you must include the `etag` field // whenever you call `setIamPolicy`. If you omit this field, then IAM allows @@ -396,43 +396,47 @@ type Binding struct { // Specifies the principals requesting access for a Cloud Platform resource. // `members` can have the following values: // - // - `allUsers`: A special identifier that represents anyone who is - // on the internet; with or without a Google account. + // * `allUsers`: A special identifier that represents anyone who is + // on the internet; with or without a Google account. // - // - `allAuthenticatedUsers`: A special identifier that represents anyone - // who is authenticated with a Google account or a service account. + // * `allAuthenticatedUsers`: A special identifier that represents anyone + // who is authenticated with a Google account or a service account. // - // - `user:{emailid}`: An email address that represents a specific Google - // account. For example, `alice@example.com` . + // * `user:{emailid}`: An email address that represents a specific Google + // account. For example, `alice@example.com` . // - // - `serviceAccount:{emailid}`: An email address that represents a service - // account. For example, `my-other-app@appspot.gserviceaccount.com`. // - // - `group:{emailid}`: An email address that represents a Google group. - // For example, `admins@example.com`. + // * `serviceAccount:{emailid}`: An email address that represents a service + // account. For example, `my-other-app@appspot.gserviceaccount.com`. // - // - `deleted:user:{emailid}?uid={uniqueid}`: An email address (plus unique - // identifier) representing a user that has been recently deleted. For - // example, `alice@example.com?uid=123456789012345678901`. If the user is - // recovered, this value reverts to `user:{emailid}` and the recovered user - // retains the role in the binding. + // * `group:{emailid}`: An email address that represents a Google group. + // For example, `admins@example.com`. // - // - `deleted:serviceAccount:{emailid}?uid={uniqueid}`: An email address (plus - // unique identifier) representing a service account that has been recently - // deleted. For example, - // `my-other-app@appspot.gserviceaccount.com?uid=123456789012345678901`. - // If the service account is undeleted, this value reverts to - // `serviceAccount:{emailid}` and the undeleted service account retains the - // role in the binding. + // * `deleted:user:{emailid}?uid={uniqueid}`: An email address (plus unique + // identifier) representing a user that has been recently deleted. For + // example, `alice@example.com?uid=123456789012345678901`. If the user is + // recovered, this value reverts to `user:{emailid}` and the recovered user + // retains the role in the binding. + // + // * `deleted:serviceAccount:{emailid}?uid={uniqueid}`: An email address (plus + // unique identifier) representing a service account that has been recently + // deleted. For example, + // `my-other-app@appspot.gserviceaccount.com?uid=123456789012345678901`. + // If the service account is undeleted, this value reverts to + // `serviceAccount:{emailid}` and the undeleted service account retains the + // role in the binding. + // + // * `deleted:group:{emailid}?uid={uniqueid}`: An email address (plus unique + // identifier) representing a Google group that has been recently + // deleted. For example, `admins@example.com?uid=123456789012345678901`. If + // the group is recovered, this value reverts to `group:{emailid}` and the + // recovered group retains the role in the binding. + // + // + // * `domain:{domain}`: The G Suite domain (primary) that represents all the + // users of that domain. For example, `google.com` or `example.com`. // - // - `deleted:group:{emailid}?uid={uniqueid}`: An email address (plus unique - // identifier) representing a Google group that has been recently - // deleted. For example, `admins@example.com?uid=123456789012345678901`. If - // the group is recovered, this value reverts to `group:{emailid}` and the - // recovered group retains the role in the binding. // - // - `domain:{domain}`: The G Suite domain (primary) that represents all the - // users of that domain. For example, `google.com` or `example.com`. Members []string `protobuf:"bytes,2,rep,name=members,proto3" json:"members,omitempty"` // The condition that is associated with this binding. // diff --git a/iam/apiv2/doc.go b/iam/apiv2/doc.go index ed6983fa91b4..d0ee2355f4fa 100644 --- a/iam/apiv2/doc.go +++ b/iam/apiv2/doc.go @@ -90,6 +90,8 @@ package iam // import "cloud.google.com/go/iam/apiv2" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -178,3 +180,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/iam/apiv2/gapic_metadata.json b/iam/apiv2/gapic_metadata.json index b6ecedae9553..096a86b27c69 100644 --- a/iam/apiv2/gapic_metadata.json +++ b/iam/apiv2/gapic_metadata.json @@ -41,6 +41,41 @@ ] } } + }, + "rest": { + "libraryClient": "PoliciesClient", + "rpcs": { + "CreatePolicy": { + "methods": [ + "CreatePolicy" + ] + }, + "DeletePolicy": { + "methods": [ + "DeletePolicy" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "GetPolicy": { + "methods": [ + "GetPolicy" + ] + }, + "ListPolicies": { + "methods": [ + "ListPolicies" + ] + }, + "UpdatePolicy": { + "methods": [ + "UpdatePolicy" + ] + } + } } } } diff --git a/iam/apiv2/policies_client.go b/iam/apiv2/policies_client.go index c988ab270467..49df06de4ac8 100644 --- a/iam/apiv2/policies_client.go +++ b/iam/apiv2/policies_client.go @@ -17,24 +17,30 @@ package iam import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" iampb "google.golang.org/genproto/googleapis/iam/v2" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -123,6 +129,62 @@ func defaultPoliciesCallOptions() *PoliciesCallOptions { } } +func defaultPoliciesRESTCallOptions() *PoliciesCallOptions { + return &PoliciesCallOptions{ + ListPolicies: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetPolicy: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreatePolicy: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UpdatePolicy: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeletePolicy: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetOperation: []gax.CallOption{}, + } +} + // internalPoliciesClient is an interface that defines the methods available from Identity and Access Management (IAM) API. type internalPoliciesClient interface { Close() error @@ -343,6 +405,89 @@ func (c *policiesGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type policiesRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing PoliciesClient + CallOptions **PoliciesCallOptions +} + +// NewPoliciesRESTClient creates a new policies rest client. +// +// An interface for managing Identity and Access Management (IAM) policies. +func NewPoliciesRESTClient(ctx context.Context, opts ...option.ClientOption) (*PoliciesClient, error) { + clientOpts := append(defaultPoliciesRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultPoliciesRESTCallOptions() + c := &policiesRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &PoliciesClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultPoliciesRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://iam.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://iam.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://iam.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *policiesRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *policiesRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *policiesRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *policiesGRPCClient) ListPolicies(ctx context.Context, req *iampb.ListPoliciesRequest, opts ...gax.CallOption) *PolicyIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -499,9 +644,436 @@ func (c *policiesGRPCClient) GetOperation(ctx context.Context, req *longrunningp return resp, nil } +// ListPolicies retrieves the policies of the specified kind that are attached to a +// resource. +// +// The response lists only policy metadata. In particular, policy rules are +// omitted. +func (c *policiesRESTClient) ListPolicies(ctx context.Context, req *iampb.ListPoliciesRequest, opts ...gax.CallOption) *PolicyIterator { + it := &PolicyIterator{} + req = proto.Clone(req).(*iampb.ListPoliciesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*iampb.Policy, string, error) { + resp := &iampb.ListPoliciesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetPolicies(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetPolicy gets a policy. +func (c *policiesRESTClient) GetPolicy(ctx context.Context, req *iampb.GetPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetPolicy[0:len((*c.CallOptions).GetPolicy):len((*c.CallOptions).GetPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreatePolicy creates a policy. +func (c *policiesRESTClient) CreatePolicy(ctx context.Context, req *iampb.CreatePolicyRequest, opts ...gax.CallOption) (*CreatePolicyOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetPolicy() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPolicyId() != "" { + params.Add("policyId", fmt.Sprintf("%v", req.GetPolicyId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &CreatePolicyOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdatePolicy updates the specified policy. +// +// You can update only the rules and the display name for the policy. +// +// To update a policy, you should use a read-modify-write loop: +// +// Use GetPolicy to read the current version of the policy. +// +// Modify the policy as needed. +// +// Use UpdatePolicy to write the updated policy. +// +// This pattern helps prevent conflicts between concurrent updates. +func (c *policiesRESTClient) UpdatePolicy(ctx context.Context, req *iampb.UpdatePolicyRequest, opts ...gax.CallOption) (*UpdatePolicyOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetPolicy() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetPolicy().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "policy.name", url.QueryEscape(req.GetPolicy().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PUT", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &UpdatePolicyOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeletePolicy deletes a policy. This action is permanent. +func (c *policiesRESTClient) DeletePolicy(ctx context.Context, req *iampb.DeletePolicyRequest, opts ...gax.CallOption) (*DeletePolicyOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetEtag() != "" { + params.Add("etag", fmt.Sprintf("%v", req.GetEtag())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &DeletePolicyOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *policiesRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + // CreatePolicyOperation manages a long-running operation from CreatePolicy. type CreatePolicyOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreatePolicyOperation returns a new CreatePolicyOperation from a given name. @@ -512,10 +1084,21 @@ func (c *policiesGRPCClient) CreatePolicyOperation(name string) *CreatePolicyOpe } } +// CreatePolicyOperation returns a new CreatePolicyOperation from a given name. +// The name must be that of a previously created CreatePolicyOperation, possibly from a different process. +func (c *policiesRESTClient) CreatePolicyOperation(name string) *CreatePolicyOperation { + override := fmt.Sprintf("/v2/%s", name) + return &CreatePolicyOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreatePolicyOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*iampb.Policy, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp iampb.Policy if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -533,6 +1116,7 @@ func (op *CreatePolicyOperation) Wait(ctx context.Context, opts ...gax.CallOptio // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreatePolicyOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*iampb.Policy, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp iampb.Policy if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -570,7 +1154,8 @@ func (op *CreatePolicyOperation) Name() string { // DeletePolicyOperation manages a long-running operation from DeletePolicy. type DeletePolicyOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeletePolicyOperation returns a new DeletePolicyOperation from a given name. @@ -581,10 +1166,21 @@ func (c *policiesGRPCClient) DeletePolicyOperation(name string) *DeletePolicyOpe } } +// DeletePolicyOperation returns a new DeletePolicyOperation from a given name. +// The name must be that of a previously created DeletePolicyOperation, possibly from a different process. +func (c *policiesRESTClient) DeletePolicyOperation(name string) *DeletePolicyOperation { + override := fmt.Sprintf("/v2/%s", name) + return &DeletePolicyOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeletePolicyOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*iampb.Policy, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp iampb.Policy if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -602,6 +1198,7 @@ func (op *DeletePolicyOperation) Wait(ctx context.Context, opts ...gax.CallOptio // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeletePolicyOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*iampb.Policy, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp iampb.Policy if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -639,7 +1236,8 @@ func (op *DeletePolicyOperation) Name() string { // UpdatePolicyOperation manages a long-running operation from UpdatePolicy. type UpdatePolicyOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdatePolicyOperation returns a new UpdatePolicyOperation from a given name. @@ -650,10 +1248,21 @@ func (c *policiesGRPCClient) UpdatePolicyOperation(name string) *UpdatePolicyOpe } } +// UpdatePolicyOperation returns a new UpdatePolicyOperation from a given name. +// The name must be that of a previously created UpdatePolicyOperation, possibly from a different process. +func (c *policiesRESTClient) UpdatePolicyOperation(name string) *UpdatePolicyOperation { + override := fmt.Sprintf("/v2/%s", name) + return &UpdatePolicyOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdatePolicyOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*iampb.Policy, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp iampb.Policy if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -671,6 +1280,7 @@ func (op *UpdatePolicyOperation) Wait(ctx context.Context, opts ...gax.CallOptio // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdatePolicyOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*iampb.Policy, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp iampb.Policy if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/iam/apiv2/policies_client_example_test.go b/iam/apiv2/policies_client_example_test.go index 8bf34c852467..9c18a486c188 100644 --- a/iam/apiv2/policies_client_example_test.go +++ b/iam/apiv2/policies_client_example_test.go @@ -42,6 +42,23 @@ func ExampleNewPoliciesClient() { _ = c } +func ExampleNewPoliciesRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := iam.NewPoliciesRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExamplePoliciesClient_ListPolicies() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/iam/credentials/apiv1/credentialspb/common.pb.go b/iam/credentials/apiv1/credentialspb/common.pb.go index 4b3e3541bc06..a3604e8291b2 100644 --- a/iam/credentials/apiv1/credentialspb/common.pb.go +++ b/iam/credentials/apiv1/credentialspb/common.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/iam/credentials/v1/common.proto package credentialspb diff --git a/iam/credentials/apiv1/credentialspb/iamcredentials.pb.go b/iam/credentials/apiv1/credentialspb/iamcredentials.pb.go index 0596b0eb7482..e67e0b5072e5 100644 --- a/iam/credentials/apiv1/credentialspb/iamcredentials.pb.go +++ b/iam/credentials/apiv1/credentialspb/iamcredentials.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/iam/credentials/v1/iamcredentials.proto package credentialspb diff --git a/iam/credentials/apiv1/doc.go b/iam/credentials/apiv1/doc.go index cdb90a80fd14..8b5e4a36d655 100644 --- a/iam/credentials/apiv1/doc.go +++ b/iam/credentials/apiv1/doc.go @@ -81,6 +81,8 @@ package credentials // import "cloud.google.com/go/iam/credentials/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -169,3 +171,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/iam/credentials/apiv1/gapic_metadata.json b/iam/credentials/apiv1/gapic_metadata.json index 7e1edb5bfd23..cf03f3f57ee2 100644 --- a/iam/credentials/apiv1/gapic_metadata.json +++ b/iam/credentials/apiv1/gapic_metadata.json @@ -31,6 +31,31 @@ ] } } + }, + "rest": { + "libraryClient": "IamCredentialsClient", + "rpcs": { + "GenerateAccessToken": { + "methods": [ + "GenerateAccessToken" + ] + }, + "GenerateIdToken": { + "methods": [ + "GenerateIdToken" + ] + }, + "SignBlob": { + "methods": [ + "SignBlob" + ] + }, + "SignJwt": { + "methods": [ + "SignJwt" + ] + } + } } } } diff --git a/iam/credentials/apiv1/iam_credentials_client.go b/iam/credentials/apiv1/iam_credentials_client.go index a17679390a46..63c2b77d1a00 100644 --- a/iam/credentials/apiv1/iam_credentials_client.go +++ b/iam/credentials/apiv1/iam_credentials_client.go @@ -17,20 +17,26 @@ package credentials import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" credentialspb "cloud.google.com/go/iam/credentials/apiv1/credentialspb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" ) var newIamCredentialsClientHook clientHook @@ -108,6 +114,55 @@ func defaultIamCredentialsCallOptions() *IamCredentialsCallOptions { } } +func defaultIamCredentialsRESTCallOptions() *IamCredentialsCallOptions { + return &IamCredentialsCallOptions{ + GenerateAccessToken: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + GenerateIdToken: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + SignBlob: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + SignJwt: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + } +} + // internalIamCredentialsClient is an interface that defines the methods available from IAM Service Account Credentials API. type internalIamCredentialsClient interface { Close() error @@ -271,6 +326,82 @@ func (c *iamCredentialsGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type iamCredentialsRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing IamCredentialsClient + CallOptions **IamCredentialsCallOptions +} + +// NewIamCredentialsRESTClient creates a new iam credentials rest client. +// +// A service account is a special type of Google account that belongs to your +// application or a virtual machine (VM), instead of to an individual end user. +// Your application assumes the identity of the service account to call Google +// APIs, so that the users aren’t directly involved. +// +// Service account credentials are used to temporarily assume the identity +// of the service account. Supported credential types include OAuth 2.0 access +// tokens, OpenID Connect ID tokens, self-signed JSON Web Tokens (JWTs), and +// more. +func NewIamCredentialsRESTClient(ctx context.Context, opts ...option.ClientOption) (*IamCredentialsClient, error) { + clientOpts := append(defaultIamCredentialsRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultIamCredentialsRESTCallOptions() + c := &iamCredentialsRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &IamCredentialsClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultIamCredentialsRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://iamcredentials.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://iamcredentials.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://iamcredentials.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *iamCredentialsRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *iamCredentialsRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *iamCredentialsRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *iamCredentialsGRPCClient) GenerateAccessToken(ctx context.Context, req *credentialspb.GenerateAccessTokenRequest, opts ...gax.CallOption) (*credentialspb.GenerateAccessTokenResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) @@ -358,3 +489,259 @@ func (c *iamCredentialsGRPCClient) SignJwt(ctx context.Context, req *credentials } return resp, nil } + +// GenerateAccessToken generates an OAuth 2.0 access token for a service account. +func (c *iamCredentialsRESTClient) GenerateAccessToken(ctx context.Context, req *credentialspb.GenerateAccessTokenRequest, opts ...gax.CallOption) (*credentialspb.GenerateAccessTokenResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:generateAccessToken", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GenerateAccessToken[0:len((*c.CallOptions).GenerateAccessToken):len((*c.CallOptions).GenerateAccessToken)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &credentialspb.GenerateAccessTokenResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GenerateIdToken generates an OpenID Connect ID token for a service account. +func (c *iamCredentialsRESTClient) GenerateIdToken(ctx context.Context, req *credentialspb.GenerateIdTokenRequest, opts ...gax.CallOption) (*credentialspb.GenerateIdTokenResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:generateIdToken", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GenerateIdToken[0:len((*c.CallOptions).GenerateIdToken):len((*c.CallOptions).GenerateIdToken)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &credentialspb.GenerateIdTokenResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SignBlob signs a blob using a service account’s system-managed private key. +func (c *iamCredentialsRESTClient) SignBlob(ctx context.Context, req *credentialspb.SignBlobRequest, opts ...gax.CallOption) (*credentialspb.SignBlobResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:signBlob", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SignBlob[0:len((*c.CallOptions).SignBlob):len((*c.CallOptions).SignBlob)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &credentialspb.SignBlobResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SignJwt signs a JWT using a service account’s system-managed private key. +func (c *iamCredentialsRESTClient) SignJwt(ctx context.Context, req *credentialspb.SignJwtRequest, opts ...gax.CallOption) (*credentialspb.SignJwtResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:signJwt", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SignJwt[0:len((*c.CallOptions).SignJwt):len((*c.CallOptions).SignJwt)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &credentialspb.SignJwtResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} diff --git a/iam/credentials/apiv1/iam_credentials_client_example_test.go b/iam/credentials/apiv1/iam_credentials_client_example_test.go index 075a494b7781..6e1554a1fec3 100644 --- a/iam/credentials/apiv1/iam_credentials_client_example_test.go +++ b/iam/credentials/apiv1/iam_credentials_client_example_test.go @@ -40,6 +40,23 @@ func ExampleNewIamCredentialsClient() { _ = c } +func ExampleNewIamCredentialsRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := credentials.NewIamCredentialsRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleIamCredentialsClient_GenerateAccessToken() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/iap/apiv1/doc.go b/iap/apiv1/doc.go index 155383a67b6f..169a62b1bc03 100644 --- a/iap/apiv1/doc.go +++ b/iap/apiv1/doc.go @@ -80,6 +80,8 @@ package iap // import "cloud.google.com/go/iap/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -168,3 +170,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/iap/apiv1/gapic_metadata.json b/iap/apiv1/gapic_metadata.json index 0b35c9a922cd..d31614857303 100644 --- a/iap/apiv1/gapic_metadata.json +++ b/iap/apiv1/gapic_metadata.json @@ -61,6 +61,61 @@ ] } } + }, + "rest": { + "libraryClient": "IdentityAwareProxyAdminClient", + "rpcs": { + "CreateTunnelDestGroup": { + "methods": [ + "CreateTunnelDestGroup" + ] + }, + "DeleteTunnelDestGroup": { + "methods": [ + "DeleteTunnelDestGroup" + ] + }, + "GetIamPolicy": { + "methods": [ + "GetIamPolicy" + ] + }, + "GetIapSettings": { + "methods": [ + "GetIapSettings" + ] + }, + "GetTunnelDestGroup": { + "methods": [ + "GetTunnelDestGroup" + ] + }, + "ListTunnelDestGroups": { + "methods": [ + "ListTunnelDestGroups" + ] + }, + "SetIamPolicy": { + "methods": [ + "SetIamPolicy" + ] + }, + "TestIamPermissions": { + "methods": [ + "TestIamPermissions" + ] + }, + "UpdateIapSettings": { + "methods": [ + "UpdateIapSettings" + ] + }, + "UpdateTunnelDestGroup": { + "methods": [ + "UpdateTunnelDestGroup" + ] + } + } } } }, @@ -110,6 +165,51 @@ ] } } + }, + "rest": { + "libraryClient": "IdentityAwareProxyOAuthClient", + "rpcs": { + "CreateBrand": { + "methods": [ + "CreateBrand" + ] + }, + "CreateIdentityAwareProxyClient": { + "methods": [ + "CreateIdentityAwareProxyClient" + ] + }, + "DeleteIdentityAwareProxyClient": { + "methods": [ + "DeleteIdentityAwareProxyClient" + ] + }, + "GetBrand": { + "methods": [ + "GetBrand" + ] + }, + "GetIdentityAwareProxyClient": { + "methods": [ + "GetIdentityAwareProxyClient" + ] + }, + "ListBrands": { + "methods": [ + "ListBrands" + ] + }, + "ListIdentityAwareProxyClients": { + "methods": [ + "ListIdentityAwareProxyClients" + ] + }, + "ResetIdentityAwareProxyClientSecret": { + "methods": [ + "ResetIdentityAwareProxyClientSecret" + ] + } + } } } } diff --git a/iap/apiv1/iappb/service.pb.go b/iap/apiv1/iappb/service.pb.go index 0a05ef8e46ca..77926e817db5 100644 --- a/iap/apiv1/iappb/service.pb.go +++ b/iap/apiv1/iappb/service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/iap/v1/service.proto package iappb diff --git a/iap/apiv1/identity_aware_proxy_admin_client.go b/iap/apiv1/identity_aware_proxy_admin_client.go index 07a2523b664b..b99252a5c2a3 100644 --- a/iap/apiv1/identity_aware_proxy_admin_client.go +++ b/iap/apiv1/identity_aware_proxy_admin_client.go @@ -17,21 +17,27 @@ package iap import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" iappb "cloud.google.com/go/iap/apiv1/iappb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" iampb "google.golang.org/genproto/googleapis/iam/v1" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -78,6 +84,21 @@ func defaultIdentityAwareProxyAdminCallOptions() *IdentityAwareProxyAdminCallOpt } } +func defaultIdentityAwareProxyAdminRESTCallOptions() *IdentityAwareProxyAdminCallOptions { + return &IdentityAwareProxyAdminCallOptions{ + SetIamPolicy: []gax.CallOption{}, + GetIamPolicy: []gax.CallOption{}, + TestIamPermissions: []gax.CallOption{}, + GetIapSettings: []gax.CallOption{}, + UpdateIapSettings: []gax.CallOption{}, + ListTunnelDestGroups: []gax.CallOption{}, + CreateTunnelDestGroup: []gax.CallOption{}, + GetTunnelDestGroup: []gax.CallOption{}, + DeleteTunnelDestGroup: []gax.CallOption{}, + UpdateTunnelDestGroup: []gax.CallOption{}, + } +} + // internalIdentityAwareProxyAdminClient is an interface that defines the methods available from Cloud Identity-Aware Proxy API. type internalIdentityAwareProxyAdminClient interface { Close() error @@ -273,6 +294,74 @@ func (c *identityAwareProxyAdminGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type identityAwareProxyAdminRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing IdentityAwareProxyAdminClient + CallOptions **IdentityAwareProxyAdminCallOptions +} + +// NewIdentityAwareProxyAdminRESTClient creates a new identity aware proxy admin service rest client. +// +// APIs for Identity-Aware Proxy Admin configurations. +func NewIdentityAwareProxyAdminRESTClient(ctx context.Context, opts ...option.ClientOption) (*IdentityAwareProxyAdminClient, error) { + clientOpts := append(defaultIdentityAwareProxyAdminRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultIdentityAwareProxyAdminRESTCallOptions() + c := &identityAwareProxyAdminRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &IdentityAwareProxyAdminClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultIdentityAwareProxyAdminRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://iap.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://iap.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://iap.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *identityAwareProxyAdminRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *identityAwareProxyAdminRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *identityAwareProxyAdminRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *identityAwareProxyAdminGRPCClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) @@ -512,6 +601,664 @@ func (c *identityAwareProxyAdminGRPCClient) UpdateTunnelDestGroup(ctx context.Co return resp, nil } +// SetIamPolicy sets the access control policy for an Identity-Aware Proxy protected +// resource. Replaces any existing policy. +// More information about managing access via IAP can be found at: +// https://cloud.google.com/iap/docs/managing-access#managing_access_via_the_api (at https://cloud.google.com/iap/docs/managing-access#managing_access_via_the_api) +func (c *identityAwareProxyAdminRESTClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:setIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetIamPolicy gets the access control policy for an Identity-Aware Proxy protected +// resource. +// More information about managing access via IAP can be found at: +// https://cloud.google.com/iap/docs/managing-access#managing_access_via_the_api (at https://cloud.google.com/iap/docs/managing-access#managing_access_via_the_api) +func (c *identityAwareProxyAdminRESTClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:getIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// TestIamPermissions returns permissions that a caller has on the Identity-Aware Proxy protected +// resource. +// More information about managing access via IAP can be found at: +// https://cloud.google.com/iap/docs/managing-access#managing_access_via_the_api (at https://cloud.google.com/iap/docs/managing-access#managing_access_via_the_api) +func (c *identityAwareProxyAdminRESTClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:testIamPermissions", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.TestIamPermissionsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetIapSettings gets the IAP settings on a particular IAP protected resource. +func (c *identityAwareProxyAdminRESTClient) GetIapSettings(ctx context.Context, req *iappb.GetIapSettingsRequest, opts ...gax.CallOption) (*iappb.IapSettings, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:iapSettings", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetIapSettings[0:len((*c.CallOptions).GetIapSettings):len((*c.CallOptions).GetIapSettings)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iappb.IapSettings{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateIapSettings updates the IAP settings on a particular IAP protected resource. It +// replaces all fields unless the update_mask is set. +func (c *identityAwareProxyAdminRESTClient) UpdateIapSettings(ctx context.Context, req *iappb.UpdateIapSettingsRequest, opts ...gax.CallOption) (*iappb.IapSettings, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetIapSettings() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:iapSettings", req.GetIapSettings().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "iap_settings.name", url.QueryEscape(req.GetIapSettings().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateIapSettings[0:len((*c.CallOptions).UpdateIapSettings):len((*c.CallOptions).UpdateIapSettings)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iappb.IapSettings{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListTunnelDestGroups lists the existing TunnelDestGroups. To group across all locations, use a +// - as the location ID. For example: +// /v1/projects/123/iap_tunnel/locations/-/destGroups +func (c *identityAwareProxyAdminRESTClient) ListTunnelDestGroups(ctx context.Context, req *iappb.ListTunnelDestGroupsRequest, opts ...gax.CallOption) *TunnelDestGroupIterator { + it := &TunnelDestGroupIterator{} + req = proto.Clone(req).(*iappb.ListTunnelDestGroupsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*iappb.TunnelDestGroup, string, error) { + resp := &iappb.ListTunnelDestGroupsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/destGroups", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetTunnelDestGroups(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CreateTunnelDestGroup creates a new TunnelDestGroup. +func (c *identityAwareProxyAdminRESTClient) CreateTunnelDestGroup(ctx context.Context, req *iappb.CreateTunnelDestGroupRequest, opts ...gax.CallOption) (*iappb.TunnelDestGroup, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetTunnelDestGroup() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/destGroups", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("tunnelDestGroupId", fmt.Sprintf("%v", req.GetTunnelDestGroupId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateTunnelDestGroup[0:len((*c.CallOptions).CreateTunnelDestGroup):len((*c.CallOptions).CreateTunnelDestGroup)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iappb.TunnelDestGroup{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetTunnelDestGroup retrieves an existing TunnelDestGroup. +func (c *identityAwareProxyAdminRESTClient) GetTunnelDestGroup(ctx context.Context, req *iappb.GetTunnelDestGroupRequest, opts ...gax.CallOption) (*iappb.TunnelDestGroup, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetTunnelDestGroup[0:len((*c.CallOptions).GetTunnelDestGroup):len((*c.CallOptions).GetTunnelDestGroup)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iappb.TunnelDestGroup{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteTunnelDestGroup deletes a TunnelDestGroup. +func (c *identityAwareProxyAdminRESTClient) DeleteTunnelDestGroup(ctx context.Context, req *iappb.DeleteTunnelDestGroupRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// UpdateTunnelDestGroup updates a TunnelDestGroup. +func (c *identityAwareProxyAdminRESTClient) UpdateTunnelDestGroup(ctx context.Context, req *iappb.UpdateTunnelDestGroupRequest, opts ...gax.CallOption) (*iappb.TunnelDestGroup, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetTunnelDestGroup() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetTunnelDestGroup().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "tunnel_dest_group.name", url.QueryEscape(req.GetTunnelDestGroup().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateTunnelDestGroup[0:len((*c.CallOptions).UpdateTunnelDestGroup):len((*c.CallOptions).UpdateTunnelDestGroup)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iappb.TunnelDestGroup{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + // TunnelDestGroupIterator manages a stream of *iappb.TunnelDestGroup. type TunnelDestGroupIterator struct { items []*iappb.TunnelDestGroup diff --git a/iap/apiv1/identity_aware_proxy_admin_client_example_test.go b/iap/apiv1/identity_aware_proxy_admin_client_example_test.go index de2596e5145c..379147fe06b8 100644 --- a/iap/apiv1/identity_aware_proxy_admin_client_example_test.go +++ b/iap/apiv1/identity_aware_proxy_admin_client_example_test.go @@ -42,6 +42,23 @@ func ExampleNewIdentityAwareProxyAdminClient() { _ = c } +func ExampleNewIdentityAwareProxyAdminRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := iap.NewIdentityAwareProxyAdminRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleIdentityAwareProxyAdminClient_SetIamPolicy() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/iap/apiv1/identity_aware_proxyo_auth_client.go b/iap/apiv1/identity_aware_proxyo_auth_client.go index 3d801f713ff7..c77723082929 100644 --- a/iap/apiv1/identity_aware_proxyo_auth_client.go +++ b/iap/apiv1/identity_aware_proxyo_auth_client.go @@ -17,20 +17,26 @@ package iap import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" iappb "cloud.google.com/go/iap/apiv1/iappb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -73,6 +79,19 @@ func defaultIdentityAwareProxyOAuthCallOptions() *IdentityAwareProxyOAuthCallOpt } } +func defaultIdentityAwareProxyOAuthRESTCallOptions() *IdentityAwareProxyOAuthCallOptions { + return &IdentityAwareProxyOAuthCallOptions{ + ListBrands: []gax.CallOption{}, + CreateBrand: []gax.CallOption{}, + GetBrand: []gax.CallOption{}, + CreateIdentityAwareProxyClient: []gax.CallOption{}, + ListIdentityAwareProxyClients: []gax.CallOption{}, + GetIdentityAwareProxyClient: []gax.CallOption{}, + ResetIdentityAwareProxyClientSecret: []gax.CallOption{}, + DeleteIdentityAwareProxyClient: []gax.CallOption{}, + } +} + // internalIdentityAwareProxyOAuthClient is an interface that defines the methods available from Cloud Identity-Aware Proxy API. type internalIdentityAwareProxyOAuthClient interface { Close() error @@ -261,6 +280,76 @@ func (c *identityAwareProxyOAuthGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type identityAwareProxyOAuthRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing IdentityAwareProxyOAuthClient + CallOptions **IdentityAwareProxyOAuthCallOptions +} + +// NewIdentityAwareProxyOAuthRESTClient creates a new identity aware proxyo auth service rest client. +// +// API to programmatically create, list and retrieve Identity Aware Proxy (IAP) +// OAuth brands; and create, retrieve, delete and reset-secret of IAP OAuth +// clients. +func NewIdentityAwareProxyOAuthRESTClient(ctx context.Context, opts ...option.ClientOption) (*IdentityAwareProxyOAuthClient, error) { + clientOpts := append(defaultIdentityAwareProxyOAuthRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultIdentityAwareProxyOAuthRESTCallOptions() + c := &identityAwareProxyOAuthRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &IdentityAwareProxyOAuthClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultIdentityAwareProxyOAuthRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://iap.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://iap.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://iap.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *identityAwareProxyOAuthRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *identityAwareProxyOAuthRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *identityAwareProxyOAuthRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *identityAwareProxyOAuthGRPCClient) ListBrands(ctx context.Context, req *iappb.ListBrandsRequest, opts ...gax.CallOption) (*iappb.ListBrandsResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) @@ -456,6 +545,515 @@ func (c *identityAwareProxyOAuthGRPCClient) DeleteIdentityAwareProxyClient(ctx c return err } +// ListBrands lists the existing brands for the project. +func (c *identityAwareProxyOAuthRESTClient) ListBrands(ctx context.Context, req *iappb.ListBrandsRequest, opts ...gax.CallOption) (*iappb.ListBrandsResponse, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/brands", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).ListBrands[0:len((*c.CallOptions).ListBrands):len((*c.CallOptions).ListBrands)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iappb.ListBrandsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateBrand constructs a new OAuth brand for the project if one does not exist. +// The created brand is “internal only”, meaning that OAuth clients created +// under it only accept requests from users who belong to the same Google +// Workspace organization as the project. The brand is created in an +// un-reviewed status. NOTE: The “internal only” status can be manually +// changed in the Google Cloud Console. Requires that a brand does not already +// exist for the project, and that the specified support email is owned by the +// caller. +func (c *identityAwareProxyOAuthRESTClient) CreateBrand(ctx context.Context, req *iappb.CreateBrandRequest, opts ...gax.CallOption) (*iappb.Brand, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetBrand() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/brands", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateBrand[0:len((*c.CallOptions).CreateBrand):len((*c.CallOptions).CreateBrand)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iappb.Brand{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetBrand retrieves the OAuth brand of the project. +func (c *identityAwareProxyOAuthRESTClient) GetBrand(ctx context.Context, req *iappb.GetBrandRequest, opts ...gax.CallOption) (*iappb.Brand, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetBrand[0:len((*c.CallOptions).GetBrand):len((*c.CallOptions).GetBrand)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iappb.Brand{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateIdentityAwareProxyClient creates an Identity Aware Proxy (IAP) OAuth client. The client is owned +// by IAP. Requires that the brand for the project exists and that it is +// set for internal-only use. +func (c *identityAwareProxyOAuthRESTClient) CreateIdentityAwareProxyClient(ctx context.Context, req *iappb.CreateIdentityAwareProxyClientRequest, opts ...gax.CallOption) (*iappb.IdentityAwareProxyClient, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetIdentityAwareProxyClient() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/identityAwareProxyClients", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateIdentityAwareProxyClient[0:len((*c.CallOptions).CreateIdentityAwareProxyClient):len((*c.CallOptions).CreateIdentityAwareProxyClient)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iappb.IdentityAwareProxyClient{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListIdentityAwareProxyClients lists the existing clients for the brand. +func (c *identityAwareProxyOAuthRESTClient) ListIdentityAwareProxyClients(ctx context.Context, req *iappb.ListIdentityAwareProxyClientsRequest, opts ...gax.CallOption) *IdentityAwareProxyClientIterator { + it := &IdentityAwareProxyClientIterator{} + req = proto.Clone(req).(*iappb.ListIdentityAwareProxyClientsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*iappb.IdentityAwareProxyClient, string, error) { + resp := &iappb.ListIdentityAwareProxyClientsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/identityAwareProxyClients", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetIdentityAwareProxyClients(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetIdentityAwareProxyClient retrieves an Identity Aware Proxy (IAP) OAuth client. +// Requires that the client is owned by IAP. +func (c *identityAwareProxyOAuthRESTClient) GetIdentityAwareProxyClient(ctx context.Context, req *iappb.GetIdentityAwareProxyClientRequest, opts ...gax.CallOption) (*iappb.IdentityAwareProxyClient, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetIdentityAwareProxyClient[0:len((*c.CallOptions).GetIdentityAwareProxyClient):len((*c.CallOptions).GetIdentityAwareProxyClient)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iappb.IdentityAwareProxyClient{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ResetIdentityAwareProxyClientSecret resets an Identity Aware Proxy (IAP) OAuth client secret. Useful if the +// secret was compromised. Requires that the client is owned by IAP. +func (c *identityAwareProxyOAuthRESTClient) ResetIdentityAwareProxyClientSecret(ctx context.Context, req *iappb.ResetIdentityAwareProxyClientSecretRequest, opts ...gax.CallOption) (*iappb.IdentityAwareProxyClient, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:resetSecret", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).ResetIdentityAwareProxyClientSecret[0:len((*c.CallOptions).ResetIdentityAwareProxyClientSecret):len((*c.CallOptions).ResetIdentityAwareProxyClientSecret)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iappb.IdentityAwareProxyClient{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteIdentityAwareProxyClient deletes an Identity Aware Proxy (IAP) OAuth client. Useful for removing +// obsolete clients, managing the number of clients in a given project, and +// cleaning up after tests. Requires that the client is owned by IAP. +func (c *identityAwareProxyOAuthRESTClient) DeleteIdentityAwareProxyClient(ctx context.Context, req *iappb.DeleteIdentityAwareProxyClientRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + // IdentityAwareProxyClientIterator manages a stream of *iappb.IdentityAwareProxyClient. type IdentityAwareProxyClientIterator struct { items []*iappb.IdentityAwareProxyClient diff --git a/iap/apiv1/identity_aware_proxyo_auth_client_example_test.go b/iap/apiv1/identity_aware_proxyo_auth_client_example_test.go index 21130d4cd1db..81ef94002f1d 100644 --- a/iap/apiv1/identity_aware_proxyo_auth_client_example_test.go +++ b/iap/apiv1/identity_aware_proxyo_auth_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewIdentityAwareProxyOAuthClient() { _ = c } +func ExampleNewIdentityAwareProxyOAuthRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := iap.NewIdentityAwareProxyOAuthRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleIdentityAwareProxyOAuthClient_ListBrands() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/ids/apiv1/doc.go b/ids/apiv1/doc.go index 2ac365f1f482..9678461bde27 100644 --- a/ids/apiv1/doc.go +++ b/ids/apiv1/doc.go @@ -90,6 +90,8 @@ package ids // import "cloud.google.com/go/ids/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -178,3 +180,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/ids/apiv1/gapic_metadata.json b/ids/apiv1/gapic_metadata.json index 99673a7c6df3..fda0583649a6 100644 --- a/ids/apiv1/gapic_metadata.json +++ b/ids/apiv1/gapic_metadata.json @@ -31,6 +31,31 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "CreateEndpoint": { + "methods": [ + "CreateEndpoint" + ] + }, + "DeleteEndpoint": { + "methods": [ + "DeleteEndpoint" + ] + }, + "GetEndpoint": { + "methods": [ + "GetEndpoint" + ] + }, + "ListEndpoints": { + "methods": [ + "ListEndpoints" + ] + } + } } } } diff --git a/ids/apiv1/ids_client.go b/ids/apiv1/ids_client.go index 8de3277d2b5f..d8740b3db5dc 100644 --- a/ids/apiv1/ids_client.go +++ b/ids/apiv1/ids_client.go @@ -17,9 +17,12 @@ package ids import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,14 +30,17 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -89,6 +95,33 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + ListEndpoints: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 250 * time.Millisecond, + Max: 32000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetEndpoint: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 250 * time.Millisecond, + Max: 32000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateEndpoint: []gax.CallOption{}, + DeleteEndpoint: []gax.CallOption{}, + } +} + // internalClient is an interface that defines the methods available from Cloud IDS API. type internalClient interface { Close() error @@ -271,6 +304,89 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new ids rest client. +// +// The IDS Service +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://ids.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://ids.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://ids.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) ListEndpoints(ctx context.Context, req *idspb.ListEndpointsRequest, opts ...gax.CallOption) *EndpointIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -386,9 +502,300 @@ func (c *gRPCClient) DeleteEndpoint(ctx context.Context, req *idspb.DeleteEndpoi }, nil } +// ListEndpoints lists Endpoints in a given project and location. +func (c *restClient) ListEndpoints(ctx context.Context, req *idspb.ListEndpointsRequest, opts ...gax.CallOption) *EndpointIterator { + it := &EndpointIterator{} + req = proto.Clone(req).(*idspb.ListEndpointsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*idspb.Endpoint, string, error) { + resp := &idspb.ListEndpointsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/endpoints", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetEndpoints(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetEndpoint gets details of a single Endpoint. +func (c *restClient) GetEndpoint(ctx context.Context, req *idspb.GetEndpointRequest, opts ...gax.CallOption) (*idspb.Endpoint, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetEndpoint[0:len((*c.CallOptions).GetEndpoint):len((*c.CallOptions).GetEndpoint)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &idspb.Endpoint{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateEndpoint creates a new Endpoint in a given project and location. +func (c *restClient) CreateEndpoint(ctx context.Context, req *idspb.CreateEndpointRequest, opts ...gax.CallOption) (*CreateEndpointOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetEndpoint() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/endpoints", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("endpointId", fmt.Sprintf("%v", req.GetEndpointId())) + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateEndpointOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteEndpoint deletes a single Endpoint. +func (c *restClient) DeleteEndpoint(ctx context.Context, req *idspb.DeleteEndpointRequest, opts ...gax.CallOption) (*DeleteEndpointOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteEndpointOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + // CreateEndpointOperation manages a long-running operation from CreateEndpoint. type CreateEndpointOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateEndpointOperation returns a new CreateEndpointOperation from a given name. @@ -399,10 +806,21 @@ func (c *gRPCClient) CreateEndpointOperation(name string) *CreateEndpointOperati } } +// CreateEndpointOperation returns a new CreateEndpointOperation from a given name. +// The name must be that of a previously created CreateEndpointOperation, possibly from a different process. +func (c *restClient) CreateEndpointOperation(name string) *CreateEndpointOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateEndpointOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateEndpointOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*idspb.Endpoint, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp idspb.Endpoint if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -420,6 +838,7 @@ func (op *CreateEndpointOperation) Wait(ctx context.Context, opts ...gax.CallOpt // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateEndpointOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*idspb.Endpoint, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp idspb.Endpoint if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -457,7 +876,8 @@ func (op *CreateEndpointOperation) Name() string { // DeleteEndpointOperation manages a long-running operation from DeleteEndpoint. type DeleteEndpointOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteEndpointOperation returns a new DeleteEndpointOperation from a given name. @@ -468,10 +888,21 @@ func (c *gRPCClient) DeleteEndpointOperation(name string) *DeleteEndpointOperati } } +// DeleteEndpointOperation returns a new DeleteEndpointOperation from a given name. +// The name must be that of a previously created DeleteEndpointOperation, possibly from a different process. +func (c *restClient) DeleteEndpointOperation(name string) *DeleteEndpointOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteEndpointOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteEndpointOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -485,6 +916,7 @@ func (op *DeleteEndpointOperation) Wait(ctx context.Context, opts ...gax.CallOpt // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteEndpointOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } diff --git a/ids/apiv1/ids_client_example_test.go b/ids/apiv1/ids_client_example_test.go index 7e4397a49724..45e5f636843a 100644 --- a/ids/apiv1/ids_client_example_test.go +++ b/ids/apiv1/ids_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := ids.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_ListEndpoints() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/ids/apiv1/idspb/ids.pb.go b/ids/apiv1/idspb/ids.pb.go index bb988be5f537..fa4e5136fa96 100644 --- a/ids/apiv1/idspb/ids.pb.go +++ b/ids/apiv1/idspb/ids.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/ids/v1/ids.proto package idspb diff --git a/iot/apiv1/device_manager_client.go b/iot/apiv1/device_manager_client.go index f760c7672b07..9d7d0c30ec1b 100644 --- a/iot/apiv1/device_manager_client.go +++ b/iot/apiv1/device_manager_client.go @@ -17,22 +17,28 @@ package iot import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" iotpb "cloud.google.com/go/iot/apiv1/iotpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" iampb "google.golang.org/genproto/googleapis/iam/v1" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -209,6 +215,132 @@ func defaultDeviceManagerCallOptions() *DeviceManagerCallOptions { } } +func defaultDeviceManagerRESTCallOptions() *DeviceManagerCallOptions { + return &DeviceManagerCallOptions{ + CreateDeviceRegistry: []gax.CallOption{}, + GetDeviceRegistry: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + UpdateDeviceRegistry: []gax.CallOption{}, + DeleteDeviceRegistry: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + ListDeviceRegistries: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + CreateDevice: []gax.CallOption{}, + GetDevice: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + UpdateDevice: []gax.CallOption{}, + DeleteDevice: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + ListDevices: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + ModifyCloudToDeviceConfig: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout, + http.StatusTooManyRequests) + }), + }, + ListDeviceConfigVersions: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + ListDeviceStates: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + SetIamPolicy: []gax.CallOption{}, + GetIamPolicy: []gax.CallOption{}, + TestIamPermissions: []gax.CallOption{}, + SendCommandToDevice: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout, + http.StatusTooManyRequests) + }), + }, + BindDeviceToGateway: []gax.CallOption{}, + UnbindDeviceFromGateway: []gax.CallOption{}, + } +} + // internalDeviceManagerClient is an interface that defines the methods available from Cloud IoT API. type internalDeviceManagerClient interface { Close() error @@ -469,6 +601,74 @@ func (c *deviceManagerGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type deviceManagerRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing DeviceManagerClient + CallOptions **DeviceManagerCallOptions +} + +// NewDeviceManagerRESTClient creates a new device manager rest client. +// +// Internet of Things (IoT) service. Securely connect and manage IoT devices. +func NewDeviceManagerRESTClient(ctx context.Context, opts ...option.ClientOption) (*DeviceManagerClient, error) { + clientOpts := append(defaultDeviceManagerRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultDeviceManagerRESTCallOptions() + c := &deviceManagerRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &DeviceManagerClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultDeviceManagerRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://cloudiot.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://cloudiot.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://cloudiot.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *deviceManagerRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *deviceManagerRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *deviceManagerRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *deviceManagerGRPCClient) CreateDeviceRegistry(ctx context.Context, req *iotpb.CreateDeviceRegistryRequest, opts ...gax.CallOption) (*iotpb.DeviceRegistry, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 120000*time.Millisecond) @@ -925,6 +1125,1278 @@ func (c *deviceManagerGRPCClient) UnbindDeviceFromGateway(ctx context.Context, r return resp, nil } +// CreateDeviceRegistry creates a device registry that contains devices. +func (c *deviceManagerRESTClient) CreateDeviceRegistry(ctx context.Context, req *iotpb.CreateDeviceRegistryRequest, opts ...gax.CallOption) (*iotpb.DeviceRegistry, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetDeviceRegistry() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/registries", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateDeviceRegistry[0:len((*c.CallOptions).CreateDeviceRegistry):len((*c.CallOptions).CreateDeviceRegistry)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iotpb.DeviceRegistry{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetDeviceRegistry gets a device registry configuration. +func (c *deviceManagerRESTClient) GetDeviceRegistry(ctx context.Context, req *iotpb.GetDeviceRegistryRequest, opts ...gax.CallOption) (*iotpb.DeviceRegistry, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetDeviceRegistry[0:len((*c.CallOptions).GetDeviceRegistry):len((*c.CallOptions).GetDeviceRegistry)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iotpb.DeviceRegistry{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateDeviceRegistry updates a device registry configuration. +func (c *deviceManagerRESTClient) UpdateDeviceRegistry(ctx context.Context, req *iotpb.UpdateDeviceRegistryRequest, opts ...gax.CallOption) (*iotpb.DeviceRegistry, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetDeviceRegistry() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetDeviceRegistry().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "device_registry.name", url.QueryEscape(req.GetDeviceRegistry().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateDeviceRegistry[0:len((*c.CallOptions).UpdateDeviceRegistry):len((*c.CallOptions).UpdateDeviceRegistry)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iotpb.DeviceRegistry{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteDeviceRegistry deletes a device registry configuration. +func (c *deviceManagerRESTClient) DeleteDeviceRegistry(ctx context.Context, req *iotpb.DeleteDeviceRegistryRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// ListDeviceRegistries lists device registries. +func (c *deviceManagerRESTClient) ListDeviceRegistries(ctx context.Context, req *iotpb.ListDeviceRegistriesRequest, opts ...gax.CallOption) *DeviceRegistryIterator { + it := &DeviceRegistryIterator{} + req = proto.Clone(req).(*iotpb.ListDeviceRegistriesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*iotpb.DeviceRegistry, string, error) { + resp := &iotpb.ListDeviceRegistriesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/registries", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetDeviceRegistries(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CreateDevice creates a device in a device registry. +func (c *deviceManagerRESTClient) CreateDevice(ctx context.Context, req *iotpb.CreateDeviceRequest, opts ...gax.CallOption) (*iotpb.Device, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetDevice() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/devices", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateDevice[0:len((*c.CallOptions).CreateDevice):len((*c.CallOptions).CreateDevice)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iotpb.Device{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetDevice gets details about a device. +func (c *deviceManagerRESTClient) GetDevice(ctx context.Context, req *iotpb.GetDeviceRequest, opts ...gax.CallOption) (*iotpb.Device, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFieldMask() != nil { + fieldMask, err := protojson.Marshal(req.GetFieldMask()) + if err != nil { + return nil, err + } + params.Add("fieldMask", string(fieldMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetDevice[0:len((*c.CallOptions).GetDevice):len((*c.CallOptions).GetDevice)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iotpb.Device{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateDevice updates a device. +func (c *deviceManagerRESTClient) UpdateDevice(ctx context.Context, req *iotpb.UpdateDeviceRequest, opts ...gax.CallOption) (*iotpb.Device, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetDevice() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetDevice().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "device.name", url.QueryEscape(req.GetDevice().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateDevice[0:len((*c.CallOptions).UpdateDevice):len((*c.CallOptions).UpdateDevice)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iotpb.Device{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteDevice deletes a device. +func (c *deviceManagerRESTClient) DeleteDevice(ctx context.Context, req *iotpb.DeleteDeviceRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// ListDevices list devices in a device registry. +func (c *deviceManagerRESTClient) ListDevices(ctx context.Context, req *iotpb.ListDevicesRequest, opts ...gax.CallOption) *DeviceIterator { + it := &DeviceIterator{} + req = proto.Clone(req).(*iotpb.ListDevicesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*iotpb.Device, string, error) { + resp := &iotpb.ListDevicesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/devices", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if items := req.GetDeviceIds(); len(items) > 0 { + for _, item := range items { + params.Add("deviceIds", fmt.Sprintf("%v", item)) + } + } + if items := req.GetDeviceNumIds(); len(items) > 0 { + for _, item := range items { + params.Add("deviceNumIds", fmt.Sprintf("%v", item)) + } + } + if req.GetFieldMask() != nil { + fieldMask, err := protojson.Marshal(req.GetFieldMask()) + if err != nil { + return nil, "", err + } + params.Add("fieldMask", string(fieldMask)) + } + if req.GetGatewayListOptions().GetAssociationsDeviceId() != "" { + params.Add("gatewayListOptions.associationsDeviceId", fmt.Sprintf("%v", req.GetGatewayListOptions().GetAssociationsDeviceId())) + } + if req.GetGatewayListOptions().GetAssociationsGatewayId() != "" { + params.Add("gatewayListOptions.associationsGatewayId", fmt.Sprintf("%v", req.GetGatewayListOptions().GetAssociationsGatewayId())) + } + if req.GetGatewayListOptions().GetGatewayType() != 0 { + params.Add("gatewayListOptions.gatewayType", fmt.Sprintf("%v", req.GetGatewayListOptions().GetGatewayType())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetDevices(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// ModifyCloudToDeviceConfig modifies the configuration for the device, which is eventually sent from +// the Cloud IoT Core servers. Returns the modified configuration version and +// its metadata. +func (c *deviceManagerRESTClient) ModifyCloudToDeviceConfig(ctx context.Context, req *iotpb.ModifyCloudToDeviceConfigRequest, opts ...gax.CallOption) (*iotpb.DeviceConfig, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:modifyCloudToDeviceConfig", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).ModifyCloudToDeviceConfig[0:len((*c.CallOptions).ModifyCloudToDeviceConfig):len((*c.CallOptions).ModifyCloudToDeviceConfig)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iotpb.DeviceConfig{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListDeviceConfigVersions lists the last few versions of the device configuration in descending +// order (i.e.: newest first). +func (c *deviceManagerRESTClient) ListDeviceConfigVersions(ctx context.Context, req *iotpb.ListDeviceConfigVersionsRequest, opts ...gax.CallOption) (*iotpb.ListDeviceConfigVersionsResponse, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/configVersions", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetNumVersions() != 0 { + params.Add("numVersions", fmt.Sprintf("%v", req.GetNumVersions())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).ListDeviceConfigVersions[0:len((*c.CallOptions).ListDeviceConfigVersions):len((*c.CallOptions).ListDeviceConfigVersions)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iotpb.ListDeviceConfigVersionsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListDeviceStates lists the last few versions of the device state in descending order (i.e.: +// newest first). +func (c *deviceManagerRESTClient) ListDeviceStates(ctx context.Context, req *iotpb.ListDeviceStatesRequest, opts ...gax.CallOption) (*iotpb.ListDeviceStatesResponse, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/states", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetNumStates() != 0 { + params.Add("numStates", fmt.Sprintf("%v", req.GetNumStates())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).ListDeviceStates[0:len((*c.CallOptions).ListDeviceStates):len((*c.CallOptions).ListDeviceStates)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iotpb.ListDeviceStatesResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SetIamPolicy sets the access control policy on the specified resource. Replaces any +// existing policy. +func (c *deviceManagerRESTClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:setIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetIamPolicy gets the access control policy for a resource. +// Returns an empty policy if the resource exists and does not have a policy +// set. +func (c *deviceManagerRESTClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:getIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// TestIamPermissions returns permissions that a caller has on the specified resource. +// If the resource does not exist, this will return an empty set of +// permissions, not a NOT_FOUND error. +func (c *deviceManagerRESTClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:testIamPermissions", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.TestIamPermissionsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SendCommandToDevice sends a command to the specified device. In order for a device to be able +// to receive commands, it must: +// +// be connected to Cloud IoT Core using the MQTT protocol, and +// +// be subscribed to the group of MQTT topics specified by +// /devices/{device-id}/commands/#. This subscription will receive commands +// at the top-level topic /devices/{device-id}/commands as well as commands +// for subfolders, like /devices/{device-id}/commands/subfolder. +// Note that subscribing to specific subfolders is not supported. +// If the command could not be delivered to the device, this method will +// return an error; in particular, if the device is not subscribed, this +// method will return FAILED_PRECONDITION. Otherwise, this method will +// return OK. If the subscription is QoS 1, at least once delivery will be +// guaranteed; for QoS 0, no acknowledgment will be expected from the device. +func (c *deviceManagerRESTClient) SendCommandToDevice(ctx context.Context, req *iotpb.SendCommandToDeviceRequest, opts ...gax.CallOption) (*iotpb.SendCommandToDeviceResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:sendCommandToDevice", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SendCommandToDevice[0:len((*c.CallOptions).SendCommandToDevice):len((*c.CallOptions).SendCommandToDevice)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iotpb.SendCommandToDeviceResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// BindDeviceToGateway associates the device with the gateway. +func (c *deviceManagerRESTClient) BindDeviceToGateway(ctx context.Context, req *iotpb.BindDeviceToGatewayRequest, opts ...gax.CallOption) (*iotpb.BindDeviceToGatewayResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:bindDeviceToGateway", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).BindDeviceToGateway[0:len((*c.CallOptions).BindDeviceToGateway):len((*c.CallOptions).BindDeviceToGateway)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iotpb.BindDeviceToGatewayResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UnbindDeviceFromGateway deletes the association between the device and the gateway. +func (c *deviceManagerRESTClient) UnbindDeviceFromGateway(ctx context.Context, req *iotpb.UnbindDeviceFromGatewayRequest, opts ...gax.CallOption) (*iotpb.UnbindDeviceFromGatewayResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:unbindDeviceFromGateway", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UnbindDeviceFromGateway[0:len((*c.CallOptions).UnbindDeviceFromGateway):len((*c.CallOptions).UnbindDeviceFromGateway)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iotpb.UnbindDeviceFromGatewayResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + // DeviceIterator manages a stream of *iotpb.Device. type DeviceIterator struct { items []*iotpb.Device diff --git a/iot/apiv1/device_manager_client_example_test.go b/iot/apiv1/device_manager_client_example_test.go index 690e02aa24fd..bb1a82105a25 100644 --- a/iot/apiv1/device_manager_client_example_test.go +++ b/iot/apiv1/device_manager_client_example_test.go @@ -42,6 +42,23 @@ func ExampleNewDeviceManagerClient() { _ = c } +func ExampleNewDeviceManagerRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := iot.NewDeviceManagerRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleDeviceManagerClient_CreateDeviceRegistry() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/iot/apiv1/doc.go b/iot/apiv1/doc.go index 22b8bdfe16d2..31692d7abcbb 100644 --- a/iot/apiv1/doc.go +++ b/iot/apiv1/doc.go @@ -81,6 +81,8 @@ package iot // import "cloud.google.com/go/iot/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -170,3 +172,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/iot/apiv1/gapic_metadata.json b/iot/apiv1/gapic_metadata.json index 75dfb965b17b..ec497533ae7c 100644 --- a/iot/apiv1/gapic_metadata.json +++ b/iot/apiv1/gapic_metadata.json @@ -106,6 +106,106 @@ ] } } + }, + "rest": { + "libraryClient": "DeviceManagerClient", + "rpcs": { + "BindDeviceToGateway": { + "methods": [ + "BindDeviceToGateway" + ] + }, + "CreateDevice": { + "methods": [ + "CreateDevice" + ] + }, + "CreateDeviceRegistry": { + "methods": [ + "CreateDeviceRegistry" + ] + }, + "DeleteDevice": { + "methods": [ + "DeleteDevice" + ] + }, + "DeleteDeviceRegistry": { + "methods": [ + "DeleteDeviceRegistry" + ] + }, + "GetDevice": { + "methods": [ + "GetDevice" + ] + }, + "GetDeviceRegistry": { + "methods": [ + "GetDeviceRegistry" + ] + }, + "GetIamPolicy": { + "methods": [ + "GetIamPolicy" + ] + }, + "ListDeviceConfigVersions": { + "methods": [ + "ListDeviceConfigVersions" + ] + }, + "ListDeviceRegistries": { + "methods": [ + "ListDeviceRegistries" + ] + }, + "ListDeviceStates": { + "methods": [ + "ListDeviceStates" + ] + }, + "ListDevices": { + "methods": [ + "ListDevices" + ] + }, + "ModifyCloudToDeviceConfig": { + "methods": [ + "ModifyCloudToDeviceConfig" + ] + }, + "SendCommandToDevice": { + "methods": [ + "SendCommandToDevice" + ] + }, + "SetIamPolicy": { + "methods": [ + "SetIamPolicy" + ] + }, + "TestIamPermissions": { + "methods": [ + "TestIamPermissions" + ] + }, + "UnbindDeviceFromGateway": { + "methods": [ + "UnbindDeviceFromGateway" + ] + }, + "UpdateDevice": { + "methods": [ + "UpdateDevice" + ] + }, + "UpdateDeviceRegistry": { + "methods": [ + "UpdateDeviceRegistry" + ] + } + } } } } diff --git a/iot/apiv1/iotpb/device_manager.pb.go b/iot/apiv1/iotpb/device_manager.pb.go index dc18720fedf5..892b5f3a7449 100644 --- a/iot/apiv1/iotpb/device_manager.pb.go +++ b/iot/apiv1/iotpb/device_manager.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/iot/v1/device_manager.proto package iotpb @@ -764,7 +764,6 @@ type GatewayListOptions struct { // filtered based on gateway type and associations. // // Types that are assignable to Filter: - // // *GatewayListOptions_GatewayType // *GatewayListOptions_AssociationsGatewayId // *GatewayListOptions_AssociationsDeviceId @@ -2587,13 +2586,12 @@ type DeviceManagerClient interface { TestIamPermissions(ctx context.Context, in *v1.TestIamPermissionsRequest, opts ...grpc.CallOption) (*v1.TestIamPermissionsResponse, error) // Sends a command to the specified device. In order for a device to be able // to receive commands, it must: - // 1. be connected to Cloud IoT Core using the MQTT protocol, and - // 2. be subscribed to the group of MQTT topics specified by - // /devices/{device-id}/commands/#. This subscription will receive commands - // at the top-level topic /devices/{device-id}/commands as well as commands - // for subfolders, like /devices/{device-id}/commands/subfolder. - // Note that subscribing to specific subfolders is not supported. - // + // 1) be connected to Cloud IoT Core using the MQTT protocol, and + // 2) be subscribed to the group of MQTT topics specified by + // /devices/{device-id}/commands/#. This subscription will receive commands + // at the top-level topic /devices/{device-id}/commands as well as commands + // for subfolders, like /devices/{device-id}/commands/subfolder. + // Note that subscribing to specific subfolders is not supported. // If the command could not be delivered to the device, this method will // return an error; in particular, if the device is not subscribed, this // method will return FAILED_PRECONDITION. Otherwise, this method will @@ -2830,13 +2828,12 @@ type DeviceManagerServer interface { TestIamPermissions(context.Context, *v1.TestIamPermissionsRequest) (*v1.TestIamPermissionsResponse, error) // Sends a command to the specified device. In order for a device to be able // to receive commands, it must: - // 1. be connected to Cloud IoT Core using the MQTT protocol, and - // 2. be subscribed to the group of MQTT topics specified by - // /devices/{device-id}/commands/#. This subscription will receive commands - // at the top-level topic /devices/{device-id}/commands as well as commands - // for subfolders, like /devices/{device-id}/commands/subfolder. - // Note that subscribing to specific subfolders is not supported. - // + // 1) be connected to Cloud IoT Core using the MQTT protocol, and + // 2) be subscribed to the group of MQTT topics specified by + // /devices/{device-id}/commands/#. This subscription will receive commands + // at the top-level topic /devices/{device-id}/commands as well as commands + // for subfolders, like /devices/{device-id}/commands/subfolder. + // Note that subscribing to specific subfolders is not supported. // If the command could not be delivered to the device, this method will // return an error; in particular, if the device is not subscribed, this // method will return FAILED_PRECONDITION. Otherwise, this method will diff --git a/iot/apiv1/iotpb/resources.pb.go b/iot/apiv1/iotpb/resources.pb.go index 3f28c6cea978..e0f3a7954626 100644 --- a/iot/apiv1/iotpb/resources.pb.go +++ b/iot/apiv1/iotpb/resources.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/iot/v1/resources.proto package iotpb @@ -1135,7 +1135,6 @@ type RegistryCredential struct { // The credential data. Reserved for expansion in the future. // // Types that are assignable to Credential: - // // *RegistryCredential_PublicKeyCertificate Credential isRegistryCredential_Credential `protobuf_oneof:"credential"` } @@ -1367,7 +1366,6 @@ type DeviceCredential struct { // The credential data. Reserved for expansion in the future. // // Types that are assignable to Credential: - // // *DeviceCredential_PublicKey Credential isDeviceCredential_Credential `protobuf_oneof:"credential"` // [Optional] The time at which this credential becomes invalid. This diff --git a/kms/apiv1/doc.go b/kms/apiv1/doc.go index 53d50e6a50bf..a5358824147b 100644 --- a/kms/apiv1/doc.go +++ b/kms/apiv1/doc.go @@ -87,6 +87,8 @@ package kms // import "cloud.google.com/go/kms/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -176,3 +178,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/kms/apiv1/ekm_client.go b/kms/apiv1/ekm_client.go index e4f37f767fb1..dab6bbcf680a 100644 --- a/kms/apiv1/ekm_client.go +++ b/kms/apiv1/ekm_client.go @@ -17,23 +17,29 @@ package kms import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" kmspb "cloud.google.com/go/kms/apiv1/kmspb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" iampb "google.golang.org/genproto/googleapis/iam/v1" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -122,6 +128,60 @@ func defaultEkmCallOptions() *EkmCallOptions { } } +func defaultEkmRESTCallOptions() *EkmCallOptions { + return &EkmCallOptions{ + ListEkmConnections: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + GetEkmConnection: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + CreateEkmConnection: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + UpdateEkmConnection: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + GetIamPolicy: []gax.CallOption{}, + SetIamPolicy: []gax.CallOption{}, + TestIamPermissions: []gax.CallOption{}, + } +} + // internalEkmClient is an interface that defines the methods available from Cloud Key Management Service (KMS) API. type internalEkmClient interface { Close() error @@ -328,6 +388,79 @@ func (c *ekmGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type ekmRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing EkmClient + CallOptions **EkmCallOptions +} + +// NewEkmRESTClient creates a new ekm service rest client. +// +// # Google Cloud Key Management EKM Service +// +// Manages external cryptographic keys and operations using those keys. +// Implements a REST model with the following objects: +// +// EkmConnection +func NewEkmRESTClient(ctx context.Context, opts ...option.ClientOption) (*EkmClient, error) { + clientOpts := append(defaultEkmRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultEkmRESTCallOptions() + c := &ekmRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &EkmClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultEkmRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://cloudkms.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://cloudkms.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://cloudkms.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *ekmRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *ekmRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *ekmRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *ekmGRPCClient) ListEkmConnections(ctx context.Context, req *kmspb.ListEkmConnectionsRequest, opts ...gax.CallOption) *EkmConnectionIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -552,6 +685,647 @@ func (c *ekmGRPCClient) TestIamPermissions(ctx context.Context, req *iampb.TestI return resp, nil } +// ListEkmConnections lists EkmConnections. +func (c *ekmRESTClient) ListEkmConnections(ctx context.Context, req *kmspb.ListEkmConnectionsRequest, opts ...gax.CallOption) *EkmConnectionIterator { + it := &EkmConnectionIterator{} + req = proto.Clone(req).(*kmspb.ListEkmConnectionsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*kmspb.EkmConnection, string, error) { + resp := &kmspb.ListEkmConnectionsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/ekmConnections", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetEkmConnections(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetEkmConnection returns metadata for a given +// EkmConnection. +func (c *ekmRESTClient) GetEkmConnection(ctx context.Context, req *kmspb.GetEkmConnectionRequest, opts ...gax.CallOption) (*kmspb.EkmConnection, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetEkmConnection[0:len((*c.CallOptions).GetEkmConnection):len((*c.CallOptions).GetEkmConnection)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &kmspb.EkmConnection{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateEkmConnection creates a new EkmConnection in a given +// Project and Location. +func (c *ekmRESTClient) CreateEkmConnection(ctx context.Context, req *kmspb.CreateEkmConnectionRequest, opts ...gax.CallOption) (*kmspb.EkmConnection, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetEkmConnection() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/ekmConnections", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("ekmConnectionId", fmt.Sprintf("%v", req.GetEkmConnectionId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateEkmConnection[0:len((*c.CallOptions).CreateEkmConnection):len((*c.CallOptions).CreateEkmConnection)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &kmspb.EkmConnection{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateEkmConnection updates an EkmConnection's metadata. +func (c *ekmRESTClient) UpdateEkmConnection(ctx context.Context, req *kmspb.UpdateEkmConnectionRequest, opts ...gax.CallOption) (*kmspb.EkmConnection, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetEkmConnection() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetEkmConnection().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "ekm_connection.name", url.QueryEscape(req.GetEkmConnection().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateEkmConnection[0:len((*c.CallOptions).UpdateEkmConnection):len((*c.CallOptions).UpdateEkmConnection)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &kmspb.EkmConnection{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetLocation gets information about a location. +func (c *ekmRESTClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *ekmRESTClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetIamPolicy gets the access control policy for a resource. Returns an empty policy +// if the resource exists and does not have a policy set. +func (c *ekmRESTClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:getIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetOptions().GetRequestedPolicyVersion() != 0 { + params.Add("options.requestedPolicyVersion", fmt.Sprintf("%v", req.GetOptions().GetRequestedPolicyVersion())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SetIamPolicy sets the access control policy on the specified resource. Replaces +// any existing policy. +// +// Can return NOT_FOUND, INVALID_ARGUMENT, and PERMISSION_DENIED +// errors. +func (c *ekmRESTClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:setIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// TestIamPermissions returns permissions that a caller has on the specified resource. If the +// resource does not exist, this will return an empty set of +// permissions, not a NOT_FOUND error. +// +// Note: This operation is designed to be used for building +// permission-aware UIs and command-line tools, not for authorization +// checking. This operation may “fail open” without warning. +func (c *ekmRESTClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:testIamPermissions", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.TestIamPermissionsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + // EkmConnectionIterator manages a stream of *kmspb.EkmConnection. type EkmConnectionIterator struct { items []*kmspb.EkmConnection diff --git a/kms/apiv1/ekm_client_example_test.go b/kms/apiv1/ekm_client_example_test.go index c5a011d26250..9e530133ab8b 100644 --- a/kms/apiv1/ekm_client_example_test.go +++ b/kms/apiv1/ekm_client_example_test.go @@ -43,6 +43,23 @@ func ExampleNewEkmClient() { _ = c } +func ExampleNewEkmRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := kms.NewEkmRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleEkmClient_ListEkmConnections() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/kms/apiv1/gapic_metadata.json b/kms/apiv1/gapic_metadata.json index 5b9024e715fa..a45d004129cb 100644 --- a/kms/apiv1/gapic_metadata.json +++ b/kms/apiv1/gapic_metadata.json @@ -56,6 +56,56 @@ ] } } + }, + "rest": { + "libraryClient": "EkmClient", + "rpcs": { + "CreateEkmConnection": { + "methods": [ + "CreateEkmConnection" + ] + }, + "GetEkmConnection": { + "methods": [ + "GetEkmConnection" + ] + }, + "GetIamPolicy": { + "methods": [ + "GetIamPolicy" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "ListEkmConnections": { + "methods": [ + "ListEkmConnections" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "SetIamPolicy": { + "methods": [ + "SetIamPolicy" + ] + }, + "TestIamPermissions": { + "methods": [ + "TestIamPermissions" + ] + }, + "UpdateEkmConnection": { + "methods": [ + "UpdateEkmConnection" + ] + } + } } } }, @@ -220,6 +270,166 @@ ] } } + }, + "rest": { + "libraryClient": "KeyManagementClient", + "rpcs": { + "AsymmetricDecrypt": { + "methods": [ + "AsymmetricDecrypt" + ] + }, + "AsymmetricSign": { + "methods": [ + "AsymmetricSign" + ] + }, + "CreateCryptoKey": { + "methods": [ + "CreateCryptoKey" + ] + }, + "CreateCryptoKeyVersion": { + "methods": [ + "CreateCryptoKeyVersion" + ] + }, + "CreateImportJob": { + "methods": [ + "CreateImportJob" + ] + }, + "CreateKeyRing": { + "methods": [ + "CreateKeyRing" + ] + }, + "Decrypt": { + "methods": [ + "Decrypt" + ] + }, + "DestroyCryptoKeyVersion": { + "methods": [ + "DestroyCryptoKeyVersion" + ] + }, + "Encrypt": { + "methods": [ + "Encrypt" + ] + }, + "GenerateRandomBytes": { + "methods": [ + "GenerateRandomBytes" + ] + }, + "GetCryptoKey": { + "methods": [ + "GetCryptoKey" + ] + }, + "GetCryptoKeyVersion": { + "methods": [ + "GetCryptoKeyVersion" + ] + }, + "GetIamPolicy": { + "methods": [ + "GetIamPolicy" + ] + }, + "GetImportJob": { + "methods": [ + "GetImportJob" + ] + }, + "GetKeyRing": { + "methods": [ + "GetKeyRing" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "GetPublicKey": { + "methods": [ + "GetPublicKey" + ] + }, + "ImportCryptoKeyVersion": { + "methods": [ + "ImportCryptoKeyVersion" + ] + }, + "ListCryptoKeyVersions": { + "methods": [ + "ListCryptoKeyVersions" + ] + }, + "ListCryptoKeys": { + "methods": [ + "ListCryptoKeys" + ] + }, + "ListImportJobs": { + "methods": [ + "ListImportJobs" + ] + }, + "ListKeyRings": { + "methods": [ + "ListKeyRings" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "MacSign": { + "methods": [ + "MacSign" + ] + }, + "MacVerify": { + "methods": [ + "MacVerify" + ] + }, + "RestoreCryptoKeyVersion": { + "methods": [ + "RestoreCryptoKeyVersion" + ] + }, + "SetIamPolicy": { + "methods": [ + "SetIamPolicy" + ] + }, + "TestIamPermissions": { + "methods": [ + "TestIamPermissions" + ] + }, + "UpdateCryptoKey": { + "methods": [ + "UpdateCryptoKey" + ] + }, + "UpdateCryptoKeyPrimaryVersion": { + "methods": [ + "UpdateCryptoKeyPrimaryVersion" + ] + }, + "UpdateCryptoKeyVersion": { + "methods": [ + "UpdateCryptoKeyVersion" + ] + } + } } } } diff --git a/kms/apiv1/key_management_client.go b/kms/apiv1/key_management_client.go index 3581887971aa..9cbae850b3fe 100644 --- a/kms/apiv1/key_management_client.go +++ b/kms/apiv1/key_management_client.go @@ -17,23 +17,29 @@ package kms import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" kmspb "cloud.google.com/go/kms/apiv1/kmspb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" iampb "google.golang.org/genproto/googleapis/iam/v1" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -386,6 +392,282 @@ func defaultKeyManagementCallOptions() *KeyManagementCallOptions { } } +func defaultKeyManagementRESTCallOptions() *KeyManagementCallOptions { + return &KeyManagementCallOptions{ + ListKeyRings: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + ListCryptoKeys: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + ListCryptoKeyVersions: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + ListImportJobs: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + GetKeyRing: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + GetCryptoKey: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + GetCryptoKeyVersion: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + GetPublicKey: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + GetImportJob: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + CreateKeyRing: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + CreateCryptoKey: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + CreateCryptoKeyVersion: []gax.CallOption{}, + ImportCryptoKeyVersion: []gax.CallOption{}, + CreateImportJob: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + UpdateCryptoKey: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + UpdateCryptoKeyVersion: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + UpdateCryptoKeyPrimaryVersion: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + DestroyCryptoKeyVersion: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + RestoreCryptoKeyVersion: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + Encrypt: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + Decrypt: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + AsymmetricSign: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + AsymmetricDecrypt: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + MacSign: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + MacVerify: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + GenerateRandomBytes: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + GetIamPolicy: []gax.CallOption{}, + SetIamPolicy: []gax.CallOption{}, + TestIamPermissions: []gax.CallOption{}, + } +} + // internalKeyManagementClient is an interface that defines the methods available from Cloud Key Management Service (KMS) API. type internalKeyManagementClient interface { Close() error @@ -834,6 +1116,88 @@ func (c *keyManagementGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type keyManagementRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing KeyManagementClient + CallOptions **KeyManagementCallOptions +} + +// NewKeyManagementRESTClient creates a new key management service rest client. +// +// # Google Cloud Key Management Service +// +// Manages cryptographic keys and operations using those keys. Implements a REST +// model with the following objects: +// +// KeyRing +// +// CryptoKey +// +// CryptoKeyVersion +// +// ImportJob +// +// If you are using manual gRPC libraries, see +// Using gRPC with Cloud KMS (at https://cloud.google.com/kms/docs/grpc). +func NewKeyManagementRESTClient(ctx context.Context, opts ...option.ClientOption) (*KeyManagementClient, error) { + clientOpts := append(defaultKeyManagementRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultKeyManagementRESTCallOptions() + c := &keyManagementRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &KeyManagementClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultKeyManagementRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://cloudkms.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://cloudkms.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://cloudkms.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *keyManagementRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *keyManagementRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *keyManagementRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *keyManagementGRPCClient) ListKeyRings(ctx context.Context, req *kmspb.ListKeyRingsRequest, opts ...gax.CallOption) *KeyRingIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1611,6 +1975,2235 @@ func (c *keyManagementGRPCClient) TestIamPermissions(ctx context.Context, req *i return resp, nil } +// ListKeyRings lists KeyRings. +func (c *keyManagementRESTClient) ListKeyRings(ctx context.Context, req *kmspb.ListKeyRingsRequest, opts ...gax.CallOption) *KeyRingIterator { + it := &KeyRingIterator{} + req = proto.Clone(req).(*kmspb.ListKeyRingsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*kmspb.KeyRing, string, error) { + resp := &kmspb.ListKeyRingsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/keyRings", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetKeyRings(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// ListCryptoKeys lists CryptoKeys. +func (c *keyManagementRESTClient) ListCryptoKeys(ctx context.Context, req *kmspb.ListCryptoKeysRequest, opts ...gax.CallOption) *CryptoKeyIterator { + it := &CryptoKeyIterator{} + req = proto.Clone(req).(*kmspb.ListCryptoKeysRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*kmspb.CryptoKey, string, error) { + resp := &kmspb.ListCryptoKeysResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/cryptoKeys", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + if req.GetVersionView() != 0 { + params.Add("versionView", fmt.Sprintf("%v", req.GetVersionView())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetCryptoKeys(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// ListCryptoKeyVersions lists CryptoKeyVersions. +func (c *keyManagementRESTClient) ListCryptoKeyVersions(ctx context.Context, req *kmspb.ListCryptoKeyVersionsRequest, opts ...gax.CallOption) *CryptoKeyVersionIterator { + it := &CryptoKeyVersionIterator{} + req = proto.Clone(req).(*kmspb.ListCryptoKeyVersionsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*kmspb.CryptoKeyVersion, string, error) { + resp := &kmspb.ListCryptoKeyVersionsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/cryptoKeyVersions", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + if req.GetView() != 0 { + params.Add("view", fmt.Sprintf("%v", req.GetView())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetCryptoKeyVersions(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// ListImportJobs lists ImportJobs. +func (c *keyManagementRESTClient) ListImportJobs(ctx context.Context, req *kmspb.ListImportJobsRequest, opts ...gax.CallOption) *ImportJobIterator { + it := &ImportJobIterator{} + req = proto.Clone(req).(*kmspb.ListImportJobsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*kmspb.ImportJob, string, error) { + resp := &kmspb.ListImportJobsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/importJobs", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetImportJobs(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetKeyRing returns metadata for a given KeyRing. +func (c *keyManagementRESTClient) GetKeyRing(ctx context.Context, req *kmspb.GetKeyRingRequest, opts ...gax.CallOption) (*kmspb.KeyRing, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetKeyRing[0:len((*c.CallOptions).GetKeyRing):len((*c.CallOptions).GetKeyRing)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &kmspb.KeyRing{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetCryptoKey returns metadata for a given CryptoKey, as +// well as its primary +// CryptoKeyVersion. +func (c *keyManagementRESTClient) GetCryptoKey(ctx context.Context, req *kmspb.GetCryptoKeyRequest, opts ...gax.CallOption) (*kmspb.CryptoKey, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetCryptoKey[0:len((*c.CallOptions).GetCryptoKey):len((*c.CallOptions).GetCryptoKey)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &kmspb.CryptoKey{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetCryptoKeyVersion returns metadata for a given +// CryptoKeyVersion. +func (c *keyManagementRESTClient) GetCryptoKeyVersion(ctx context.Context, req *kmspb.GetCryptoKeyVersionRequest, opts ...gax.CallOption) (*kmspb.CryptoKeyVersion, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetCryptoKeyVersion[0:len((*c.CallOptions).GetCryptoKeyVersion):len((*c.CallOptions).GetCryptoKeyVersion)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &kmspb.CryptoKeyVersion{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetPublicKey returns the public key for the given +// CryptoKeyVersion. The +// CryptoKey.purpose must be +// ASYMMETRIC_SIGN +// or +// ASYMMETRIC_DECRYPT. +func (c *keyManagementRESTClient) GetPublicKey(ctx context.Context, req *kmspb.GetPublicKeyRequest, opts ...gax.CallOption) (*kmspb.PublicKey, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/publicKey", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetPublicKey[0:len((*c.CallOptions).GetPublicKey):len((*c.CallOptions).GetPublicKey)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &kmspb.PublicKey{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetImportJob returns metadata for a given ImportJob. +func (c *keyManagementRESTClient) GetImportJob(ctx context.Context, req *kmspb.GetImportJobRequest, opts ...gax.CallOption) (*kmspb.ImportJob, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetImportJob[0:len((*c.CallOptions).GetImportJob):len((*c.CallOptions).GetImportJob)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &kmspb.ImportJob{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateKeyRing create a new KeyRing in a given Project and +// Location. +func (c *keyManagementRESTClient) CreateKeyRing(ctx context.Context, req *kmspb.CreateKeyRingRequest, opts ...gax.CallOption) (*kmspb.KeyRing, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetKeyRing() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/keyRings", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("keyRingId", fmt.Sprintf("%v", req.GetKeyRingId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateKeyRing[0:len((*c.CallOptions).CreateKeyRing):len((*c.CallOptions).CreateKeyRing)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &kmspb.KeyRing{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateCryptoKey create a new CryptoKey within a +// KeyRing. +// +// CryptoKey.purpose and +// CryptoKey.version_template.algorithm +// are required. +func (c *keyManagementRESTClient) CreateCryptoKey(ctx context.Context, req *kmspb.CreateCryptoKeyRequest, opts ...gax.CallOption) (*kmspb.CryptoKey, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetCryptoKey() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/cryptoKeys", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("cryptoKeyId", fmt.Sprintf("%v", req.GetCryptoKeyId())) + if req.GetSkipInitialVersionCreation() { + params.Add("skipInitialVersionCreation", fmt.Sprintf("%v", req.GetSkipInitialVersionCreation())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateCryptoKey[0:len((*c.CallOptions).CreateCryptoKey):len((*c.CallOptions).CreateCryptoKey)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &kmspb.CryptoKey{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateCryptoKeyVersion create a new CryptoKeyVersion in a +// CryptoKey. +// +// The server will assign the next sequential id. If unset, +// state will be set to +// ENABLED. +func (c *keyManagementRESTClient) CreateCryptoKeyVersion(ctx context.Context, req *kmspb.CreateCryptoKeyVersionRequest, opts ...gax.CallOption) (*kmspb.CryptoKeyVersion, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetCryptoKeyVersion() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/cryptoKeyVersions", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateCryptoKeyVersion[0:len((*c.CallOptions).CreateCryptoKeyVersion):len((*c.CallOptions).CreateCryptoKeyVersion)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &kmspb.CryptoKeyVersion{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ImportCryptoKeyVersion import wrapped key material into a +// CryptoKeyVersion. +// +// All requests must specify a CryptoKey. If +// a CryptoKeyVersion is additionally +// specified in the request, key material will be reimported into that +// version. Otherwise, a new version will be created, and will be assigned the +// next sequential id within the CryptoKey. +func (c *keyManagementRESTClient) ImportCryptoKeyVersion(ctx context.Context, req *kmspb.ImportCryptoKeyVersionRequest, opts ...gax.CallOption) (*kmspb.CryptoKeyVersion, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/cryptoKeyVersions:import", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).ImportCryptoKeyVersion[0:len((*c.CallOptions).ImportCryptoKeyVersion):len((*c.CallOptions).ImportCryptoKeyVersion)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &kmspb.CryptoKeyVersion{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateImportJob create a new ImportJob within a +// KeyRing. +// +// ImportJob.import_method is +// required. +func (c *keyManagementRESTClient) CreateImportJob(ctx context.Context, req *kmspb.CreateImportJobRequest, opts ...gax.CallOption) (*kmspb.ImportJob, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetImportJob() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/importJobs", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("importJobId", fmt.Sprintf("%v", req.GetImportJobId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateImportJob[0:len((*c.CallOptions).CreateImportJob):len((*c.CallOptions).CreateImportJob)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &kmspb.ImportJob{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateCryptoKey update a CryptoKey. +func (c *keyManagementRESTClient) UpdateCryptoKey(ctx context.Context, req *kmspb.UpdateCryptoKeyRequest, opts ...gax.CallOption) (*kmspb.CryptoKey, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetCryptoKey() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetCryptoKey().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "crypto_key.name", url.QueryEscape(req.GetCryptoKey().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateCryptoKey[0:len((*c.CallOptions).UpdateCryptoKey):len((*c.CallOptions).UpdateCryptoKey)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &kmspb.CryptoKey{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateCryptoKeyVersion update a CryptoKeyVersion's +// metadata. +// +// state may be changed between +// ENABLED +// and +// DISABLED +// using this method. See +// DestroyCryptoKeyVersion +// and +// RestoreCryptoKeyVersion +// to move between other states. +func (c *keyManagementRESTClient) UpdateCryptoKeyVersion(ctx context.Context, req *kmspb.UpdateCryptoKeyVersionRequest, opts ...gax.CallOption) (*kmspb.CryptoKeyVersion, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetCryptoKeyVersion() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetCryptoKeyVersion().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "crypto_key_version.name", url.QueryEscape(req.GetCryptoKeyVersion().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateCryptoKeyVersion[0:len((*c.CallOptions).UpdateCryptoKeyVersion):len((*c.CallOptions).UpdateCryptoKeyVersion)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &kmspb.CryptoKeyVersion{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateCryptoKeyPrimaryVersion update the version of a CryptoKey that +// will be used in +// Encrypt. +// +// Returns an error if called on a key whose purpose is not +// ENCRYPT_DECRYPT. +func (c *keyManagementRESTClient) UpdateCryptoKeyPrimaryVersion(ctx context.Context, req *kmspb.UpdateCryptoKeyPrimaryVersionRequest, opts ...gax.CallOption) (*kmspb.CryptoKey, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:updatePrimaryVersion", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateCryptoKeyPrimaryVersion[0:len((*c.CallOptions).UpdateCryptoKeyPrimaryVersion):len((*c.CallOptions).UpdateCryptoKeyPrimaryVersion)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &kmspb.CryptoKey{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DestroyCryptoKeyVersion schedule a CryptoKeyVersion for +// destruction. +// +// Upon calling this method, +// CryptoKeyVersion.state will +// be set to +// DESTROY_SCHEDULED, +// and destroy_time will +// be set to the time +// destroy_scheduled_duration +// in the future. At that time, the +// state will automatically +// change to +// DESTROYED, +// and the key material will be irrevocably destroyed. +// +// Before the +// destroy_time is +// reached, +// RestoreCryptoKeyVersion +// may be called to reverse the process. +func (c *keyManagementRESTClient) DestroyCryptoKeyVersion(ctx context.Context, req *kmspb.DestroyCryptoKeyVersionRequest, opts ...gax.CallOption) (*kmspb.CryptoKeyVersion, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:destroy", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).DestroyCryptoKeyVersion[0:len((*c.CallOptions).DestroyCryptoKeyVersion):len((*c.CallOptions).DestroyCryptoKeyVersion)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &kmspb.CryptoKeyVersion{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// RestoreCryptoKeyVersion restore a CryptoKeyVersion in the +// DESTROY_SCHEDULED +// state. +// +// Upon restoration of the CryptoKeyVersion, +// state will be set to +// DISABLED, +// and destroy_time will +// be cleared. +func (c *keyManagementRESTClient) RestoreCryptoKeyVersion(ctx context.Context, req *kmspb.RestoreCryptoKeyVersionRequest, opts ...gax.CallOption) (*kmspb.CryptoKeyVersion, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:restore", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).RestoreCryptoKeyVersion[0:len((*c.CallOptions).RestoreCryptoKeyVersion):len((*c.CallOptions).RestoreCryptoKeyVersion)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &kmspb.CryptoKeyVersion{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// Encrypt encrypts data, so that it can only be recovered by a call to +// Decrypt. The +// CryptoKey.purpose must be +// ENCRYPT_DECRYPT. +func (c *keyManagementRESTClient) Encrypt(ctx context.Context, req *kmspb.EncryptRequest, opts ...gax.CallOption) (*kmspb.EncryptResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:encrypt", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).Encrypt[0:len((*c.CallOptions).Encrypt):len((*c.CallOptions).Encrypt)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &kmspb.EncryptResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// Decrypt decrypts data that was protected by +// Encrypt. The +// CryptoKey.purpose must be +// ENCRYPT_DECRYPT. +func (c *keyManagementRESTClient) Decrypt(ctx context.Context, req *kmspb.DecryptRequest, opts ...gax.CallOption) (*kmspb.DecryptResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:decrypt", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).Decrypt[0:len((*c.CallOptions).Decrypt):len((*c.CallOptions).Decrypt)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &kmspb.DecryptResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// AsymmetricSign signs data using a CryptoKeyVersion +// with CryptoKey.purpose +// ASYMMETRIC_SIGN, producing a signature that can be verified with the public +// key retrieved from +// GetPublicKey. +func (c *keyManagementRESTClient) AsymmetricSign(ctx context.Context, req *kmspb.AsymmetricSignRequest, opts ...gax.CallOption) (*kmspb.AsymmetricSignResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:asymmetricSign", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).AsymmetricSign[0:len((*c.CallOptions).AsymmetricSign):len((*c.CallOptions).AsymmetricSign)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &kmspb.AsymmetricSignResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// AsymmetricDecrypt decrypts data that was encrypted with a public key retrieved from +// GetPublicKey +// corresponding to a CryptoKeyVersion +// with CryptoKey.purpose +// ASYMMETRIC_DECRYPT. +func (c *keyManagementRESTClient) AsymmetricDecrypt(ctx context.Context, req *kmspb.AsymmetricDecryptRequest, opts ...gax.CallOption) (*kmspb.AsymmetricDecryptResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:asymmetricDecrypt", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).AsymmetricDecrypt[0:len((*c.CallOptions).AsymmetricDecrypt):len((*c.CallOptions).AsymmetricDecrypt)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &kmspb.AsymmetricDecryptResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// MacSign signs data using a CryptoKeyVersion +// with CryptoKey.purpose MAC, +// producing a tag that can be verified by another source with the same key. +func (c *keyManagementRESTClient) MacSign(ctx context.Context, req *kmspb.MacSignRequest, opts ...gax.CallOption) (*kmspb.MacSignResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:macSign", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).MacSign[0:len((*c.CallOptions).MacSign):len((*c.CallOptions).MacSign)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &kmspb.MacSignResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// MacVerify verifies MAC tag using a +// CryptoKeyVersion with +// CryptoKey.purpose MAC, and returns +// a response that indicates whether or not the verification was successful. +func (c *keyManagementRESTClient) MacVerify(ctx context.Context, req *kmspb.MacVerifyRequest, opts ...gax.CallOption) (*kmspb.MacVerifyResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:macVerify", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).MacVerify[0:len((*c.CallOptions).MacVerify):len((*c.CallOptions).MacVerify)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &kmspb.MacVerifyResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GenerateRandomBytes generate random bytes using the Cloud KMS randomness source in the provided +// location. +func (c *keyManagementRESTClient) GenerateRandomBytes(ctx context.Context, req *kmspb.GenerateRandomBytesRequest, opts ...gax.CallOption) (*kmspb.GenerateRandomBytesResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:generateRandomBytes", req.GetLocation()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "location", url.QueryEscape(req.GetLocation()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GenerateRandomBytes[0:len((*c.CallOptions).GenerateRandomBytes):len((*c.CallOptions).GenerateRandomBytes)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &kmspb.GenerateRandomBytesResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetLocation gets information about a location. +func (c *keyManagementRESTClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *keyManagementRESTClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetIamPolicy gets the access control policy for a resource. Returns an empty policy +// if the resource exists and does not have a policy set. +func (c *keyManagementRESTClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:getIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetOptions().GetRequestedPolicyVersion() != 0 { + params.Add("options.requestedPolicyVersion", fmt.Sprintf("%v", req.GetOptions().GetRequestedPolicyVersion())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SetIamPolicy sets the access control policy on the specified resource. Replaces +// any existing policy. +// +// Can return NOT_FOUND, INVALID_ARGUMENT, and PERMISSION_DENIED +// errors. +func (c *keyManagementRESTClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:setIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// TestIamPermissions returns permissions that a caller has on the specified resource. If the +// resource does not exist, this will return an empty set of +// permissions, not a NOT_FOUND error. +// +// Note: This operation is designed to be used for building +// permission-aware UIs and command-line tools, not for authorization +// checking. This operation may “fail open” without warning. +func (c *keyManagementRESTClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:testIamPermissions", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.TestIamPermissionsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + // CryptoKeyIterator manages a stream of *kmspb.CryptoKey. type CryptoKeyIterator struct { items []*kmspb.CryptoKey diff --git a/kms/apiv1/key_management_client_example_test.go b/kms/apiv1/key_management_client_example_test.go index ade51655f98c..123534786222 100644 --- a/kms/apiv1/key_management_client_example_test.go +++ b/kms/apiv1/key_management_client_example_test.go @@ -43,6 +43,23 @@ func ExampleNewKeyManagementClient() { _ = c } +func ExampleNewKeyManagementRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := kms.NewKeyManagementRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleKeyManagementClient_ListKeyRings() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/kms/apiv1/kmspb/ekm_service.pb.go b/kms/apiv1/kmspb/ekm_service.pb.go index 2cf0cd4f4f19..b013144e40a0 100644 --- a/kms/apiv1/kmspb/ekm_service.pb.go +++ b/kms/apiv1/kmspb/ekm_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/kms/v1/ekm_service.proto package kmspb diff --git a/kms/apiv1/kmspb/resources.pb.go b/kms/apiv1/kmspb/resources.pb.go index 83b3568c9475..f7057c0ab3ec 100644 --- a/kms/apiv1/kmspb/resources.pb.go +++ b/kms/apiv1/kmspb/resources.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/kms/v1/resources.proto package kmspb @@ -875,7 +875,6 @@ type CryptoKey struct { // Controls the rate of automatic rotation. // // Types that are assignable to RotationSchedule: - // // *CryptoKey_RotationPeriod RotationSchedule isCryptoKey_RotationSchedule `protobuf_oneof:"rotation_schedule"` // A template describing settings for new diff --git a/kms/apiv1/kmspb/service.pb.go b/kms/apiv1/kmspb/service.pb.go index d345c167dab8..7d3756eb1d67 100644 --- a/kms/apiv1/kmspb/service.pb.go +++ b/kms/apiv1/kmspb/service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/kms/v1/service.proto package kmspb @@ -1285,16 +1285,14 @@ type ImportCryptoKeyVersionRequest struct { // // this field must contain the concatenation of: //
    - // - //
  1. An ephemeral AES-256 wrapping key wrapped with the - // [public_key][google.cloud.kms.v1.ImportJob.public_key] using - // RSAES-OAEP with SHA-1/SHA-256, MGF1 with SHA-1/SHA-256, and an empty - // label. - //
  2. - //
  3. The formatted key to be imported, wrapped with the ephemeral AES-256 - // key using AES-KWP (RFC 5649). - //
  4. - // + //
  5. An ephemeral AES-256 wrapping key wrapped with the + // [public_key][google.cloud.kms.v1.ImportJob.public_key] using + // RSAES-OAEP with SHA-1/SHA-256, MGF1 with SHA-1/SHA-256, and an empty + // label. + //
  6. + //
  7. The formatted key to be imported, wrapped with the ephemeral AES-256 + // key using AES-KWP (RFC 5649). + //
  8. //
// // This format is the same as the format produced by PKCS#11 mechanism @@ -1314,7 +1312,6 @@ type ImportCryptoKeyVersionRequest struct { // instead. // // Types that are assignable to WrappedKeyMaterial: - // // *ImportCryptoKeyVersionRequest_RsaAesWrappedKey WrappedKeyMaterial isImportCryptoKeyVersionRequest_WrappedKeyMaterial `protobuf_oneof:"wrapped_key_material"` } @@ -3350,7 +3347,6 @@ type Digest struct { // Required. The message digest. // // Types that are assignable to Digest: - // // *Digest_Sha256 // *Digest_Sha384 // *Digest_Sha512 diff --git a/language/apiv1/doc.go b/language/apiv1/doc.go index cfe739b26fa0..eb5fcda86a7c 100644 --- a/language/apiv1/doc.go +++ b/language/apiv1/doc.go @@ -82,6 +82,8 @@ package language // import "cloud.google.com/go/language/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -171,3 +173,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/language/apiv1/gapic_metadata.json b/language/apiv1/gapic_metadata.json index f49ef2f8a6a7..a53f00e85468 100644 --- a/language/apiv1/gapic_metadata.json +++ b/language/apiv1/gapic_metadata.json @@ -41,6 +41,41 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "AnalyzeEntities": { + "methods": [ + "AnalyzeEntities" + ] + }, + "AnalyzeEntitySentiment": { + "methods": [ + "AnalyzeEntitySentiment" + ] + }, + "AnalyzeSentiment": { + "methods": [ + "AnalyzeSentiment" + ] + }, + "AnalyzeSyntax": { + "methods": [ + "AnalyzeSyntax" + ] + }, + "AnnotateText": { + "methods": [ + "AnnotateText" + ] + }, + "ClassifyText": { + "methods": [ + "ClassifyText" + ] + } + } } } } diff --git a/language/apiv1/language_client.go b/language/apiv1/language_client.go index 7a929afd0b7f..9fbc041a7710 100644 --- a/language/apiv1/language_client.go +++ b/language/apiv1/language_client.go @@ -17,18 +17,26 @@ package language import ( + "bytes" "context" + "fmt" + "io/ioutil" "math" + "net/http" + "net/url" "time" languagepb "cloud.google.com/go/language/apiv1/languagepb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" ) var newClientHook clientHook @@ -132,6 +140,77 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + AnalyzeSentiment: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + AnalyzeEntities: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + AnalyzeEntitySentiment: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + AnalyzeSyntax: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + ClassifyText: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + AnnotateText: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + } +} + // internalClient is an interface that defines the methods available from Cloud Natural Language API. type internalClient interface { Close() error @@ -299,6 +378,75 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new language service rest client. +// +// Provides text analysis operations such as sentiment analysis and entity +// recognition. +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://language.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://language.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://language.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) AnalyzeSentiment(ctx context.Context, req *languagepb.AnalyzeSentimentRequest, opts ...gax.CallOption) (*languagepb.AnalyzeSentimentResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) @@ -418,3 +566,381 @@ func (c *gRPCClient) AnnotateText(ctx context.Context, req *languagepb.AnnotateT } return resp, nil } + +// AnalyzeSentiment analyzes the sentiment of the provided text. +func (c *restClient) AnalyzeSentiment(ctx context.Context, req *languagepb.AnalyzeSentimentRequest, opts ...gax.CallOption) (*languagepb.AnalyzeSentimentResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/documents:analyzeSentiment") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).AnalyzeSentiment[0:len((*c.CallOptions).AnalyzeSentiment):len((*c.CallOptions).AnalyzeSentiment)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &languagepb.AnalyzeSentimentResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// AnalyzeEntities finds named entities (currently proper names and common nouns) in the text +// along with entity types, salience, mentions for each entity, and +// other properties. +func (c *restClient) AnalyzeEntities(ctx context.Context, req *languagepb.AnalyzeEntitiesRequest, opts ...gax.CallOption) (*languagepb.AnalyzeEntitiesResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/documents:analyzeEntities") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).AnalyzeEntities[0:len((*c.CallOptions).AnalyzeEntities):len((*c.CallOptions).AnalyzeEntities)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &languagepb.AnalyzeEntitiesResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// AnalyzeEntitySentiment finds entities, similar to AnalyzeEntities in the text and analyzes +// sentiment associated with each entity and its mentions. +func (c *restClient) AnalyzeEntitySentiment(ctx context.Context, req *languagepb.AnalyzeEntitySentimentRequest, opts ...gax.CallOption) (*languagepb.AnalyzeEntitySentimentResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/documents:analyzeEntitySentiment") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).AnalyzeEntitySentiment[0:len((*c.CallOptions).AnalyzeEntitySentiment):len((*c.CallOptions).AnalyzeEntitySentiment)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &languagepb.AnalyzeEntitySentimentResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// AnalyzeSyntax analyzes the syntax of the text and provides sentence boundaries and +// tokenization along with part of speech tags, dependency trees, and other +// properties. +func (c *restClient) AnalyzeSyntax(ctx context.Context, req *languagepb.AnalyzeSyntaxRequest, opts ...gax.CallOption) (*languagepb.AnalyzeSyntaxResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/documents:analyzeSyntax") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).AnalyzeSyntax[0:len((*c.CallOptions).AnalyzeSyntax):len((*c.CallOptions).AnalyzeSyntax)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &languagepb.AnalyzeSyntaxResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ClassifyText classifies a document into categories. +func (c *restClient) ClassifyText(ctx context.Context, req *languagepb.ClassifyTextRequest, opts ...gax.CallOption) (*languagepb.ClassifyTextResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/documents:classifyText") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).ClassifyText[0:len((*c.CallOptions).ClassifyText):len((*c.CallOptions).ClassifyText)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &languagepb.ClassifyTextResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// AnnotateText a convenience method that provides all the features that analyzeSentiment, +// analyzeEntities, and analyzeSyntax provide in one call. +func (c *restClient) AnnotateText(ctx context.Context, req *languagepb.AnnotateTextRequest, opts ...gax.CallOption) (*languagepb.AnnotateTextResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/documents:annotateText") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).AnnotateText[0:len((*c.CallOptions).AnnotateText):len((*c.CallOptions).AnnotateText)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &languagepb.AnnotateTextResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} diff --git a/language/apiv1/language_client_example_test.go b/language/apiv1/language_client_example_test.go index 8c1e60c50141..e6e5aed0f570 100644 --- a/language/apiv1/language_client_example_test.go +++ b/language/apiv1/language_client_example_test.go @@ -40,6 +40,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := language.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_AnalyzeSentiment() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/language/apiv1/languagepb/language_service.pb.go b/language/apiv1/languagepb/language_service.pb.go index c6b2dee9e035..117b590cd563 100644 --- a/language/apiv1/languagepb/language_service.pb.go +++ b/language/apiv1/languagepb/language_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/language/v1/language_service.proto package languagepb @@ -1611,7 +1611,6 @@ type Document struct { // Google Cloud Storage URI. // // Types that are assignable to Source: - // // *Document_Content // *Document_GcsContentUri Source isDocument_Source `protobuf_oneof:"source"` @@ -2435,7 +2434,6 @@ type ClassificationModelOptions struct { // If this field is not set, then the `v1_model` will be used by default. // // Types that are assignable to ModelType: - // // *ClassificationModelOptions_V1Model_ // *ClassificationModelOptions_V2Model_ ModelType isClassificationModelOptions_ModelType `protobuf_oneof:"model_type"` diff --git a/language/apiv1beta2/language_client.go b/language/apiv1beta2/language_client.go index d0440ec60c1d..f46247ceed14 100644 --- a/language/apiv1beta2/language_client.go +++ b/language/apiv1beta2/language_client.go @@ -581,6 +581,11 @@ func (c *restClient) AnalyzeSentiment(ctx context.Context, req *languagepb.Analy } baseUrl.Path += fmt.Sprintf("/v1beta2/documents:analyzeSentiment") + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) opts = append((*c.CallOptions).AnalyzeSentiment[0:len((*c.CallOptions).AnalyzeSentiment):len((*c.CallOptions).AnalyzeSentiment)], opts...) @@ -640,6 +645,11 @@ func (c *restClient) AnalyzeEntities(ctx context.Context, req *languagepb.Analyz } baseUrl.Path += fmt.Sprintf("/v1beta2/documents:analyzeEntities") + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) opts = append((*c.CallOptions).AnalyzeEntities[0:len((*c.CallOptions).AnalyzeEntities):len((*c.CallOptions).AnalyzeEntities)], opts...) @@ -698,6 +708,11 @@ func (c *restClient) AnalyzeEntitySentiment(ctx context.Context, req *languagepb } baseUrl.Path += fmt.Sprintf("/v1beta2/documents:analyzeEntitySentiment") + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) opts = append((*c.CallOptions).AnalyzeEntitySentiment[0:len((*c.CallOptions).AnalyzeEntitySentiment):len((*c.CallOptions).AnalyzeEntitySentiment)], opts...) @@ -757,6 +772,11 @@ func (c *restClient) AnalyzeSyntax(ctx context.Context, req *languagepb.AnalyzeS } baseUrl.Path += fmt.Sprintf("/v1beta2/documents:analyzeSyntax") + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) opts = append((*c.CallOptions).AnalyzeSyntax[0:len((*c.CallOptions).AnalyzeSyntax):len((*c.CallOptions).AnalyzeSyntax)], opts...) @@ -814,6 +834,11 @@ func (c *restClient) ClassifyText(ctx context.Context, req *languagepb.ClassifyT } baseUrl.Path += fmt.Sprintf("/v1beta2/documents:classifyText") + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) opts = append((*c.CallOptions).ClassifyText[0:len((*c.CallOptions).ClassifyText):len((*c.CallOptions).ClassifyText)], opts...) @@ -872,6 +897,11 @@ func (c *restClient) AnnotateText(ctx context.Context, req *languagepb.AnnotateT } baseUrl.Path += fmt.Sprintf("/v1beta2/documents:annotateText") + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) opts = append((*c.CallOptions).AnnotateText[0:len((*c.CallOptions).AnnotateText):len((*c.CallOptions).AnnotateText)], opts...) diff --git a/language/apiv1beta2/languagepb/language_service.pb.go b/language/apiv1beta2/languagepb/language_service.pb.go index 62d9a50e2581..86a7ab970565 100644 --- a/language/apiv1beta2/languagepb/language_service.pb.go +++ b/language/apiv1beta2/languagepb/language_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/language/v1beta2/language_service.proto package languagepb @@ -1665,7 +1665,6 @@ type Document struct { // Google Cloud Storage URI. // // Types that are assignable to Source: - // // *Document_Content // *Document_GcsContentUri Source isDocument_Source `protobuf_oneof:"source"` @@ -2507,7 +2506,6 @@ type ClassificationModelOptions struct { // If this field is not set, then the `v1_model` will be used by default. // // Types that are assignable to ModelType: - // // *ClassificationModelOptions_V1Model_ // *ClassificationModelOptions_V2Model_ ModelType isClassificationModelOptions_ModelType `protobuf_oneof:"model_type"` diff --git a/lifesciences/apiv2beta/lifesciencespb/workflows.pb.go b/lifesciences/apiv2beta/lifesciencespb/workflows.pb.go index 4e3967922a85..ff9d90072222 100644 --- a/lifesciences/apiv2beta/lifesciencespb/workflows.pb.go +++ b/lifesciences/apiv2beta/lifesciencespb/workflows.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/lifesciences/v2beta/workflows.proto package lifesciencespb @@ -347,17 +347,15 @@ type Action struct { // operational components. // //
    - // - //
  • /google/logs All logs written during the pipeline - // execution.
  • - //
  • /google/logs/output The combined standard output and - // standard error of all actions run as part of the pipeline - // execution.
  • - //
  • /google/logs/action/*/stdout The complete contents of - // each individual action's standard output.
  • - //
  • /google/logs/action/*/stderr The complete contents of - // each individual action's standard error output.
  • - // + //
  • /google/logs All logs written during the pipeline + // execution.
  • + //
  • /google/logs/output The combined standard output and + // standard error of all actions run as part of the pipeline + // execution.
  • + //
  • /google/logs/action/*/stdout The complete contents of + // each individual action's standard output.
  • + //
  • /google/logs/action/*/stderr The complete contents of + // each individual action's standard error output.
  • //
Mounts []*Mount `protobuf:"bytes,9,rep,name=mounts,proto3" json:"mounts,omitempty"` // Labels to associate with the action. This field is provided to assist @@ -1334,7 +1332,6 @@ type Volume struct { // start with a hyphen. Volume string `protobuf:"bytes,1,opt,name=volume,proto3" json:"volume,omitempty"` // Types that are assignable to Storage: - // // *Volume_PersistentDisk // *Volume_ExistingDisk // *Volume_NfsMount @@ -1737,7 +1734,6 @@ type Event struct { // Machine-readable details about the event. // // Types that are assignable to Details: - // // *Event_Delayed // *Event_WorkerAssigned // *Event_WorkerReleased @@ -2544,7 +2540,7 @@ func (x *FailedEvent) GetCode() code.Code { if x != nil { return x.Code } - return code.Code_OK + return code.Code(0) } func (x *FailedEvent) GetCause() string { diff --git a/lifesciences/apiv2beta/workflows_service_v2_beta_client.go b/lifesciences/apiv2beta/workflows_service_v2_beta_client.go index 9714870af6c0..1639b292d393 100644 --- a/lifesciences/apiv2beta/workflows_service_v2_beta_client.go +++ b/lifesciences/apiv2beta/workflows_service_v2_beta_client.go @@ -596,6 +596,11 @@ func (c *workflowsServiceV2BetaRESTClient) RunPipeline(ctx context.Context, req } baseUrl.Path += fmt.Sprintf("/v2beta/%v/pipelines:run", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -653,6 +658,11 @@ func (c *workflowsServiceV2BetaRESTClient) GetLocation(ctx context.Context, req } baseUrl.Path += fmt.Sprintf("/v2beta/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -720,6 +730,7 @@ func (c *workflowsServiceV2BetaRESTClient) ListLocations(ctx context.Context, re baseUrl.Path += fmt.Sprintf("/v2beta/%v/locations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -812,6 +823,11 @@ func (c *workflowsServiceV2BetaRESTClient) CancelOperation(ctx context.Context, } baseUrl.Path += fmt.Sprintf("/v2beta/%v:cancel", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -853,6 +869,11 @@ func (c *workflowsServiceV2BetaRESTClient) GetOperation(ctx context.Context, req } baseUrl.Path += fmt.Sprintf("/v2beta/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -924,6 +945,7 @@ func (c *workflowsServiceV2BetaRESTClient) ListOperations(ctx context.Context, r baseUrl.Path += fmt.Sprintf("/v2beta/%v/operations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/logging/apiv2/config_client.go b/logging/apiv2/config_client.go index a236985410b9..c838504ed5e3 100644 --- a/logging/apiv2/config_client.go +++ b/logging/apiv2/config_client.go @@ -17,9 +17,12 @@ package logging import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,14 +30,17 @@ import ( "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -197,6 +203,114 @@ func defaultConfigCallOptions() *ConfigCallOptions { } } +func defaultConfigRESTCallOptions() *ConfigCallOptions { + return &ConfigCallOptions{ + ListBuckets: []gax.CallOption{}, + GetBucket: []gax.CallOption{}, + CreateBucket: []gax.CallOption{}, + UpdateBucket: []gax.CallOption{}, + DeleteBucket: []gax.CallOption{}, + UndeleteBucket: []gax.CallOption{}, + ListViews: []gax.CallOption{}, + GetView: []gax.CallOption{}, + CreateView: []gax.CallOption{}, + UpdateView: []gax.CallOption{}, + DeleteView: []gax.CallOption{}, + ListSinks: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusInternalServerError, + http.StatusServiceUnavailable) + }), + }, + GetSink: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusInternalServerError, + http.StatusServiceUnavailable) + }), + }, + CreateSink: []gax.CallOption{}, + UpdateSink: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusInternalServerError, + http.StatusServiceUnavailable) + }), + }, + DeleteSink: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusInternalServerError, + http.StatusServiceUnavailable) + }), + }, + ListExclusions: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusInternalServerError, + http.StatusServiceUnavailable) + }), + }, + GetExclusion: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusInternalServerError, + http.StatusServiceUnavailable) + }), + }, + CreateExclusion: []gax.CallOption{}, + UpdateExclusion: []gax.CallOption{}, + DeleteExclusion: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusInternalServerError, + http.StatusServiceUnavailable) + }), + }, + GetCmekSettings: []gax.CallOption{}, + UpdateCmekSettings: []gax.CallOption{}, + GetSettings: []gax.CallOption{}, + UpdateSettings: []gax.CallOption{}, + CopyLogEntries: []gax.CallOption{}, + } +} + // internalConfigClient is an interface that defines the methods available from Cloud Logging API. type internalConfigClient interface { Close() error @@ -585,6 +699,89 @@ func (c *configGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type configRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing ConfigClient + CallOptions **ConfigCallOptions +} + +// NewConfigRESTClient creates a new config service v2 rest client. +// +// Service for configuring sinks used to route log entries. +func NewConfigRESTClient(ctx context.Context, opts ...option.ClientOption) (*ConfigClient, error) { + clientOpts := append(defaultConfigRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultConfigRESTCallOptions() + c := &configRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &ConfigClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultConfigRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://logging.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://logging.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://logging.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *configRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *configRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *configRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *configGRPCClient) ListBuckets(ctx context.Context, req *loggingpb.ListBucketsRequest, opts ...gax.CallOption) *LogBucketIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1159,16 +1356,1780 @@ func (c *configGRPCClient) CopyLogEntries(ctx context.Context, req *loggingpb.Co }, nil } -// CopyLogEntriesOperation manages a long-running operation from CopyLogEntries. -type CopyLogEntriesOperation struct { - lro *longrunning.Operation +// ListBuckets lists log buckets. +func (c *configRESTClient) ListBuckets(ctx context.Context, req *loggingpb.ListBucketsRequest, opts ...gax.CallOption) *LogBucketIterator { + it := &LogBucketIterator{} + req = proto.Clone(req).(*loggingpb.ListBucketsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*loggingpb.LogBucket, string, error) { + resp := &loggingpb.ListBucketsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/buckets", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetBuckets(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it } -// CopyLogEntriesOperation returns a new CopyLogEntriesOperation from a given name. -// The name must be that of a previously created CopyLogEntriesOperation, possibly from a different process. -func (c *configGRPCClient) CopyLogEntriesOperation(name string) *CopyLogEntriesOperation { - return &CopyLogEntriesOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), +// GetBucket gets a log bucket. +func (c *configRESTClient) GetBucket(ctx context.Context, req *loggingpb.GetBucketRequest, opts ...gax.CallOption) (*loggingpb.LogBucket, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetBucket[0:len((*c.CallOptions).GetBucket):len((*c.CallOptions).GetBucket)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &loggingpb.LogBucket{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateBucket creates a log bucket that can be used to store log entries. After a bucket +// has been created, the bucket’s location cannot be changed. +func (c *configRESTClient) CreateBucket(ctx context.Context, req *loggingpb.CreateBucketRequest, opts ...gax.CallOption) (*loggingpb.LogBucket, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetBucket() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/buckets", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("bucketId", fmt.Sprintf("%v", req.GetBucketId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateBucket[0:len((*c.CallOptions).CreateBucket):len((*c.CallOptions).CreateBucket)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &loggingpb.LogBucket{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateBucket updates a log bucket. This method replaces the following fields in the +// existing bucket with values from the new bucket: retention_period +// +// If the retention period is decreased and the bucket is locked, +// FAILED_PRECONDITION will be returned. +// +// If the bucket has a lifecycle_state of DELETE_REQUESTED, then +// FAILED_PRECONDITION will be returned. +// +// After a bucket has been created, the bucket’s location cannot be changed. +func (c *configRESTClient) UpdateBucket(ctx context.Context, req *loggingpb.UpdateBucketRequest, opts ...gax.CallOption) (*loggingpb.LogBucket, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetBucket() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateBucket[0:len((*c.CallOptions).UpdateBucket):len((*c.CallOptions).UpdateBucket)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &loggingpb.LogBucket{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteBucket deletes a log bucket. +// +// Changes the bucket’s lifecycle_state to the DELETE_REQUESTED state. +// After 7 days, the bucket will be purged and all log entries in the bucket +// will be permanently deleted. +func (c *configRESTClient) DeleteBucket(ctx context.Context, req *loggingpb.DeleteBucketRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// UndeleteBucket undeletes a log bucket. A bucket that has been deleted can be undeleted +// within the grace period of 7 days. +func (c *configRESTClient) UndeleteBucket(ctx context.Context, req *loggingpb.UndeleteBucketRequest, opts ...gax.CallOption) error { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:undelete", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// ListViews lists views on a log bucket. +func (c *configRESTClient) ListViews(ctx context.Context, req *loggingpb.ListViewsRequest, opts ...gax.CallOption) *LogViewIterator { + it := &LogViewIterator{} + req = proto.Clone(req).(*loggingpb.ListViewsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*loggingpb.LogView, string, error) { + resp := &loggingpb.ListViewsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/views", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetViews(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetView gets a view on a log bucket… +func (c *configRESTClient) GetView(ctx context.Context, req *loggingpb.GetViewRequest, opts ...gax.CallOption) (*loggingpb.LogView, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetView[0:len((*c.CallOptions).GetView):len((*c.CallOptions).GetView)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &loggingpb.LogView{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateView creates a view over log entries in a log bucket. A bucket may contain a +// maximum of 30 views. +func (c *configRESTClient) CreateView(ctx context.Context, req *loggingpb.CreateViewRequest, opts ...gax.CallOption) (*loggingpb.LogView, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetView() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/views", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("viewId", fmt.Sprintf("%v", req.GetViewId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateView[0:len((*c.CallOptions).CreateView):len((*c.CallOptions).CreateView)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &loggingpb.LogView{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateView updates a view on a log bucket. This method replaces the following fields +// in the existing view with values from the new view: filter. +// If an UNAVAILABLE error is returned, this indicates that system is not in +// a state where it can update the view. If this occurs, please try again in a +// few minutes. +func (c *configRESTClient) UpdateView(ctx context.Context, req *loggingpb.UpdateViewRequest, opts ...gax.CallOption) (*loggingpb.LogView, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetView() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateView[0:len((*c.CallOptions).UpdateView):len((*c.CallOptions).UpdateView)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &loggingpb.LogView{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteView deletes a view on a log bucket. +// If an UNAVAILABLE error is returned, this indicates that system is not in +// a state where it can delete the view. If this occurs, please try again in a +// few minutes. +func (c *configRESTClient) DeleteView(ctx context.Context, req *loggingpb.DeleteViewRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// ListSinks lists sinks. +func (c *configRESTClient) ListSinks(ctx context.Context, req *loggingpb.ListSinksRequest, opts ...gax.CallOption) *LogSinkIterator { + it := &LogSinkIterator{} + req = proto.Clone(req).(*loggingpb.ListSinksRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*loggingpb.LogSink, string, error) { + resp := &loggingpb.ListSinksResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/sinks", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetSinks(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetSink gets a sink. +func (c *configRESTClient) GetSink(ctx context.Context, req *loggingpb.GetSinkRequest, opts ...gax.CallOption) (*loggingpb.LogSink, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetSinkName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "sink_name", url.QueryEscape(req.GetSinkName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetSink[0:len((*c.CallOptions).GetSink):len((*c.CallOptions).GetSink)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &loggingpb.LogSink{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateSink creates a sink that exports specified log entries to a destination. The +// export of newly-ingested log entries begins immediately, unless the sink’s +// writer_identity is not permitted to write to the destination. A sink can +// export log entries only from the resource owning the sink. +func (c *configRESTClient) CreateSink(ctx context.Context, req *loggingpb.CreateSinkRequest, opts ...gax.CallOption) (*loggingpb.LogSink, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetSink() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/sinks", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUniqueWriterIdentity() { + params.Add("uniqueWriterIdentity", fmt.Sprintf("%v", req.GetUniqueWriterIdentity())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateSink[0:len((*c.CallOptions).CreateSink):len((*c.CallOptions).CreateSink)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &loggingpb.LogSink{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateSink updates a sink. This method replaces the following fields in the existing +// sink with values from the new sink: destination, and filter. +// +// The updated sink might also have a new writer_identity; see the +// unique_writer_identity field. +func (c *configRESTClient) UpdateSink(ctx context.Context, req *loggingpb.UpdateSinkRequest, opts ...gax.CallOption) (*loggingpb.LogSink, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetSink() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetSinkName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUniqueWriterIdentity() { + params.Add("uniqueWriterIdentity", fmt.Sprintf("%v", req.GetUniqueWriterIdentity())) + } + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "sink_name", url.QueryEscape(req.GetSinkName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateSink[0:len((*c.CallOptions).UpdateSink):len((*c.CallOptions).UpdateSink)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &loggingpb.LogSink{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PUT", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteSink deletes a sink. If the sink has a unique writer_identity, then that +// service account is also deleted. +func (c *configRESTClient) DeleteSink(ctx context.Context, req *loggingpb.DeleteSinkRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetSinkName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "sink_name", url.QueryEscape(req.GetSinkName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// ListExclusions lists all the exclusions on the _Default sink in a parent resource. +func (c *configRESTClient) ListExclusions(ctx context.Context, req *loggingpb.ListExclusionsRequest, opts ...gax.CallOption) *LogExclusionIterator { + it := &LogExclusionIterator{} + req = proto.Clone(req).(*loggingpb.ListExclusionsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*loggingpb.LogExclusion, string, error) { + resp := &loggingpb.ListExclusionsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/exclusions", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetExclusions(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetExclusion gets the description of an exclusion in the _Default sink. +func (c *configRESTClient) GetExclusion(ctx context.Context, req *loggingpb.GetExclusionRequest, opts ...gax.CallOption) (*loggingpb.LogExclusion, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetExclusion[0:len((*c.CallOptions).GetExclusion):len((*c.CallOptions).GetExclusion)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &loggingpb.LogExclusion{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateExclusion creates a new exclusion in the _Default sink in a specified parent +// resource. Only log entries belonging to that resource can be excluded. You +// can have up to 10 exclusions in a resource. +func (c *configRESTClient) CreateExclusion(ctx context.Context, req *loggingpb.CreateExclusionRequest, opts ...gax.CallOption) (*loggingpb.LogExclusion, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetExclusion() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/exclusions", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateExclusion[0:len((*c.CallOptions).CreateExclusion):len((*c.CallOptions).CreateExclusion)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &loggingpb.LogExclusion{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateExclusion changes one or more properties of an existing exclusion in the _Default +// sink. +func (c *configRESTClient) UpdateExclusion(ctx context.Context, req *loggingpb.UpdateExclusionRequest, opts ...gax.CallOption) (*loggingpb.LogExclusion, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetExclusion() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateExclusion[0:len((*c.CallOptions).UpdateExclusion):len((*c.CallOptions).UpdateExclusion)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &loggingpb.LogExclusion{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteExclusion deletes an exclusion in the _Default sink. +func (c *configRESTClient) DeleteExclusion(ctx context.Context, req *loggingpb.DeleteExclusionRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetCmekSettings gets the Logging CMEK settings for the given resource. +// +// Note: CMEK for the Log Router can be configured for Google Cloud projects, +// folders, organizations and billing accounts. Once configured for an +// organization, it applies to all projects and folders in the Google Cloud +// organization. +// +// See Enabling CMEK for Log +// Router (at https://cloud.google.com/logging/docs/routing/managed-encryption) +// for more information. +func (c *configRESTClient) GetCmekSettings(ctx context.Context, req *loggingpb.GetCmekSettingsRequest, opts ...gax.CallOption) (*loggingpb.CmekSettings, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/cmekSettings", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetCmekSettings[0:len((*c.CallOptions).GetCmekSettings):len((*c.CallOptions).GetCmekSettings)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &loggingpb.CmekSettings{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateCmekSettings updates the Log Router CMEK settings for the given resource. +// +// Note: CMEK for the Log Router can currently only be configured for Google +// Cloud organizations. Once configured, it applies to all projects and +// folders in the Google Cloud organization. +// +// UpdateCmekSettings +// will fail if 1) kms_key_name is invalid, or 2) the associated service +// account does not have the required +// roles/cloudkms.cryptoKeyEncrypterDecrypter role assigned for the key, or +// 3) access to the key is disabled. +// +// See Enabling CMEK for Log +// Router (at https://cloud.google.com/logging/docs/routing/managed-encryption) +// for more information. +func (c *configRESTClient) UpdateCmekSettings(ctx context.Context, req *loggingpb.UpdateCmekSettingsRequest, opts ...gax.CallOption) (*loggingpb.CmekSettings, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetCmekSettings() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/cmekSettings", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateCmekSettings[0:len((*c.CallOptions).UpdateCmekSettings):len((*c.CallOptions).UpdateCmekSettings)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &loggingpb.CmekSettings{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetSettings gets the Log Router settings for the given resource. +// +// Note: Settings for the Log Router can be get for Google Cloud projects, +// folders, organizations and billing accounts. Currently it can only be +// configured for organizations. Once configured for an organization, it +// applies to all projects and folders in the Google Cloud organization. +// +// See Enabling CMEK for Log +// Router (at https://cloud.google.com/logging/docs/routing/managed-encryption) +// for more information. +func (c *configRESTClient) GetSettings(ctx context.Context, req *loggingpb.GetSettingsRequest, opts ...gax.CallOption) (*loggingpb.Settings, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/settings", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetSettings[0:len((*c.CallOptions).GetSettings):len((*c.CallOptions).GetSettings)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &loggingpb.Settings{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateSettings updates the Log Router settings for the given resource. +// +// Note: Settings for the Log Router can currently only be configured for +// Google Cloud organizations. Once configured, it applies to all projects and +// folders in the Google Cloud organization. +// +// UpdateSettings +// will fail if 1) kms_key_name is invalid, or 2) the associated service +// account does not have the required +// roles/cloudkms.cryptoKeyEncrypterDecrypter role assigned for the key, or +// 3) access to the key is disabled. 4) location_id is not supported by +// Logging. 5) location_id violate OrgPolicy. +// +// See Enabling CMEK for Log +// Router (at https://cloud.google.com/logging/docs/routing/managed-encryption) +// for more information. +func (c *configRESTClient) UpdateSettings(ctx context.Context, req *loggingpb.UpdateSettingsRequest, opts ...gax.CallOption) (*loggingpb.Settings, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetSettings() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/settings", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateSettings[0:len((*c.CallOptions).UpdateSettings):len((*c.CallOptions).UpdateSettings)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &loggingpb.Settings{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CopyLogEntries copies a set of log entries from a log bucket to a Cloud Storage bucket. +func (c *configRESTClient) CopyLogEntries(ctx context.Context, req *loggingpb.CopyLogEntriesRequest, opts ...gax.CallOption) (*CopyLogEntriesOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/entries:copy") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &CopyLogEntriesOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// CopyLogEntriesOperation manages a long-running operation from CopyLogEntries. +type CopyLogEntriesOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CopyLogEntriesOperation returns a new CopyLogEntriesOperation from a given name. +// The name must be that of a previously created CopyLogEntriesOperation, possibly from a different process. +func (c *configGRPCClient) CopyLogEntriesOperation(name string) *CopyLogEntriesOperation { + return &CopyLogEntriesOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CopyLogEntriesOperation returns a new CopyLogEntriesOperation from a given name. +// The name must be that of a previously created CopyLogEntriesOperation, possibly from a different process. +func (c *configRESTClient) CopyLogEntriesOperation(name string) *CopyLogEntriesOperation { + override := fmt.Sprintf("/v2/%s", name) + return &CopyLogEntriesOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, } } @@ -1176,6 +3137,7 @@ func (c *configGRPCClient) CopyLogEntriesOperation(name string) *CopyLogEntriesO // // See documentation of Poll for error-handling information. func (op *CopyLogEntriesOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*loggingpb.CopyLogEntriesResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp loggingpb.CopyLogEntriesResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1193,6 +3155,7 @@ func (op *CopyLogEntriesOperation) Wait(ctx context.Context, opts ...gax.CallOpt // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CopyLogEntriesOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*loggingpb.CopyLogEntriesResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp loggingpb.CopyLogEntriesResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/logging/apiv2/config_client_example_test.go b/logging/apiv2/config_client_example_test.go index 5fa2f9c48a33..bdeb3671514e 100644 --- a/logging/apiv2/config_client_example_test.go +++ b/logging/apiv2/config_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewConfigClient() { _ = c } +func ExampleNewConfigRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := logging.NewConfigRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleConfigClient_ListBuckets() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/logging/apiv2/doc.go b/logging/apiv2/doc.go index 5a35c38b61d8..ed15e5cf9cd7 100644 --- a/logging/apiv2/doc.go +++ b/logging/apiv2/doc.go @@ -78,6 +78,8 @@ package logging // import "cloud.google.com/go/logging/apiv2" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -170,3 +172,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/logging/apiv2/gapic_metadata.json b/logging/apiv2/gapic_metadata.json index b125a4fa1dc2..7772e8fc5a04 100644 --- a/logging/apiv2/gapic_metadata.json +++ b/logging/apiv2/gapic_metadata.json @@ -141,6 +141,141 @@ ] } } + }, + "rest": { + "libraryClient": "ConfigClient", + "rpcs": { + "CopyLogEntries": { + "methods": [ + "CopyLogEntries" + ] + }, + "CreateBucket": { + "methods": [ + "CreateBucket" + ] + }, + "CreateExclusion": { + "methods": [ + "CreateExclusion" + ] + }, + "CreateSink": { + "methods": [ + "CreateSink" + ] + }, + "CreateView": { + "methods": [ + "CreateView" + ] + }, + "DeleteBucket": { + "methods": [ + "DeleteBucket" + ] + }, + "DeleteExclusion": { + "methods": [ + "DeleteExclusion" + ] + }, + "DeleteSink": { + "methods": [ + "DeleteSink" + ] + }, + "DeleteView": { + "methods": [ + "DeleteView" + ] + }, + "GetBucket": { + "methods": [ + "GetBucket" + ] + }, + "GetCmekSettings": { + "methods": [ + "GetCmekSettings" + ] + }, + "GetExclusion": { + "methods": [ + "GetExclusion" + ] + }, + "GetSettings": { + "methods": [ + "GetSettings" + ] + }, + "GetSink": { + "methods": [ + "GetSink" + ] + }, + "GetView": { + "methods": [ + "GetView" + ] + }, + "ListBuckets": { + "methods": [ + "ListBuckets" + ] + }, + "ListExclusions": { + "methods": [ + "ListExclusions" + ] + }, + "ListSinks": { + "methods": [ + "ListSinks" + ] + }, + "ListViews": { + "methods": [ + "ListViews" + ] + }, + "UndeleteBucket": { + "methods": [ + "UndeleteBucket" + ] + }, + "UpdateBucket": { + "methods": [ + "UpdateBucket" + ] + }, + "UpdateCmekSettings": { + "methods": [ + "UpdateCmekSettings" + ] + }, + "UpdateExclusion": { + "methods": [ + "UpdateExclusion" + ] + }, + "UpdateSettings": { + "methods": [ + "UpdateSettings" + ] + }, + "UpdateSink": { + "methods": [ + "UpdateSink" + ] + }, + "UpdateView": { + "methods": [ + "UpdateView" + ] + } + } } } }, @@ -180,6 +315,41 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "DeleteLog": { + "methods": [ + "DeleteLog" + ] + }, + "ListLogEntries": { + "methods": [ + "ListLogEntries" + ] + }, + "ListLogs": { + "methods": [ + "ListLogs" + ] + }, + "ListMonitoredResourceDescriptors": { + "methods": [ + "ListMonitoredResourceDescriptors" + ] + }, + "TailLogEntries": { + "methods": [ + "TailLogEntries" + ] + }, + "WriteLogEntries": { + "methods": [ + "WriteLogEntries" + ] + } + } } } }, @@ -214,6 +384,36 @@ ] } } + }, + "rest": { + "libraryClient": "MetricsClient", + "rpcs": { + "CreateLogMetric": { + "methods": [ + "CreateLogMetric" + ] + }, + "DeleteLogMetric": { + "methods": [ + "DeleteLogMetric" + ] + }, + "GetLogMetric": { + "methods": [ + "GetLogMetric" + ] + }, + "ListLogMetrics": { + "methods": [ + "ListLogMetrics" + ] + }, + "UpdateLogMetric": { + "methods": [ + "UpdateLogMetric" + ] + } + } } } } diff --git a/logging/apiv2/logging_client.go b/logging/apiv2/logging_client.go index 5db69be76b4c..14f9bc5c5a22 100644 --- a/logging/apiv2/logging_client.go +++ b/logging/apiv2/logging_client.go @@ -17,22 +17,28 @@ package logging import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" loggingpb "cloud.google.com/go/logging/apiv2/loggingpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" monitoredrespb "google.golang.org/genproto/googleapis/api/monitoredres" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -143,6 +149,83 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + DeleteLog: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusInternalServerError, + http.StatusServiceUnavailable) + }), + }, + WriteLogEntries: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusInternalServerError, + http.StatusServiceUnavailable) + }), + }, + ListLogEntries: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusInternalServerError, + http.StatusServiceUnavailable) + }), + }, + ListMonitoredResourceDescriptors: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusInternalServerError, + http.StatusServiceUnavailable) + }), + }, + ListLogs: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusInternalServerError, + http.StatusServiceUnavailable) + }), + }, + TailLogEntries: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusInternalServerError, + http.StatusServiceUnavailable) + }), + }, + } +} + // internalClient is an interface that defines the methods available from Cloud Logging API. type internalClient interface { Close() error @@ -231,6 +314,8 @@ func (c *Client) ListLogs(ctx context.Context, req *loggingpb.ListLogsRequest, o // TailLogEntries streaming read of log entries as they are ingested. Until the stream is // terminated, it will continue reading logs. +// +// This method is not supported for the REST transport. func (c *Client) TailLogEntries(ctx context.Context, opts ...gax.CallOption) (loggingpb.LoggingServiceV2_TailLogEntriesClient, error) { return c.internalClient.TailLogEntries(ctx, opts...) } @@ -316,6 +401,74 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new logging service v2 rest client. +// +// Service for ingesting and querying logs. +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://logging.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://logging.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://logging.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) DeleteLog(ctx context.Context, req *loggingpb.DeleteLogRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) @@ -500,6 +653,398 @@ func (c *gRPCClient) TailLogEntries(ctx context.Context, opts ...gax.CallOption) return resp, nil } +// DeleteLog deletes all the log entries in a log for the _Default Log Bucket. The log +// reappears if it receives new entries. Log entries written shortly before +// the delete operation might not be deleted. Entries received after the +// delete operation with a timestamp before the operation will be deleted. +func (c *restClient) DeleteLog(ctx context.Context, req *loggingpb.DeleteLogRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetLogName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "log_name", url.QueryEscape(req.GetLogName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// WriteLogEntries writes log entries to Logging. This API method is the +// only way to send log entries to Logging. This method +// is used, directly or indirectly, by the Logging agent +// (fluentd) and all logging libraries configured to use Logging. +// A single request may contain log entries for a maximum of 1000 +// different resources (projects, organizations, billing accounts or +// folders) +func (c *restClient) WriteLogEntries(ctx context.Context, req *loggingpb.WriteLogEntriesRequest, opts ...gax.CallOption) (*loggingpb.WriteLogEntriesResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/entries:write") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).WriteLogEntries[0:len((*c.CallOptions).WriteLogEntries):len((*c.CallOptions).WriteLogEntries)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &loggingpb.WriteLogEntriesResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLogEntries lists log entries. Use this method to retrieve log entries that originated +// from a project/folder/organization/billing account. For ways to export log +// entries, see Exporting +// Logs (at https://cloud.google.com/logging/docs/export). +func (c *restClient) ListLogEntries(ctx context.Context, req *loggingpb.ListLogEntriesRequest, opts ...gax.CallOption) *LogEntryIterator { + it := &LogEntryIterator{} + req = proto.Clone(req).(*loggingpb.ListLogEntriesRequest) + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*loggingpb.LogEntry, string, error) { + resp := &loggingpb.ListLogEntriesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, "", err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/entries:list") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetEntries(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// ListMonitoredResourceDescriptors lists the descriptors for monitored resource types used by Logging. +func (c *restClient) ListMonitoredResourceDescriptors(ctx context.Context, req *loggingpb.ListMonitoredResourceDescriptorsRequest, opts ...gax.CallOption) *MonitoredResourceDescriptorIterator { + it := &MonitoredResourceDescriptorIterator{} + req = proto.Clone(req).(*loggingpb.ListMonitoredResourceDescriptorsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*monitoredrespb.MonitoredResourceDescriptor, string, error) { + resp := &loggingpb.ListMonitoredResourceDescriptorsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/monitoredResourceDescriptors") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetResourceDescriptors(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// ListLogs lists the logs in projects, organizations, folders, or billing accounts. +// Only logs that have entries are listed. +func (c *restClient) ListLogs(ctx context.Context, req *loggingpb.ListLogsRequest, opts ...gax.CallOption) *StringIterator { + it := &StringIterator{} + req = proto.Clone(req).(*loggingpb.ListLogsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]string, string, error) { + resp := &loggingpb.ListLogsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/logs", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + if items := req.GetResourceNames(); len(items) > 0 { + for _, item := range items { + params.Add("resourceNames", fmt.Sprintf("%v", item)) + } + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLogNames(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// TailLogEntries streaming read of log entries as they are ingested. Until the stream is +// terminated, it will continue reading logs. +// +// This method is not supported for the REST transport. +func (c *restClient) TailLogEntries(ctx context.Context, opts ...gax.CallOption) (loggingpb.LoggingServiceV2_TailLogEntriesClient, error) { + return nil, fmt.Errorf("TailLogEntries not yet supported for REST clients") +} + // LogEntryIterator manages a stream of *loggingpb.LogEntry. type LogEntryIterator struct { items []*loggingpb.LogEntry diff --git a/logging/apiv2/logging_client_example_test.go b/logging/apiv2/logging_client_example_test.go index 93373c824203..11846a46535b 100644 --- a/logging/apiv2/logging_client_example_test.go +++ b/logging/apiv2/logging_client_example_test.go @@ -42,6 +42,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := logging.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_DeleteLog() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/logging/apiv2/loggingpb/log_entry.pb.go b/logging/apiv2/loggingpb/log_entry.pb.go index 5ee4fb37bd53..d93fd60c8c45 100644 --- a/logging/apiv2/loggingpb/log_entry.pb.go +++ b/logging/apiv2/loggingpb/log_entry.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/logging/v2/log_entry.proto package loggingpb @@ -49,10 +49,10 @@ type LogEntry struct { // Required. The resource name of the log to which this log entry belongs: // - // "projects/[PROJECT_ID]/logs/[LOG_ID]" - // "organizations/[ORGANIZATION_ID]/logs/[LOG_ID]" - // "billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]" - // "folders/[FOLDER_ID]/logs/[LOG_ID]" + // "projects/[PROJECT_ID]/logs/[LOG_ID]" + // "organizations/[ORGANIZATION_ID]/logs/[LOG_ID]" + // "billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]" + // "folders/[FOLDER_ID]/logs/[LOG_ID]" // // A project number may be used in place of PROJECT_ID. The project number is // translated to its corresponding PROJECT_ID internally and the `log_name` @@ -80,7 +80,6 @@ type LogEntry struct { // The log entry payload, which can be one of multiple types. // // Types that are assignable to Payload: - // // *LogEntry_ProtoPayload // *LogEntry_TextPayload // *LogEntry_JsonPayload @@ -252,7 +251,7 @@ func (x *LogEntry) GetSeverity() _type.LogSeverity { if x != nil { return x.Severity } - return _type.LogSeverity_DEFAULT + return _type.LogSeverity(0) } func (x *LogEntry) GetInsertId() string { @@ -329,8 +328,8 @@ type LogEntry_ProtoPayload struct { // The following protocol buffer types are supported; user-defined types // are not supported: // - // "type.googleapis.com/google.cloud.audit.AuditLog" - // "type.googleapis.com/google.appengine.logging.v1.RequestLog" + // "type.googleapis.com/google.cloud.audit.AuditLog" + // "type.googleapis.com/google.appengine.logging.v1.RequestLog" ProtoPayload *anypb.Any `protobuf:"bytes,2,opt,name=proto_payload,json=protoPayload,proto3,oneof"` } diff --git a/logging/apiv2/loggingpb/logging.pb.go b/logging/apiv2/loggingpb/logging.pb.go index cbc6ce968bf0..4ea22fb31186 100644 --- a/logging/apiv2/loggingpb/logging.pb.go +++ b/logging/apiv2/loggingpb/logging.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/logging/v2/logging.proto package loggingpb @@ -178,8 +178,8 @@ type WriteLogEntriesRequest struct { // // `[LOG_ID]` must be URL-encoded. For example: // - // "projects/my-project-id/logs/syslog" - // "organizations/123/logs/cloudaudit.googleapis.com%2Factivity" + // "projects/my-project-id/logs/syslog" + // "organizations/123/logs/cloudaudit.googleapis.com%2Factivity" // // The permission `logging.logEntries.create` is needed on each project, // organization, billing account, or folder that is receiving new log @@ -189,9 +189,9 @@ type WriteLogEntriesRequest struct { // Optional. A default monitored resource object that is assigned to all log // entries in `entries` that do not specify a value for `resource`. Example: // - // { "type": "gce_instance", - // "labels": { - // "zone": "us-central1-a", "instance_id": "00000000000000000000" }} + // { "type": "gce_instance", + // "labels": { + // "zone": "us-central1-a", "instance_id": "00000000000000000000" }} // // See [LogEntry][google.logging.v2.LogEntry]. Resource *monitoredres.MonitoredResource `protobuf:"bytes,2,opt,name=resource,proto3" json:"resource,omitempty"` @@ -420,10 +420,10 @@ type ListLogEntriesRequest struct { // // May alternatively be one or more views: // - // - `projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` - // - `organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` - // - `billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` - // - `folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` + // * `projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` + // * `organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` + // * `billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` + // * `folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` // // Projects listed in the `project_ids` field are added to this list. ResourceNames []string `protobuf:"bytes,8,rep,name=resource_names,json=resourceNames,proto3" json:"resource_names,omitempty"` @@ -737,10 +737,10 @@ type ListLogsRequest struct { PageToken string `protobuf:"bytes,3,opt,name=page_token,json=pageToken,proto3" json:"page_token,omitempty"` // Optional. The resource name that owns the logs: // - // - `projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` - // - `organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` - // - `billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` - // - `folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` + // * `projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` + // * `organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` + // * `billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` + // * `folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` // // To support legacy queries, it could also be: // @@ -888,10 +888,10 @@ type TailLogEntriesRequest struct { // // May alternatively be one or more views: // - // - `projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` - // - `organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` - // - `billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` - // - `folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` + // * `projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` + // * `organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` + // * `billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` + // * `folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]` ResourceNames []string `protobuf:"bytes,1,rep,name=resource_names,json=resourceNames,proto3" json:"resource_names,omitempty"` // Optional. A filter that chooses which log entries to return. See [Advanced // Logs Filters](https://cloud.google.com/logging/docs/view/advanced_filters). diff --git a/logging/apiv2/loggingpb/logging_config.pb.go b/logging/apiv2/loggingpb/logging_config.pb.go index 95ba5c66bbe7..dae342dfe4bb 100644 --- a/logging/apiv2/loggingpb/logging_config.pb.go +++ b/logging/apiv2/loggingpb/logging_config.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/logging/v2/logging_config.proto package loggingpb @@ -235,7 +235,7 @@ type LogBucket struct { // // For example: // - // `projects/my-project/locations/global/buckets/my-bucket` + // `projects/my-project/locations/global/buckets/my-bucket` // // For a list of supported locations, see [Supported // Regions](https://cloud.google.com/logging/docs/region-support) @@ -385,7 +385,7 @@ type LogView struct { // // For example: // - // `projects/my-project/locations/global/buckets/my-bucket/views/my-view` + // `projects/my-project/locations/global/buckets/my-bucket/views/my-view` Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Describes this view. Description string `protobuf:"bytes,3,opt,name=description,proto3" json:"description,omitempty"` @@ -405,8 +405,8 @@ type LogView struct { // // For example: // - // SOURCE("projects/myproject") AND resource.type = "gce_instance" - // AND LOG_ID("stdout") + // SOURCE("projects/myproject") AND resource.type = "gce_instance" + // AND LOG_ID("stdout") Filter string `protobuf:"bytes,7,opt,name=filter,proto3" json:"filter,omitempty"` } @@ -496,9 +496,9 @@ type LogSink struct { Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Required. The export destination: // - // "storage.googleapis.com/[GCS_BUCKET]" - // "bigquery.googleapis.com/projects/[PROJECT_ID]/datasets/[DATASET]" - // "pubsub.googleapis.com/projects/[PROJECT_ID]/topics/[TOPIC_ID]" + // "storage.googleapis.com/[GCS_BUCKET]" + // "bigquery.googleapis.com/projects/[PROJECT_ID]/datasets/[DATASET]" + // "pubsub.googleapis.com/projects/[PROJECT_ID]/topics/[TOPIC_ID]" // // The sink's `writer_identity`, set when the sink is created, must have // permission to write to the destination or else the log entries are not @@ -513,7 +513,7 @@ type LogSink struct { // // For example: // - // `logName="projects/[PROJECT_ID]/logs/[LOG_ID]" AND severity>=ERROR` + // `logName="projects/[PROJECT_ID]/logs/[LOG_ID]" AND severity>=ERROR` Filter string `protobuf:"bytes,5,opt,name=filter,proto3" json:"filter,omitempty"` // Optional. A description of this sink. // @@ -564,13 +564,12 @@ type LogSink struct { // To only export entries from certain child projects, filter on the project // part of the log name: // - // logName:("projects/test-project1/" OR "projects/test-project2/") AND - // resource.type=gce_instance + // logName:("projects/test-project1/" OR "projects/test-project2/") AND + // resource.type=gce_instance IncludeChildren bool `protobuf:"varint,9,opt,name=include_children,json=includeChildren,proto3" json:"include_children,omitempty"` // Destination dependent options. // // Types that are assignable to Options: - // // *LogSink_BigqueryOptions Options isLogSink_Options `protobuf_oneof:"options"` // Output only. The creation timestamp of the sink. @@ -797,10 +796,10 @@ type ListBucketsRequest struct { // Required. The parent resource whose buckets are to be listed: // - // "projects/[PROJECT_ID]/locations/[LOCATION_ID]" - // "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]" - // "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]" - // "folders/[FOLDER_ID]/locations/[LOCATION_ID]" + // "projects/[PROJECT_ID]/locations/[LOCATION_ID]" + // "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]" + // "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]" + // "folders/[FOLDER_ID]/locations/[LOCATION_ID]" // // Note: The locations portion of the resource must be specified, but // supplying the character `-` in place of [LOCATION_ID] will return all @@ -938,11 +937,11 @@ type CreateBucketRequest struct { // Required. The resource in which to create the log bucket: // - // "projects/[PROJECT_ID]/locations/[LOCATION_ID]" + // "projects/[PROJECT_ID]/locations/[LOCATION_ID]" // // For example: // - // `"projects/my-project/locations/global"` + // `"projects/my-project/locations/global"` Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // Required. A client-assigned identifier such as `"my-bucket"`. Identifiers are limited // to 100 characters and can include only letters, digits, underscores, @@ -1015,14 +1014,14 @@ type UpdateBucketRequest struct { // Required. The full resource name of the bucket to update. // - // "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - // "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - // "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - // "folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + // "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + // "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + // "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + // "folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" // // For example: // - // `"projects/my-project/locations/global/buckets/my-bucket"` + // `"projects/my-project/locations/global/buckets/my-bucket"` Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Required. The updated bucket. Bucket *LogBucket `protobuf:"bytes,2,opt,name=bucket,proto3" json:"bucket,omitempty"` @@ -1098,14 +1097,14 @@ type GetBucketRequest struct { // Required. The resource name of the bucket: // - // "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - // "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - // "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - // "folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + // "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + // "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + // "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + // "folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" // // For example: // - // `"projects/my-project/locations/global/buckets/my-bucket"` + // `"projects/my-project/locations/global/buckets/my-bucket"` Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` } @@ -1156,14 +1155,14 @@ type DeleteBucketRequest struct { // Required. The full resource name of the bucket to delete. // - // "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - // "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - // "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - // "folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + // "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + // "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + // "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + // "folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" // // For example: // - // `"projects/my-project/locations/global/buckets/my-bucket"` + // `"projects/my-project/locations/global/buckets/my-bucket"` Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` } @@ -1214,14 +1213,14 @@ type UndeleteBucketRequest struct { // Required. The full resource name of the bucket to undelete. // - // "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - // "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - // "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" - // "folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + // "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + // "organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + // "billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + // "folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" // // For example: // - // `"projects/my-project/locations/global/buckets/my-bucket"` + // `"projects/my-project/locations/global/buckets/my-bucket"` Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` } @@ -1272,7 +1271,7 @@ type ListViewsRequest struct { // Required. The bucket whose views are to be listed: // - // "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" + // "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]" Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // Optional. If present, then retrieve the next batch of results from the preceding call // to this method. `pageToken` must be the value of `nextPageToken` from the @@ -1407,11 +1406,11 @@ type CreateViewRequest struct { // Required. The bucket in which to create the view // - // `"projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]"` + // `"projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]"` // // For example: // - // `"projects/my-project/locations/global/buckets/my-bucket"` + // `"projects/my-project/locations/global/buckets/my-bucket"` Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // Required. The id to use for this view. ViewId string `protobuf:"bytes,2,opt,name=view_id,json=viewId,proto3" json:"view_id,omitempty"` @@ -1480,11 +1479,11 @@ type UpdateViewRequest struct { // Required. The full resource name of the view to update // - // "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]" + // "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]" // // For example: // - // `"projects/my-project/locations/global/buckets/my-bucket/views/my-view"` + // `"projects/my-project/locations/global/buckets/my-bucket/views/my-view"` Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Required. The updated view. View *LogView `protobuf:"bytes,2,opt,name=view,proto3" json:"view,omitempty"` @@ -1560,11 +1559,11 @@ type GetViewRequest struct { // Required. The resource name of the policy: // - // "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]" + // "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]" // // For example: // - // `"projects/my-project/locations/global/buckets/my-bucket/views/my-view"` + // `"projects/my-project/locations/global/buckets/my-bucket/views/my-view"` Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` } @@ -1615,11 +1614,11 @@ type DeleteViewRequest struct { // Required. The full resource name of the view to delete: // - // "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]" + // "projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]" // // For example: // - // `"projects/my-project/locations/global/buckets/my-bucket/views/my-view"` + // `"projects/my-project/locations/global/buckets/my-bucket/views/my-view"` Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` } @@ -1670,10 +1669,10 @@ type ListSinksRequest struct { // Required. The parent resource whose sinks are to be listed: // - // "projects/[PROJECT_ID]" - // "organizations/[ORGANIZATION_ID]" - // "billingAccounts/[BILLING_ACCOUNT_ID]" - // "folders/[FOLDER_ID]" + // "projects/[PROJECT_ID]" + // "organizations/[ORGANIZATION_ID]" + // "billingAccounts/[BILLING_ACCOUNT_ID]" + // "folders/[FOLDER_ID]" Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // Optional. If present, then retrieve the next batch of results from the // preceding call to this method. `pageToken` must be the value of @@ -1807,14 +1806,14 @@ type GetSinkRequest struct { // Required. The resource name of the sink: // - // "projects/[PROJECT_ID]/sinks/[SINK_ID]" - // "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" - // "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" - // "folders/[FOLDER_ID]/sinks/[SINK_ID]" + // "projects/[PROJECT_ID]/sinks/[SINK_ID]" + // "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" + // "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" + // "folders/[FOLDER_ID]/sinks/[SINK_ID]" // // For example: // - // `"projects/my-project/sinks/my-sink"` + // `"projects/my-project/sinks/my-sink"` SinkName string `protobuf:"bytes,1,opt,name=sink_name,json=sinkName,proto3" json:"sink_name,omitempty"` } @@ -1865,15 +1864,15 @@ type CreateSinkRequest struct { // Required. The resource in which to create the sink: // - // "projects/[PROJECT_ID]" - // "organizations/[ORGANIZATION_ID]" - // "billingAccounts/[BILLING_ACCOUNT_ID]" - // "folders/[FOLDER_ID]" + // "projects/[PROJECT_ID]" + // "organizations/[ORGANIZATION_ID]" + // "billingAccounts/[BILLING_ACCOUNT_ID]" + // "folders/[FOLDER_ID]" // // For examples: // - // `"projects/my-project"` - // `"organizations/123456789"` + // `"projects/my-project"` + // `"organizations/123456789"` Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // Required. The new sink, whose `name` parameter is a sink identifier that // is not already in use. @@ -1954,14 +1953,14 @@ type UpdateSinkRequest struct { // Required. The full resource name of the sink to update, including the parent // resource and the sink identifier: // - // "projects/[PROJECT_ID]/sinks/[SINK_ID]" - // "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" - // "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" - // "folders/[FOLDER_ID]/sinks/[SINK_ID]" + // "projects/[PROJECT_ID]/sinks/[SINK_ID]" + // "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" + // "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" + // "folders/[FOLDER_ID]/sinks/[SINK_ID]" // // For example: // - // `"projects/my-project/sinks/my-sink"` + // `"projects/my-project/sinks/my-sink"` SinkName string `protobuf:"bytes,1,opt,name=sink_name,json=sinkName,proto3" json:"sink_name,omitempty"` // Required. The updated sink, whose name is the same identifier that appears as part // of `sink_name`. @@ -1971,11 +1970,11 @@ type UpdateSinkRequest struct { // field on the value of `writer_identity` in the updated sink depends on both // the old and new values of this field: // - // - If the old and new values of this field are both false or both true, + // + If the old and new values of this field are both false or both true, // then there is no change to the sink's `writer_identity`. - // - If the old value is false and the new value is true, then + // + If the old value is false and the new value is true, then // `writer_identity` is changed to a unique service account. - // - It is an error if the old value is true and the new value is + // + It is an error if the old value is true and the new value is // set to false or defaulted to false. UniqueWriterIdentity bool `protobuf:"varint,3,opt,name=unique_writer_identity,json=uniqueWriterIdentity,proto3" json:"unique_writer_identity,omitempty"` // Optional. Field mask that specifies the fields in `sink` that need @@ -1985,7 +1984,7 @@ type UpdateSinkRequest struct { // An empty `updateMask` is temporarily treated as using the following mask // for backwards compatibility purposes: // - // `destination,filter,includeChildren` + // `destination,filter,includeChildren` // // At some point in the future, behavior will be removed and specifying an // empty `updateMask` will be an error. @@ -2066,14 +2065,14 @@ type DeleteSinkRequest struct { // Required. The full resource name of the sink to delete, including the parent // resource and the sink identifier: // - // "projects/[PROJECT_ID]/sinks/[SINK_ID]" - // "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" - // "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" - // "folders/[FOLDER_ID]/sinks/[SINK_ID]" + // "projects/[PROJECT_ID]/sinks/[SINK_ID]" + // "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" + // "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" + // "folders/[FOLDER_ID]/sinks/[SINK_ID]" // // For example: // - // `"projects/my-project/sinks/my-sink"` + // `"projects/my-project/sinks/my-sink"` SinkName string `protobuf:"bytes,1,opt,name=sink_name,json=sinkName,proto3" json:"sink_name,omitempty"` } @@ -2142,7 +2141,7 @@ type LogExclusion struct { // For example, the following query matches 99% of low-severity log entries // from Google Cloud Storage buckets: // - // `resource.type=gcs_bucket severity=ERROR" + // "resource.type=gae_app AND severity>=ERROR" // // The maximum length of the filter is 20000 characters. Filter string `protobuf:"bytes,3,opt,name=filter,proto3" json:"filter,omitempty"` @@ -159,14 +159,14 @@ type LogMetric struct { // logs-based metric to extract the values to record from a log entry. // Two functions are supported for value extraction: `EXTRACT(field)` or // `REGEXP_EXTRACT(field, regex)`. The argument are: - // 1. field: The name of the log entry field from which the value is to be - // extracted. - // 2. regex: A regular expression using the Google RE2 syntax - // (https://github.com/google/re2/wiki/Syntax) with a single capture - // group to extract data from the specified log entry field. The value - // of the field is converted to a string before applying the regex. - // It is an error to specify a regex that does not include exactly one - // capture group. + // 1. field: The name of the log entry field from which the value is to be + // extracted. + // 2. regex: A regular expression using the Google RE2 syntax + // (https://github.com/google/re2/wiki/Syntax) with a single capture + // group to extract data from the specified log entry field. The value + // of the field is converted to a string before applying the regex. + // It is an error to specify a regex that does not include exactly one + // capture group. // // The result of the extraction must be convertible to a double type, as the // distribution always records double values. If either the extraction or @@ -327,7 +327,7 @@ type ListLogMetricsRequest struct { // Required. The name of the project containing the metrics: // - // "projects/[PROJECT_ID]" + // "projects/[PROJECT_ID]" Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // Optional. If present, then retrieve the next batch of results from the // preceding call to this method. `pageToken` must be the value of @@ -461,7 +461,7 @@ type GetLogMetricRequest struct { // Required. The resource name of the desired metric: // - // "projects/[PROJECT_ID]/metrics/[METRIC_ID]" + // "projects/[PROJECT_ID]/metrics/[METRIC_ID]" MetricName string `protobuf:"bytes,1,opt,name=metric_name,json=metricName,proto3" json:"metric_name,omitempty"` } @@ -512,7 +512,7 @@ type CreateLogMetricRequest struct { // Required. The resource name of the project in which to create the metric: // - // "projects/[PROJECT_ID]" + // "projects/[PROJECT_ID]" // // The new metric must be provided in the request. Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` @@ -575,7 +575,7 @@ type UpdateLogMetricRequest struct { // Required. The resource name of the metric to update: // - // "projects/[PROJECT_ID]/metrics/[METRIC_ID]" + // "projects/[PROJECT_ID]/metrics/[METRIC_ID]" // // The updated metric must be provided in the request and it's // `name` field must be the same as `[METRIC_ID]` If the metric @@ -639,7 +639,7 @@ type DeleteLogMetricRequest struct { // Required. The resource name of the metric to delete: // - // "projects/[PROJECT_ID]/metrics/[METRIC_ID]" + // "projects/[PROJECT_ID]/metrics/[METRIC_ID]" MetricName string `protobuf:"bytes,1,opt,name=metric_name,json=metricName,proto3" json:"metric_name,omitempty"` } diff --git a/logging/apiv2/metrics_client.go b/logging/apiv2/metrics_client.go index b2ee28aada48..3dcb53ceeb04 100644 --- a/logging/apiv2/metrics_client.go +++ b/logging/apiv2/metrics_client.go @@ -17,21 +17,27 @@ package logging import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" loggingpb "cloud.google.com/go/logging/apiv2/loggingpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -116,6 +122,60 @@ func defaultMetricsCallOptions() *MetricsCallOptions { } } +func defaultMetricsRESTCallOptions() *MetricsCallOptions { + return &MetricsCallOptions{ + ListLogMetrics: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusInternalServerError, + http.StatusServiceUnavailable) + }), + }, + GetLogMetric: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusInternalServerError, + http.StatusServiceUnavailable) + }), + }, + CreateLogMetric: []gax.CallOption{}, + UpdateLogMetric: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusInternalServerError, + http.StatusServiceUnavailable) + }), + }, + DeleteLogMetric: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusInternalServerError, + http.StatusServiceUnavailable) + }), + }, + } +} + // internalMetricsClient is an interface that defines the methods available from Cloud Logging API. type internalMetricsClient interface { Close() error @@ -269,6 +329,74 @@ func (c *metricsGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type metricsRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing MetricsClient + CallOptions **MetricsCallOptions +} + +// NewMetricsRESTClient creates a new metrics service v2 rest client. +// +// Service for configuring logs-based metrics. +func NewMetricsRESTClient(ctx context.Context, opts ...option.ClientOption) (*MetricsClient, error) { + clientOpts := append(defaultMetricsRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultMetricsRESTCallOptions() + c := &metricsRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &MetricsClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultMetricsRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://logging.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://logging.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://logging.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *metricsRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *metricsRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *metricsRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *metricsGRPCClient) ListLogMetrics(ctx context.Context, req *loggingpb.ListLogMetricsRequest, opts ...gax.CallOption) *LogMetricIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -398,6 +526,322 @@ func (c *metricsGRPCClient) DeleteLogMetric(ctx context.Context, req *loggingpb. return err } +// ListLogMetrics lists logs-based metrics. +func (c *metricsRESTClient) ListLogMetrics(ctx context.Context, req *loggingpb.ListLogMetricsRequest, opts ...gax.CallOption) *LogMetricIterator { + it := &LogMetricIterator{} + req = proto.Clone(req).(*loggingpb.ListLogMetricsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*loggingpb.LogMetric, string, error) { + resp := &loggingpb.ListLogMetricsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/metrics", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetMetrics(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetLogMetric gets a logs-based metric. +func (c *metricsRESTClient) GetLogMetric(ctx context.Context, req *loggingpb.GetLogMetricRequest, opts ...gax.CallOption) (*loggingpb.LogMetric, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetMetricName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "metric_name", url.QueryEscape(req.GetMetricName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLogMetric[0:len((*c.CallOptions).GetLogMetric):len((*c.CallOptions).GetLogMetric)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &loggingpb.LogMetric{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateLogMetric creates a logs-based metric. +func (c *metricsRESTClient) CreateLogMetric(ctx context.Context, req *loggingpb.CreateLogMetricRequest, opts ...gax.CallOption) (*loggingpb.LogMetric, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetMetric() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/metrics", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateLogMetric[0:len((*c.CallOptions).CreateLogMetric):len((*c.CallOptions).CreateLogMetric)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &loggingpb.LogMetric{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateLogMetric creates or updates a logs-based metric. +func (c *metricsRESTClient) UpdateLogMetric(ctx context.Context, req *loggingpb.UpdateLogMetricRequest, opts ...gax.CallOption) (*loggingpb.LogMetric, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetMetric() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetMetricName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "metric_name", url.QueryEscape(req.GetMetricName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateLogMetric[0:len((*c.CallOptions).UpdateLogMetric):len((*c.CallOptions).UpdateLogMetric)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &loggingpb.LogMetric{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PUT", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteLogMetric deletes a logs-based metric. +func (c *metricsRESTClient) DeleteLogMetric(ctx context.Context, req *loggingpb.DeleteLogMetricRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetMetricName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "metric_name", url.QueryEscape(req.GetMetricName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + // LogMetricIterator manages a stream of *loggingpb.LogMetric. type LogMetricIterator struct { items []*loggingpb.LogMetric diff --git a/logging/apiv2/metrics_client_example_test.go b/logging/apiv2/metrics_client_example_test.go index 5df29046fe1e..5e0cad7c9d08 100644 --- a/logging/apiv2/metrics_client_example_test.go +++ b/logging/apiv2/metrics_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewMetricsClient() { _ = c } +func ExampleNewMetricsRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := logging.NewMetricsRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleMetricsClient_ListLogMetrics() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/longrunning/autogen/longrunningpb/operations.pb.go b/longrunning/autogen/longrunningpb/operations.pb.go index e979b7a8d93f..2a1b1ff13c50 100644 --- a/longrunning/autogen/longrunningpb/operations.pb.go +++ b/longrunning/autogen/longrunningpb/operations.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/longrunning/operations.proto package longrunningpb @@ -70,7 +70,6 @@ type Operation struct { // If `done` == `true`, exactly one of `error` or `response` is set. // // Types that are assignable to Result: - // // *Operation_Error // *Operation_Response Result isOperation_Result `protobuf_oneof:"result"` diff --git a/longrunning/autogen/operations_client.go b/longrunning/autogen/operations_client.go index a04f1e341f43..219bfffda1a5 100644 --- a/longrunning/autogen/operations_client.go +++ b/longrunning/autogen/operations_client.go @@ -585,6 +585,7 @@ func (c *operationsRESTClient) ListOperations(ctx context.Context, req *longrunn baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -663,6 +664,11 @@ func (c *operationsRESTClient) GetOperation(ctx context.Context, req *longrunnin } baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -719,6 +725,11 @@ func (c *operationsRESTClient) DeleteOperation(ctx context.Context, req *longrun } baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -769,6 +780,11 @@ func (c *operationsRESTClient) CancelOperation(ctx context.Context, req *longrun } baseUrl.Path += fmt.Sprintf("/v1/%v:cancel", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -813,6 +829,7 @@ func (c *operationsRESTClient) WaitOperation(ctx context.Context, req *longrunni baseUrl.Path += fmt.Sprintf("") params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetName() != "" { params.Add("name", fmt.Sprintf("%v", req.GetName())) } diff --git a/managedidentities/apiv1/doc.go b/managedidentities/apiv1/doc.go index 457324a1dbdc..e4c29f8475ff 100644 --- a/managedidentities/apiv1/doc.go +++ b/managedidentities/apiv1/doc.go @@ -87,6 +87,8 @@ package managedidentities // import "cloud.google.com/go/managedidentities/apiv1 import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -175,3 +177,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/managedidentities/apiv1/gapic_metadata.json b/managedidentities/apiv1/gapic_metadata.json index 4277b2fe80f1..3789c31376b9 100644 --- a/managedidentities/apiv1/gapic_metadata.json +++ b/managedidentities/apiv1/gapic_metadata.json @@ -61,6 +61,61 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "AttachTrust": { + "methods": [ + "AttachTrust" + ] + }, + "CreateMicrosoftAdDomain": { + "methods": [ + "CreateMicrosoftAdDomain" + ] + }, + "DeleteDomain": { + "methods": [ + "DeleteDomain" + ] + }, + "DetachTrust": { + "methods": [ + "DetachTrust" + ] + }, + "GetDomain": { + "methods": [ + "GetDomain" + ] + }, + "ListDomains": { + "methods": [ + "ListDomains" + ] + }, + "ReconfigureTrust": { + "methods": [ + "ReconfigureTrust" + ] + }, + "ResetAdminPassword": { + "methods": [ + "ResetAdminPassword" + ] + }, + "UpdateDomain": { + "methods": [ + "UpdateDomain" + ] + }, + "ValidateTrust": { + "methods": [ + "ValidateTrust" + ] + } + } } } } diff --git a/managedidentities/apiv1/managed_identities_client.go b/managedidentities/apiv1/managed_identities_client.go index c09834956bcd..beee676ba34b 100644 --- a/managedidentities/apiv1/managed_identities_client.go +++ b/managedidentities/apiv1/managed_identities_client.go @@ -17,9 +17,12 @@ package managedidentities import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,13 +30,16 @@ import ( lroauto "cloud.google.com/go/longrunning/autogen" managedidentitiespb "cloud.google.com/go/managedidentities/apiv1/managedidentitiespb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -80,6 +86,21 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + CreateMicrosoftAdDomain: []gax.CallOption{}, + ResetAdminPassword: []gax.CallOption{}, + ListDomains: []gax.CallOption{}, + GetDomain: []gax.CallOption{}, + UpdateDomain: []gax.CallOption{}, + DeleteDomain: []gax.CallOption{}, + AttachTrust: []gax.CallOption{}, + ReconfigureTrust: []gax.CallOption{}, + DetachTrust: []gax.CallOption{}, + ValidateTrust: []gax.CallOption{}, + } +} + // internalClient is an interface that defines the methods available from Managed Service for Microsoft Active Directory API. type internalClient interface { Close() error @@ -410,6 +431,127 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new managed identities service rest client. +// +// # API Overview +// +// The managedidentites.googleapis.com service implements the Google Cloud +// Managed Identites API for identity services +// (e.g. Microsoft Active Directory). +// +// The Managed Identities service provides methods to manage +// (create/read/update/delete) domains, reset managed identities admin password, +// add/remove domain controllers in GCP regions and add/remove VPC peering. +// +// # Data Model +// +// The Managed Identities service exposes the following resources: +// +// Locations as global, named as follows: +// projects/{project_id}/locations/global. +// +// Domains, named as follows: +// /projects/{project_id}/locations/global/domain/{domain_name}. +// +// The {domain_name} refers to fully qualified domain name in the customer +// project e.g. mydomain.myorganization.com (at http://mydomain.myorganization.com), with the following restrictions: +// +// Must contain only lowercase letters, numbers, periods and hyphens. +// +// Must start with a letter. +// +// Must contain between 2-64 characters. +// +// Must end with a number or a letter. +// +// Must not start with period. +// +// First segement length (mydomain form example above) shouldn’t exceed +// 15 chars. +// +// The last segment cannot be fully numeric. +// +// Must be unique within the customer project. +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://managedidentities.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://managedidentities.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://managedidentities.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) CreateMicrosoftAdDomain(ctx context.Context, req *managedidentitiespb.CreateMicrosoftAdDomainRequest, opts ...gax.CallOption) (*CreateMicrosoftAdDomainOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) @@ -667,161 +809,896 @@ func (c *gRPCClient) ValidateTrust(ctx context.Context, req *managedidentitiespb }, nil } -// AttachTrustOperation manages a long-running operation from AttachTrust. -type AttachTrustOperation struct { - lro *longrunning.Operation -} - -// AttachTrustOperation returns a new AttachTrustOperation from a given name. -// The name must be that of a previously created AttachTrustOperation, possibly from a different process. -func (c *gRPCClient) AttachTrustOperation(name string) *AttachTrustOperation { - return &AttachTrustOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} - -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *AttachTrustOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*managedidentitiespb.Domain, error) { - var resp managedidentitiespb.Domain - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { +// CreateMicrosoftAdDomain creates a Microsoft AD domain. +func (c *restClient) CreateMicrosoftAdDomain(ctx context.Context, req *managedidentitiespb.CreateMicrosoftAdDomainRequest, opts ...gax.CallOption) (*CreateMicrosoftAdDomainOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetDomain() + jsonReq, err := m.Marshal(body) + if err != nil { return nil, err } - return &resp, nil -} -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *AttachTrustOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*managedidentitiespb.Domain, error) { - var resp managedidentitiespb.Domain - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - if !op.Done() { - return nil, nil - } - return &resp, nil -} + baseUrl.Path += fmt.Sprintf("/v1/%v/domains", req.GetParent()) -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *AttachTrustOperation) Metadata() (*managedidentitiespb.OpMetadata, error) { - var meta managedidentitiespb.OpMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { - return nil, err - } - return &meta, nil -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("domainName", fmt.Sprintf("%v", req.GetDomainName())) -// Done reports whether the long-running operation has completed. -func (op *AttachTrustOperation) Done() bool { - return op.lro.Done() -} + baseUrl.RawQuery = params.Encode() -// 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 *AttachTrustOperation) Name() string { - return op.lro.Name() -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) -// CreateMicrosoftAdDomainOperation manages a long-running operation from CreateMicrosoftAdDomain. -type CreateMicrosoftAdDomainOperation struct { - lro *longrunning.Operation -} + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers -// CreateMicrosoftAdDomainOperation returns a new CreateMicrosoftAdDomainOperation from a given name. -// The name must be that of a previously created CreateMicrosoftAdDomainOperation, possibly from a different process. -func (c *gRPCClient) CreateMicrosoftAdDomainOperation(name string) *CreateMicrosoftAdDomainOperation { - return &CreateMicrosoftAdDomainOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *CreateMicrosoftAdDomainOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*managedidentitiespb.Domain, error) { - var resp managedidentitiespb.Domain - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { - return nil, err + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e } - return &resp, nil + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateMicrosoftAdDomainOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil } -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *CreateMicrosoftAdDomainOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*managedidentitiespb.Domain, error) { - var resp managedidentitiespb.Domain - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { +// ResetAdminPassword resets a domain’s administrator password. +func (c *restClient) ResetAdminPassword(ctx context.Context, req *managedidentitiespb.ResetAdminPasswordRequest, opts ...gax.CallOption) (*managedidentitiespb.ResetAdminPasswordResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { return nil, err } - if !op.Done() { - return nil, nil - } - return &resp, nil -} -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *CreateMicrosoftAdDomainOperation) Metadata() (*managedidentitiespb.OpMetadata, error) { - var meta managedidentitiespb.OpMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - return &meta, nil -} - -// Done reports whether the long-running operation has completed. -func (op *CreateMicrosoftAdDomainOperation) Done() bool { - return op.lro.Done() -} + baseUrl.Path += fmt.Sprintf("/v1/%v:resetAdminPassword", req.GetName()) -// 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 *CreateMicrosoftAdDomainOperation) Name() string { - return op.lro.Name() -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") -// DeleteDomainOperation manages a long-running operation from DeleteDomain. -type DeleteDomainOperation struct { - lro *longrunning.Operation -} + baseUrl.RawQuery = params.Encode() -// DeleteDomainOperation returns a new DeleteDomainOperation from a given name. -// The name must be that of a previously created DeleteDomainOperation, possibly from a different process. -func (c *gRPCClient) DeleteDomainOperation(name string) *DeleteDomainOperation { - return &DeleteDomainOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).ResetAdminPassword[0:len((*c.CallOptions).ResetAdminPassword):len((*c.CallOptions).ResetAdminPassword)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &managedidentitiespb.ResetAdminPasswordResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListDomains lists domains in a project. +func (c *restClient) ListDomains(ctx context.Context, req *managedidentitiespb.ListDomainsRequest, opts ...gax.CallOption) *DomainIterator { + it := &DomainIterator{} + req = proto.Clone(req).(*managedidentitiespb.ListDomainsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*managedidentitiespb.Domain, string, error) { + resp := &managedidentitiespb.ListDomainsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/domains", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetDomains(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetDomain gets information about a domain. +func (c *restClient) GetDomain(ctx context.Context, req *managedidentitiespb.GetDomainRequest, opts ...gax.CallOption) (*managedidentitiespb.Domain, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetDomain[0:len((*c.CallOptions).GetDomain):len((*c.CallOptions).GetDomain)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &managedidentitiespb.Domain{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateDomain updates the metadata and configuration of a domain. +func (c *restClient) UpdateDomain(ctx context.Context, req *managedidentitiespb.UpdateDomainRequest, opts ...gax.CallOption) (*UpdateDomainOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetDomain() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetDomain().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "domain.name", url.QueryEscape(req.GetDomain().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateDomainOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteDomain deletes a domain. +func (c *restClient) DeleteDomain(ctx context.Context, req *managedidentitiespb.DeleteDomainRequest, opts ...gax.CallOption) (*DeleteDomainOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteDomainOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// AttachTrust adds an AD trust to a domain. +func (c *restClient) AttachTrust(ctx context.Context, req *managedidentitiespb.AttachTrustRequest, opts ...gax.CallOption) (*AttachTrustOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:attachTrust", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &AttachTrustOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ReconfigureTrust updates the DNS conditional forwarder. +func (c *restClient) ReconfigureTrust(ctx context.Context, req *managedidentitiespb.ReconfigureTrustRequest, opts ...gax.CallOption) (*ReconfigureTrustOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:reconfigureTrust", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &ReconfigureTrustOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DetachTrust removes an AD trust. +func (c *restClient) DetachTrust(ctx context.Context, req *managedidentitiespb.DetachTrustRequest, opts ...gax.CallOption) (*DetachTrustOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:detachTrust", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DetachTrustOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ValidateTrust validates a trust state, that the target domain is reachable, and that the +// target domain is able to accept incoming trust requests. +func (c *restClient) ValidateTrust(ctx context.Context, req *managedidentitiespb.ValidateTrustRequest, opts ...gax.CallOption) (*ValidateTrustOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:validateTrust", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &ValidateTrustOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// AttachTrustOperation manages a long-running operation from AttachTrust. +type AttachTrustOperation struct { + lro *longrunning.Operation + pollPath string +} + +// AttachTrustOperation returns a new AttachTrustOperation from a given name. +// The name must be that of a previously created AttachTrustOperation, possibly from a different process. +func (c *gRPCClient) AttachTrustOperation(name string) *AttachTrustOperation { + return &AttachTrustOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// AttachTrustOperation returns a new AttachTrustOperation from a given name. +// The name must be that of a previously created AttachTrustOperation, possibly from a different process. +func (c *restClient) AttachTrustOperation(name string) *AttachTrustOperation { + override := fmt.Sprintf("/v1/%s", name) + return &AttachTrustOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *AttachTrustOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*managedidentitiespb.Domain, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp managedidentitiespb.Domain + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *AttachTrustOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*managedidentitiespb.Domain, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp managedidentitiespb.Domain + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *AttachTrustOperation) Metadata() (*managedidentitiespb.OpMetadata, error) { + var meta managedidentitiespb.OpMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *AttachTrustOperation) Done() bool { + return op.lro.Done() +} + +// 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 *AttachTrustOperation) Name() string { + return op.lro.Name() +} + +// CreateMicrosoftAdDomainOperation manages a long-running operation from CreateMicrosoftAdDomain. +type CreateMicrosoftAdDomainOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateMicrosoftAdDomainOperation returns a new CreateMicrosoftAdDomainOperation from a given name. +// The name must be that of a previously created CreateMicrosoftAdDomainOperation, possibly from a different process. +func (c *gRPCClient) CreateMicrosoftAdDomainOperation(name string) *CreateMicrosoftAdDomainOperation { + return &CreateMicrosoftAdDomainOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateMicrosoftAdDomainOperation returns a new CreateMicrosoftAdDomainOperation from a given name. +// The name must be that of a previously created CreateMicrosoftAdDomainOperation, possibly from a different process. +func (c *restClient) CreateMicrosoftAdDomainOperation(name string) *CreateMicrosoftAdDomainOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateMicrosoftAdDomainOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CreateMicrosoftAdDomainOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*managedidentitiespb.Domain, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp managedidentitiespb.Domain + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *CreateMicrosoftAdDomainOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*managedidentitiespb.Domain, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp managedidentitiespb.Domain + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *CreateMicrosoftAdDomainOperation) Metadata() (*managedidentitiespb.OpMetadata, error) { + var meta managedidentitiespb.OpMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *CreateMicrosoftAdDomainOperation) Done() bool { + return op.lro.Done() +} + +// 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 *CreateMicrosoftAdDomainOperation) Name() string { + return op.lro.Name() +} + +// DeleteDomainOperation manages a long-running operation from DeleteDomain. +type DeleteDomainOperation struct { + lro *longrunning.Operation + pollPath string +} + +// DeleteDomainOperation returns a new DeleteDomainOperation from a given name. +// The name must be that of a previously created DeleteDomainOperation, possibly from a different process. +func (c *gRPCClient) DeleteDomainOperation(name string) *DeleteDomainOperation { + return &DeleteDomainOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// DeleteDomainOperation returns a new DeleteDomainOperation from a given name. +// The name must be that of a previously created DeleteDomainOperation, possibly from a different process. +func (c *restClient) DeleteDomainOperation(name string) *DeleteDomainOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteDomainOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteDomainOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -835,6 +1712,7 @@ func (op *DeleteDomainOperation) Wait(ctx context.Context, opts ...gax.CallOptio // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteDomainOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -865,7 +1743,8 @@ func (op *DeleteDomainOperation) Name() string { // DetachTrustOperation manages a long-running operation from DetachTrust. type DetachTrustOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DetachTrustOperation returns a new DetachTrustOperation from a given name. @@ -876,10 +1755,21 @@ func (c *gRPCClient) DetachTrustOperation(name string) *DetachTrustOperation { } } +// DetachTrustOperation returns a new DetachTrustOperation from a given name. +// The name must be that of a previously created DetachTrustOperation, possibly from a different process. +func (c *restClient) DetachTrustOperation(name string) *DetachTrustOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DetachTrustOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DetachTrustOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*managedidentitiespb.Domain, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp managedidentitiespb.Domain if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -897,6 +1787,7 @@ func (op *DetachTrustOperation) Wait(ctx context.Context, opts ...gax.CallOption // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DetachTrustOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*managedidentitiespb.Domain, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp managedidentitiespb.Domain if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -934,7 +1825,8 @@ func (op *DetachTrustOperation) Name() string { // ReconfigureTrustOperation manages a long-running operation from ReconfigureTrust. type ReconfigureTrustOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // ReconfigureTrustOperation returns a new ReconfigureTrustOperation from a given name. @@ -945,10 +1837,21 @@ func (c *gRPCClient) ReconfigureTrustOperation(name string) *ReconfigureTrustOpe } } +// ReconfigureTrustOperation returns a new ReconfigureTrustOperation from a given name. +// The name must be that of a previously created ReconfigureTrustOperation, possibly from a different process. +func (c *restClient) ReconfigureTrustOperation(name string) *ReconfigureTrustOperation { + override := fmt.Sprintf("/v1/%s", name) + return &ReconfigureTrustOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *ReconfigureTrustOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*managedidentitiespb.Domain, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp managedidentitiespb.Domain if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -966,6 +1869,7 @@ func (op *ReconfigureTrustOperation) Wait(ctx context.Context, opts ...gax.CallO // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *ReconfigureTrustOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*managedidentitiespb.Domain, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp managedidentitiespb.Domain if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1003,7 +1907,8 @@ func (op *ReconfigureTrustOperation) Name() string { // UpdateDomainOperation manages a long-running operation from UpdateDomain. type UpdateDomainOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateDomainOperation returns a new UpdateDomainOperation from a given name. @@ -1014,10 +1919,21 @@ func (c *gRPCClient) UpdateDomainOperation(name string) *UpdateDomainOperation { } } +// UpdateDomainOperation returns a new UpdateDomainOperation from a given name. +// The name must be that of a previously created UpdateDomainOperation, possibly from a different process. +func (c *restClient) UpdateDomainOperation(name string) *UpdateDomainOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateDomainOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateDomainOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*managedidentitiespb.Domain, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp managedidentitiespb.Domain if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1035,6 +1951,7 @@ func (op *UpdateDomainOperation) Wait(ctx context.Context, opts ...gax.CallOptio // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateDomainOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*managedidentitiespb.Domain, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp managedidentitiespb.Domain if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1072,7 +1989,8 @@ func (op *UpdateDomainOperation) Name() string { // ValidateTrustOperation manages a long-running operation from ValidateTrust. type ValidateTrustOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // ValidateTrustOperation returns a new ValidateTrustOperation from a given name. @@ -1083,10 +2001,21 @@ func (c *gRPCClient) ValidateTrustOperation(name string) *ValidateTrustOperation } } +// ValidateTrustOperation returns a new ValidateTrustOperation from a given name. +// The name must be that of a previously created ValidateTrustOperation, possibly from a different process. +func (c *restClient) ValidateTrustOperation(name string) *ValidateTrustOperation { + override := fmt.Sprintf("/v1/%s", name) + return &ValidateTrustOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *ValidateTrustOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*managedidentitiespb.Domain, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp managedidentitiespb.Domain if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1104,6 +2033,7 @@ func (op *ValidateTrustOperation) Wait(ctx context.Context, opts ...gax.CallOpti // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *ValidateTrustOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*managedidentitiespb.Domain, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp managedidentitiespb.Domain if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/managedidentities/apiv1/managed_identities_client_example_test.go b/managedidentities/apiv1/managed_identities_client_example_test.go index 571af48cf90a..8435a78bb43f 100644 --- a/managedidentities/apiv1/managed_identities_client_example_test.go +++ b/managedidentities/apiv1/managed_identities_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := managedidentities.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_CreateMicrosoftAdDomain() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/managedidentities/apiv1/managedidentitiespb/managed_identities_service.pb.go b/managedidentities/apiv1/managedidentitiespb/managed_identities_service.pb.go index 7c0faca41ca3..2770b37d6825 100644 --- a/managedidentities/apiv1/managedidentitiespb/managed_identities_service.pb.go +++ b/managedidentities/apiv1/managedidentitiespb/managed_identities_service.pb.go @@ -15,8 +15,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/managedidentities/v1/managed_identities_service.proto package managedidentitiespb @@ -154,15 +154,15 @@ type CreateMicrosoftAdDomainRequest struct { // Required. The fully qualified domain name. // e.g. mydomain.myorganization.com, with the following restrictions: // - // - Must contain only lowercase letters, numbers, periods and hyphens. - // - Must start with a letter. - // - Must contain between 2-64 characters. - // - Must end with a number or a letter. - // - Must not start with period. - // - First segement length (mydomain form example above) shouldn't exceed - // 15 chars. - // - The last segment cannot be fully numeric. - // - Must be unique within the customer project. + // * Must contain only lowercase letters, numbers, periods and hyphens. + // * Must start with a letter. + // * Must contain between 2-64 characters. + // * Must end with a number or a letter. + // * Must not start with period. + // * First segement length (mydomain form example above) shouldn't exceed + // 15 chars. + // * The last segment cannot be fully numeric. + // * Must be unique within the customer project. DomainName string `protobuf:"bytes,2,opt,name=domain_name,json=domainName,proto3" json:"domain_name,omitempty"` // Required. A Managed Identity domain resource. Domain *Domain `protobuf:"bytes,3,opt,name=domain,proto3" json:"domain,omitempty"` @@ -548,9 +548,9 @@ type UpdateDomainRequest struct { // Required. Mask of fields to update. At least one path must be supplied in this // field. The elements of the repeated paths field may only include // fields from [Domain][google.cloud.managedidentities.v1.Domain]: - // - `labels` - // - `locations` - // - `authorized_networks` + // * `labels` + // * `locations` + // * `authorized_networks` UpdateMask *fieldmaskpb.FieldMask `protobuf:"bytes,1,opt,name=update_mask,json=updateMask,proto3" json:"update_mask,omitempty"` // Required. Domain message with updated fields. Only supported fields specified in // update_mask are updated. diff --git a/managedidentities/apiv1/managedidentitiespb/resource.pb.go b/managedidentities/apiv1/managedidentitiespb/resource.pb.go index 83a0fe609844..b03ef4e6d064 100644 --- a/managedidentities/apiv1/managedidentitiespb/resource.pb.go +++ b/managedidentities/apiv1/managedidentitiespb/resource.pb.go @@ -15,8 +15,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/managedidentities/v1/resource.proto package managedidentitiespb diff --git a/maps/addressvalidation/apiv1/address_validation_client.go b/maps/addressvalidation/apiv1/address_validation_client.go index 94a7a888ef09..87129e37cbe9 100644 --- a/maps/addressvalidation/apiv1/address_validation_client.go +++ b/maps/addressvalidation/apiv1/address_validation_client.go @@ -17,18 +17,26 @@ package addressvalidation import ( + "bytes" "context" + "fmt" + "io/ioutil" "math" + "net/http" + "net/url" "time" addressvalidationpb "cloud.google.com/go/maps/addressvalidation/apiv1/addressvalidationpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" ) var newClientHook clientHook @@ -78,6 +86,31 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + ValidateAddress: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ProvideValidationFeedback: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + } +} + // internalClient is an interface that defines the methods available from Address Validation API. type internalClient interface { Close() error @@ -217,6 +250,74 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new address validation rest client. +// +// The service for validating addresses. +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://addressvalidation.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://addressvalidation.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://addressvalidation.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) ValidateAddress(ctx context.Context, req *addressvalidationpb.ValidateAddressRequest, opts ...gax.CallOption) (*addressvalidationpb.ValidateAddressResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) @@ -256,3 +357,131 @@ func (c *gRPCClient) ProvideValidationFeedback(ctx context.Context, req *address } return resp, nil } + +// ValidateAddress validates an address. +func (c *restClient) ValidateAddress(ctx context.Context, req *addressvalidationpb.ValidateAddressRequest, opts ...gax.CallOption) (*addressvalidationpb.ValidateAddressResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1:validateAddress") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).ValidateAddress[0:len((*c.CallOptions).ValidateAddress):len((*c.CallOptions).ValidateAddress)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &addressvalidationpb.ValidateAddressResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ProvideValidationFeedback feedback about the outcome of the sequence of validation attempts. This +// should be the last call made after a sequence of validation calls for the +// same address, and should be called once the transaction is concluded. This +// should only be sent once for the sequence of ValidateAddress requests +// needed to validate an address fully. +func (c *restClient) ProvideValidationFeedback(ctx context.Context, req *addressvalidationpb.ProvideValidationFeedbackRequest, opts ...gax.CallOption) (*addressvalidationpb.ProvideValidationFeedbackResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1:provideValidationFeedback") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).ProvideValidationFeedback[0:len((*c.CallOptions).ProvideValidationFeedback):len((*c.CallOptions).ProvideValidationFeedback)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &addressvalidationpb.ProvideValidationFeedbackResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} diff --git a/maps/addressvalidation/apiv1/address_validation_client_example_test.go b/maps/addressvalidation/apiv1/address_validation_client_example_test.go index 7906d34ff595..ea5bb19c3c9f 100644 --- a/maps/addressvalidation/apiv1/address_validation_client_example_test.go +++ b/maps/addressvalidation/apiv1/address_validation_client_example_test.go @@ -40,6 +40,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := addressvalidation.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_ValidateAddress() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/maps/addressvalidation/apiv1/addressvalidationpb/address.pb.go b/maps/addressvalidation/apiv1/addressvalidationpb/address.pb.go index f556e21fff93..d012c7a594f4 100644 --- a/maps/addressvalidation/apiv1/addressvalidationpb/address.pb.go +++ b/maps/addressvalidation/apiv1/addressvalidationpb/address.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/maps/addressvalidation/v1/address.proto package addressvalidationpb diff --git a/maps/addressvalidation/apiv1/addressvalidationpb/address_validation_service.pb.go b/maps/addressvalidation/apiv1/addressvalidationpb/address_validation_service.pb.go index 18aa9769626a..56788b4ba150 100644 --- a/maps/addressvalidation/apiv1/addressvalidationpb/address_validation_service.pb.go +++ b/maps/addressvalidation/apiv1/addressvalidationpb/address_validation_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/maps/addressvalidation/v1/address_validation_service.proto package addressvalidationpb diff --git a/maps/addressvalidation/apiv1/addressvalidationpb/geocode.pb.go b/maps/addressvalidation/apiv1/addressvalidationpb/geocode.pb.go index 55c0b416f0d7..9170c1ffc0ad 100644 --- a/maps/addressvalidation/apiv1/addressvalidationpb/geocode.pb.go +++ b/maps/addressvalidation/apiv1/addressvalidationpb/geocode.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/maps/addressvalidation/v1/geocode.proto package addressvalidationpb diff --git a/maps/addressvalidation/apiv1/addressvalidationpb/metadata.pb.go b/maps/addressvalidation/apiv1/addressvalidationpb/metadata.pb.go index a41d026235d7..8682bfa9c07a 100644 --- a/maps/addressvalidation/apiv1/addressvalidationpb/metadata.pb.go +++ b/maps/addressvalidation/apiv1/addressvalidationpb/metadata.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/maps/addressvalidation/v1/metadata.proto package addressvalidationpb diff --git a/maps/addressvalidation/apiv1/addressvalidationpb/usps_data.pb.go b/maps/addressvalidation/apiv1/addressvalidationpb/usps_data.pb.go index 7454ca089eb3..25d087ba0d2c 100644 --- a/maps/addressvalidation/apiv1/addressvalidationpb/usps_data.pb.go +++ b/maps/addressvalidation/apiv1/addressvalidationpb/usps_data.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/maps/addressvalidation/v1/usps_data.proto package addressvalidationpb diff --git a/maps/addressvalidation/apiv1/doc.go b/maps/addressvalidation/apiv1/doc.go index d56158dab2ec..29247152f465 100644 --- a/maps/addressvalidation/apiv1/doc.go +++ b/maps/addressvalidation/apiv1/doc.go @@ -85,6 +85,8 @@ package addressvalidation // import "cloud.google.com/go/maps/addressvalidation/ import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -173,3 +175,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/maps/addressvalidation/apiv1/gapic_metadata.json b/maps/addressvalidation/apiv1/gapic_metadata.json index cfa315b7d69e..f08fdcf8ada4 100644 --- a/maps/addressvalidation/apiv1/gapic_metadata.json +++ b/maps/addressvalidation/apiv1/gapic_metadata.json @@ -21,6 +21,21 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "ProvideValidationFeedback": { + "methods": [ + "ProvideValidationFeedback" + ] + }, + "ValidateAddress": { + "methods": [ + "ValidateAddress" + ] + } + } } } } diff --git a/maps/routing/apiv2/doc.go b/maps/routing/apiv2/doc.go index a620f1fd42d9..f13364b4bba9 100644 --- a/maps/routing/apiv2/doc.go +++ b/maps/routing/apiv2/doc.go @@ -82,6 +82,8 @@ package routing // import "cloud.google.com/go/maps/routing/apiv2" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -170,3 +172,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/maps/routing/apiv2/gapic_metadata.json b/maps/routing/apiv2/gapic_metadata.json index d35c03d0ed37..1297441a65ce 100644 --- a/maps/routing/apiv2/gapic_metadata.json +++ b/maps/routing/apiv2/gapic_metadata.json @@ -21,6 +21,21 @@ ] } } + }, + "rest": { + "libraryClient": "RoutesClient", + "rpcs": { + "ComputeRouteMatrix": { + "methods": [ + "ComputeRouteMatrix" + ] + }, + "ComputeRoutes": { + "methods": [ + "ComputeRoutes" + ] + } + } } } } diff --git a/maps/routing/apiv2/routes_client.go b/maps/routing/apiv2/routes_client.go index 59bb1b5218c7..5216df8bc543 100644 --- a/maps/routing/apiv2/routes_client.go +++ b/maps/routing/apiv2/routes_client.go @@ -17,16 +17,24 @@ package routing import ( + "bytes" "context" + "fmt" + "io/ioutil" "math" + "net/http" + "net/url" routingpb "cloud.google.com/go/maps/routing/apiv2/routingpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" ) var newRoutesClientHook clientHook @@ -56,6 +64,13 @@ func defaultRoutesCallOptions() *RoutesCallOptions { } } +func defaultRoutesRESTCallOptions() *RoutesCallOptions { + return &RoutesCallOptions{ + ComputeRoutes: []gax.CallOption{}, + ComputeRouteMatrix: []gax.CallOption{}, + } +} + // internalRoutesClient is an interface that defines the methods available from Routes API. type internalRoutesClient interface { Close() error @@ -263,6 +278,74 @@ func (c *routesGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type routesRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing RoutesClient + CallOptions **RoutesCallOptions +} + +// NewRoutesRESTClient creates a new routes rest client. +// +// The Routes API. +func NewRoutesRESTClient(ctx context.Context, opts ...option.ClientOption) (*RoutesClient, error) { + clientOpts := append(defaultRoutesRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRoutesRESTCallOptions() + c := &routesRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &RoutesClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRoutesRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://routes.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://routes.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://routes.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *routesRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *routesRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *routesRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *routesGRPCClient) ComputeRoutes(ctx context.Context, req *routingpb.ComputeRoutesRequest, opts ...gax.CallOption) (*routingpb.ComputeRoutesResponse, error) { ctx = insertMetadata(ctx, c.xGoogMetadata) opts = append((*c.CallOptions).ComputeRoutes[0:len((*c.CallOptions).ComputeRoutes):len((*c.CallOptions).ComputeRoutes)], opts...) @@ -291,3 +374,239 @@ func (c *routesGRPCClient) ComputeRouteMatrix(ctx context.Context, req *routingp } return resp, nil } + +// ComputeRoutes returns the primary route along with optional alternate routes, given a set +// of terminal and intermediate waypoints. +// +// NOTE: This method requires that you specify a response field mask in +// the input. You can provide the response field mask by using URL parameter +// $fields or fields, or by using an HTTP/gRPC header X-Goog-FieldMask +// (see the available URL parameters and +// headers (at https://cloud.google.com/apis/docs/system-parameters). The value +// is a comma separated list of field paths. See detailed documentation about +// how to construct the field +// paths (at https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/field_mask.proto). +// +// For example, in this method: +// +// Field mask of all available fields (for manual inspection): +// X-Goog-FieldMask: * +// +// Field mask of Route-level duration, distance, and polyline (an example +// production setup): +// X-Goog-FieldMask: routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline +// +// Google discourage the use of the wildcard (*) response field mask, or +// specifying the field mask at the top level (routes), because: +// +// Selecting only the fields that you need helps our server save computation +// cycles, allowing us to return the result to you with a lower latency. +// +// Selecting only the fields that you need +// in your production job ensures stable latency performance. We might add +// more response fields in the future, and those new fields might require +// extra computation time. If you select all fields, or if you select all +// fields at the top level, then you might experience performance degradation +// because any new field we add will be automatically included in the +// response. +// +// Selecting only the fields that you need results in a smaller response +// size, and thus higher network throughput. +func (c *routesRESTClient) ComputeRoutes(ctx context.Context, req *routingpb.ComputeRoutesRequest, opts ...gax.CallOption) (*routingpb.ComputeRoutesResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/directions/v2:computeRoutes") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).ComputeRoutes[0:len((*c.CallOptions).ComputeRoutes):len((*c.CallOptions).ComputeRoutes)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &routingpb.ComputeRoutesResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ComputeRouteMatrix takes in a list of origins and destinations and returns a stream containing +// route information for each combination of origin and destination. +// +// NOTE: This method requires that you specify a response field mask in +// the input. You can provide the response field mask by using the URL +// parameter $fields or fields, or by using the HTTP/gRPC header +// X-Goog-FieldMask (see the available URL parameters and +// headers (at https://cloud.google.com/apis/docs/system-parameters). The value +// is a comma separated list of field paths. See this detailed documentation +// about how to construct the field +// paths (at https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/field_mask.proto). +// +// For example, in this method: +// +// Field mask of all available fields (for manual inspection): +// X-Goog-FieldMask: * +// +// Field mask of route durations, distances, element status, condition, and +// element indices (an example production setup): +// X-Goog-FieldMask: originIndex,destinationIndex,status,condition,distanceMeters,duration +// +// It is critical that you include status in your field mask as otherwise +// all messages will appear to be OK. Google discourages the use of the +// wildcard (*) response field mask, because: +// +// Selecting only the fields that you need helps our server save computation +// cycles, allowing us to return the result to you with a lower latency. +// +// Selecting only the fields that you need in your production job ensures +// stable latency performance. We might add more response fields in the +// future, and those new fields might require extra computation time. If you +// select all fields, or if you select all fields at the top level, then you +// might experience performance degradation because any new field we add will +// be automatically included in the response. +// +// Selecting only the fields that you need results in a smaller response +// size, and thus higher network throughput. +func (c *routesRESTClient) ComputeRouteMatrix(ctx context.Context, req *routingpb.ComputeRouteMatrixRequest, opts ...gax.CallOption) (routingpb.Routes_ComputeRouteMatrixClient, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/distanceMatrix/v2:computeRouteMatrix") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + var streamClient *computeRouteMatrixRESTClient + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + streamClient = &computeRouteMatrixRESTClient{ + ctx: ctx, + md: metadata.MD(httpRsp.Header), + stream: gax.NewProtoJSONStreamReader(httpRsp.Body, (&routingpb.RouteMatrixElement{}).ProtoReflect().Type()), + } + return nil + }, opts...) + + return streamClient, e +} + +// computeRouteMatrixRESTClient is the stream client used to consume the server stream created by +// the REST implementation of ComputeRouteMatrix. +type computeRouteMatrixRESTClient struct { + ctx context.Context + md metadata.MD + stream *gax.ProtoJSONStream +} + +func (c *computeRouteMatrixRESTClient) Recv() (*routingpb.RouteMatrixElement, error) { + if err := c.ctx.Err(); err != nil { + defer c.stream.Close() + return nil, err + } + msg, err := c.stream.Recv() + if err != nil { + defer c.stream.Close() + return nil, err + } + res := msg.(*routingpb.RouteMatrixElement) + return res, nil +} + +func (c *computeRouteMatrixRESTClient) Header() (metadata.MD, error) { + return c.md, nil +} + +func (c *computeRouteMatrixRESTClient) Trailer() metadata.MD { + return c.md +} + +func (c *computeRouteMatrixRESTClient) CloseSend() error { + // This is a no-op to fulfill the interface. + return fmt.Errorf("this method is not implemented for a server-stream") +} + +func (c *computeRouteMatrixRESTClient) Context() context.Context { + return c.ctx +} + +func (c *computeRouteMatrixRESTClient) SendMsg(m interface{}) error { + // This is a no-op to fulfill the interface. + return fmt.Errorf("this method is not implemented for a server-stream") +} + +func (c *computeRouteMatrixRESTClient) RecvMsg(m interface{}) error { + // This is a no-op to fulfill the interface. + return fmt.Errorf("this method is not implemented, use Recv") +} diff --git a/maps/routing/apiv2/routes_client_example_test.go b/maps/routing/apiv2/routes_client_example_test.go index b0424124fa7a..370bb278bf41 100644 --- a/maps/routing/apiv2/routes_client_example_test.go +++ b/maps/routing/apiv2/routes_client_example_test.go @@ -40,6 +40,23 @@ func ExampleNewRoutesClient() { _ = c } +func ExampleNewRoutesRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := routing.NewRoutesRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleRoutesClient_ComputeRoutes() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/maps/routing/apiv2/routingpb/fallback_info.pb.go b/maps/routing/apiv2/routingpb/fallback_info.pb.go index a4d601ca5298..9e6c1a92f0cc 100644 --- a/maps/routing/apiv2/routingpb/fallback_info.pb.go +++ b/maps/routing/apiv2/routingpb/fallback_info.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/maps/routing/v2/fallback_info.proto package routingpb diff --git a/maps/routing/apiv2/routingpb/location.pb.go b/maps/routing/apiv2/routingpb/location.pb.go index c5acfacbe53e..bc43597be652 100644 --- a/maps/routing/apiv2/routingpb/location.pb.go +++ b/maps/routing/apiv2/routingpb/location.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/maps/routing/v2/location.proto package routingpb diff --git a/maps/routing/apiv2/routingpb/maneuver.pb.go b/maps/routing/apiv2/routingpb/maneuver.pb.go index a2f23063da19..0eb569903b18 100644 --- a/maps/routing/apiv2/routingpb/maneuver.pb.go +++ b/maps/routing/apiv2/routingpb/maneuver.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/maps/routing/v2/maneuver.proto package routingpb diff --git a/maps/routing/apiv2/routingpb/navigation_instruction.pb.go b/maps/routing/apiv2/routingpb/navigation_instruction.pb.go index c1d8c4ac51a4..72a66bfb751d 100644 --- a/maps/routing/apiv2/routingpb/navigation_instruction.pb.go +++ b/maps/routing/apiv2/routingpb/navigation_instruction.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/maps/routing/v2/navigation_instruction.proto package routingpb diff --git a/maps/routing/apiv2/routingpb/polyline.pb.go b/maps/routing/apiv2/routingpb/polyline.pb.go index b843e656ca40..d79ccce20b9e 100644 --- a/maps/routing/apiv2/routingpb/polyline.pb.go +++ b/maps/routing/apiv2/routingpb/polyline.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/maps/routing/v2/polyline.proto package routingpb @@ -158,7 +158,6 @@ type Polyline struct { // Encapsulates the type of polyline. Defaults to encoded_polyline. // // Types that are assignable to PolylineType: - // // *Polyline_EncodedPolyline // *Polyline_GeoJsonLinestring PolylineType isPolyline_PolylineType `protobuf_oneof:"polyline_type"` diff --git a/maps/routing/apiv2/routingpb/route.pb.go b/maps/routing/apiv2/routingpb/route.pb.go index 67e395d2ce50..05e7ba194cb1 100644 --- a/maps/routing/apiv2/routingpb/route.pb.go +++ b/maps/routing/apiv2/routingpb/route.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/maps/routing/v2/route.proto package routingpb @@ -215,8 +215,8 @@ type RouteTravelAdvisory struct { // // Example: // - // polyline: A ---- B ---- C ---- D ---- E ---- F ---- G - // speed_reading_intervals: [A,C), [C,D), [D,G). + // polyline: A ---- B ---- C ---- D ---- E ---- F ---- G + // speed_reading_intervals: [A,C), [C,D), [D,G). SpeedReadingIntervals []*SpeedReadingInterval `protobuf:"bytes,3,rep,name=speed_reading_intervals,json=speedReadingIntervals,proto3" json:"speed_reading_intervals,omitempty"` // The fuel consumption prediction in microliters. FuelConsumptionMicroliters int64 `protobuf:"varint,5,opt,name=fuel_consumption_microliters,json=fuelConsumptionMicroliters,proto3" json:"fuel_consumption_microliters,omitempty"` @@ -296,8 +296,8 @@ type RouteLegTravelAdvisory struct { // // Example: // - // polyline: A ---- B ---- C ---- D ---- E ---- F ---- G - // speed_reading_intervals: [A,C), [C,D), [D,G). + // polyline: A ---- B ---- C ---- D ---- E ---- F ---- G + // speed_reading_intervals: [A,C), [C,D), [D,G). SpeedReadingIntervals []*SpeedReadingInterval `protobuf:"bytes,2,rep,name=speed_reading_intervals,json=speedReadingIntervals,proto3" json:"speed_reading_intervals,omitempty"` } @@ -362,8 +362,8 @@ type RouteLegStepTravelAdvisory struct { // // Example: // - // polyline: A ---- B ---- C ---- D ---- E ---- F ---- G - // speed_reading_intervals: [A,C), [C,D), [D,G). + // polyline: A ---- B ---- C ---- D ---- E ---- F ---- G + // speed_reading_intervals: [A,C), [C,D), [D,G). SpeedReadingIntervals []*SpeedReadingInterval `protobuf:"bytes,1,rep,name=speed_reading_intervals,json=speedReadingIntervals,proto3" json:"speed_reading_intervals,omitempty"` } diff --git a/maps/routing/apiv2/routingpb/route_label.pb.go b/maps/routing/apiv2/routingpb/route_label.pb.go index 4cd9bcbe8c9b..4b5ede9afca8 100644 --- a/maps/routing/apiv2/routingpb/route_label.pb.go +++ b/maps/routing/apiv2/routingpb/route_label.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/maps/routing/v2/route_label.proto package routingpb diff --git a/maps/routing/apiv2/routingpb/route_modifiers.pb.go b/maps/routing/apiv2/routingpb/route_modifiers.pb.go index 924ae42c27ce..ede20509a0d6 100644 --- a/maps/routing/apiv2/routingpb/route_modifiers.pb.go +++ b/maps/routing/apiv2/routingpb/route_modifiers.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/maps/routing/v2/route_modifiers.proto package routingpb diff --git a/maps/routing/apiv2/routingpb/route_travel_mode.pb.go b/maps/routing/apiv2/routingpb/route_travel_mode.pb.go index cab902e8ed16..56cfc31c8e3b 100644 --- a/maps/routing/apiv2/routingpb/route_travel_mode.pb.go +++ b/maps/routing/apiv2/routingpb/route_travel_mode.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/maps/routing/v2/route_travel_mode.proto package routingpb diff --git a/maps/routing/apiv2/routingpb/routes_service.pb.go b/maps/routing/apiv2/routingpb/routes_service.pb.go index e388f2a69861..a12db6b3f641 100644 --- a/maps/routing/apiv2/routingpb/routes_service.pb.go +++ b/maps/routing/apiv2/routingpb/routes_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/maps/routing/v2/routes_service.proto package routingpb @@ -166,9 +166,7 @@ type ComputeRoutesRequest struct { TravelMode RouteTravelMode `protobuf:"varint,4,opt,name=travel_mode,json=travelMode,proto3,enum=google.maps.routing.v2.RouteTravelMode" json:"travel_mode,omitempty"` // Optional. Specifies how to compute the route. The server // attempts to use the selected routing preference to compute the route. If - // - // the routing preference results in an error or an extra long latency, then - // + // the routing preference results in an error or an extra long latency, then // an error is returned. In the future, we might implement a fallback // mechanism to use a different option when the preferred option does not give // a valid result. You can specify this option only when the `travel_mode` is @@ -1196,14 +1194,12 @@ type RoutesClient interface { // // For example, in this method: // - // - Field mask of all available fields (for manual inspection): - // `X-Goog-FieldMask: *` - // - Field mask of Route-level duration, distance, and polyline (an example - // + // * Field mask of all available fields (for manual inspection): + // `X-Goog-FieldMask: *` + // * Field mask of Route-level duration, distance, and polyline (an example // production setup): - // - // `X-Goog-FieldMask: - // routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline` + // `X-Goog-FieldMask: + // routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline` // // Google discourage the use of the wildcard (`*`) response field mask, or // specifying the field mask at the top level (`routes`), because: @@ -1234,12 +1230,12 @@ type RoutesClient interface { // // For example, in this method: // - // - Field mask of all available fields (for manual inspection): - // `X-Goog-FieldMask: *` - // - Field mask of route durations, distances, element status, condition, and - // element indices (an example production setup): - // `X-Goog-FieldMask: - // originIndex,destinationIndex,status,condition,distanceMeters,duration` + // * Field mask of all available fields (for manual inspection): + // `X-Goog-FieldMask: *` + // * Field mask of route durations, distances, element status, condition, and + // element indices (an example production setup): + // `X-Goog-FieldMask: + // originIndex,destinationIndex,status,condition,distanceMeters,duration` // // It is critical that you include `status` in your field mask as otherwise // all messages will appear to be OK. Google discourages the use of the @@ -1323,14 +1319,12 @@ type RoutesServer interface { // // For example, in this method: // - // - Field mask of all available fields (for manual inspection): - // `X-Goog-FieldMask: *` - // - Field mask of Route-level duration, distance, and polyline (an example - // + // * Field mask of all available fields (for manual inspection): + // `X-Goog-FieldMask: *` + // * Field mask of Route-level duration, distance, and polyline (an example // production setup): - // - // `X-Goog-FieldMask: - // routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline` + // `X-Goog-FieldMask: + // routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline` // // Google discourage the use of the wildcard (`*`) response field mask, or // specifying the field mask at the top level (`routes`), because: @@ -1361,12 +1355,12 @@ type RoutesServer interface { // // For example, in this method: // - // - Field mask of all available fields (for manual inspection): - // `X-Goog-FieldMask: *` - // - Field mask of route durations, distances, element status, condition, and - // element indices (an example production setup): - // `X-Goog-FieldMask: - // originIndex,destinationIndex,status,condition,distanceMeters,duration` + // * Field mask of all available fields (for manual inspection): + // `X-Goog-FieldMask: *` + // * Field mask of route durations, distances, element status, condition, and + // element indices (an example production setup): + // `X-Goog-FieldMask: + // originIndex,destinationIndex,status,condition,distanceMeters,duration` // // It is critical that you include `status` in your field mask as otherwise // all messages will appear to be OK. Google discourages the use of the diff --git a/maps/routing/apiv2/routingpb/routing_preference.pb.go b/maps/routing/apiv2/routingpb/routing_preference.pb.go index 5cedee058283..6901d52e2026 100644 --- a/maps/routing/apiv2/routingpb/routing_preference.pb.go +++ b/maps/routing/apiv2/routingpb/routing_preference.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/maps/routing/v2/routing_preference.proto package routingpb diff --git a/maps/routing/apiv2/routingpb/speed_reading_interval.pb.go b/maps/routing/apiv2/routingpb/speed_reading_interval.pb.go index 5b3a68216e9b..6b099c4ff710 100644 --- a/maps/routing/apiv2/routingpb/speed_reading_interval.pb.go +++ b/maps/routing/apiv2/routingpb/speed_reading_interval.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/maps/routing/v2/speed_reading_interval.proto package routingpb diff --git a/maps/routing/apiv2/routingpb/toll_info.pb.go b/maps/routing/apiv2/routingpb/toll_info.pb.go index fc9f3a2a2330..90700f3e2919 100644 --- a/maps/routing/apiv2/routingpb/toll_info.pb.go +++ b/maps/routing/apiv2/routingpb/toll_info.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/maps/routing/v2/toll_info.proto package routingpb diff --git a/maps/routing/apiv2/routingpb/toll_passes.pb.go b/maps/routing/apiv2/routingpb/toll_passes.pb.go index 867dc85cc86f..7c680de61f38 100644 --- a/maps/routing/apiv2/routingpb/toll_passes.pb.go +++ b/maps/routing/apiv2/routingpb/toll_passes.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/maps/routing/v2/toll_passes.proto package routingpb @@ -93,8 +93,7 @@ const ( // https://www.pase.com.mx TollPass_MX_PASE TollPass = 91 // Mexico - // - // https://operadoravial.com/quick-pass/ + // https://operadoravial.com/quick-pass/ TollPass_MX_QUICKPASS TollPass = 93 // http://appsh.chihuahua.gob.mx/transparencia/?doc=/ingresos/TelepeajeFormato4.pdf TollPass_MX_SISTEMA_TELEPEAJE_CHIHUAHUA TollPass = 89 diff --git a/maps/routing/apiv2/routingpb/units.pb.go b/maps/routing/apiv2/routingpb/units.pb.go index 2aed8573af84..73431dfefc82 100644 --- a/maps/routing/apiv2/routingpb/units.pb.go +++ b/maps/routing/apiv2/routingpb/units.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/maps/routing/v2/units.proto package routingpb diff --git a/maps/routing/apiv2/routingpb/vehicle_emission_type.pb.go b/maps/routing/apiv2/routingpb/vehicle_emission_type.pb.go index 9b0426819d0f..92768a2809de 100644 --- a/maps/routing/apiv2/routingpb/vehicle_emission_type.pb.go +++ b/maps/routing/apiv2/routingpb/vehicle_emission_type.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/maps/routing/v2/vehicle_emission_type.proto package routingpb diff --git a/maps/routing/apiv2/routingpb/vehicle_info.pb.go b/maps/routing/apiv2/routingpb/vehicle_info.pb.go index 78114a1058dc..508985fe792a 100644 --- a/maps/routing/apiv2/routingpb/vehicle_info.pb.go +++ b/maps/routing/apiv2/routingpb/vehicle_info.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/maps/routing/v2/vehicle_info.proto package routingpb diff --git a/maps/routing/apiv2/routingpb/waypoint.pb.go b/maps/routing/apiv2/routingpb/waypoint.pb.go index 433f723828e6..10a7f88b3b8b 100644 --- a/maps/routing/apiv2/routingpb/waypoint.pb.go +++ b/maps/routing/apiv2/routingpb/waypoint.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/maps/routing/v2/waypoint.proto package routingpb @@ -45,7 +45,6 @@ type Waypoint struct { // Different ways to represent a location. // // Types that are assignable to LocationType: - // // *Waypoint_Location // *Waypoint_PlaceId LocationType isWaypoint_LocationType `protobuf_oneof:"location_type"` diff --git a/mediatranslation/apiv1beta1/mediatranslationpb/media_translation.pb.go b/mediatranslation/apiv1beta1/mediatranslationpb/media_translation.pb.go index 339d2222323c..b741a7fbae2f 100644 --- a/mediatranslation/apiv1beta1/mediatranslationpb/media_translation.pb.go +++ b/mediatranslation/apiv1beta1/mediatranslationpb/media_translation.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/mediatranslation/v1beta1/media_translation.proto package mediatranslationpb @@ -111,37 +111,37 @@ type TranslateSpeechConfig struct { // // - `linear16` // - // Uncompressed 16-bit signed little-endian samples (Linear PCM). + // Uncompressed 16-bit signed little-endian samples (Linear PCM). // // - `flac` // - // `flac` (Free Lossless Audio Codec) is the recommended encoding - // because it is lossless--therefore recognition is not compromised--and - // requires only about half the bandwidth of `linear16`. + // `flac` (Free Lossless Audio Codec) is the recommended encoding + // because it is lossless--therefore recognition is not compromised--and + // requires only about half the bandwidth of `linear16`. // // - `mulaw` // - // 8-bit samples that compand 14-bit audio samples using G.711 PCMU/mu-law. + // 8-bit samples that compand 14-bit audio samples using G.711 PCMU/mu-law. // // - `amr` // - // Adaptive Multi-Rate Narrowband codec. `sample_rate_hertz` must be 8000. + // Adaptive Multi-Rate Narrowband codec. `sample_rate_hertz` must be 8000. // // - `amr-wb` // - // Adaptive Multi-Rate Wideband codec. `sample_rate_hertz` must be 16000. + // Adaptive Multi-Rate Wideband codec. `sample_rate_hertz` must be 16000. // // - `ogg-opus` // - // Opus encoded audio frames in [Ogg](https://wikipedia.org/wiki/Ogg) - // container. `sample_rate_hertz` must be one of 8000, 12000, 16000, 24000, - // or 48000. + // Opus encoded audio frames in [Ogg](https://wikipedia.org/wiki/Ogg) + // container. `sample_rate_hertz` must be one of 8000, 12000, 16000, 24000, + // or 48000. // // - `mp3` // - // MP3 audio. Support all standard MP3 bitrates (which range from 32-320 - // kbps). When using this encoding, `sample_rate_hertz` has to match the - // sample rate of the file being used. + // MP3 audio. Support all standard MP3 bitrates (which range from 32-320 + // kbps). When using this encoding, `sample_rate_hertz` has to match the + // sample rate of the file being used. AudioEncoding string `protobuf:"bytes,1,opt,name=audio_encoding,json=audioEncoding,proto3" json:"audio_encoding,omitempty"` // Required. Source language code (BCP-47) of the input audio. SourceLanguageCode string `protobuf:"bytes,2,opt,name=source_language_code,json=sourceLanguageCode,proto3" json:"source_language_code,omitempty"` @@ -309,7 +309,6 @@ type StreamingTranslateSpeechRequest struct { // The streaming request, which is either a streaming config or content. // // Types that are assignable to StreamingRequest: - // // *StreamingTranslateSpeechRequest_StreamingConfig // *StreamingTranslateSpeechRequest_AudioContent StreamingRequest isStreamingTranslateSpeechRequest_StreamingRequest `protobuf_oneof:"streaming_request"` @@ -407,7 +406,6 @@ type StreamingTranslateSpeechResult struct { // Translation result. // // Types that are assignable to Result: - // // *StreamingTranslateSpeechResult_TextTranslationResult_ Result isStreamingTranslateSpeechResult_Result `protobuf_oneof:"result"` } diff --git a/mediatranslation/apiv1beta1/speech_translation_client.go b/mediatranslation/apiv1beta1/speech_translation_client.go index 3566f392fc88..b93c1f91682a 100644 --- a/mediatranslation/apiv1beta1/speech_translation_client.go +++ b/mediatranslation/apiv1beta1/speech_translation_client.go @@ -108,6 +108,8 @@ func (c *SpeechTranslationClient) Connection() *grpc.ClientConn { // StreamingTranslateSpeech performs bidirectional streaming speech translation: receive results while // sending audio. This method is only available via the gRPC API (not REST). +// +// This method is not supported for the REST transport. func (c *SpeechTranslationClient) StreamingTranslateSpeech(ctx context.Context, opts ...gax.CallOption) (mediatranslationpb.SpeechTranslationService_StreamingTranslateSpeechClient, error) { return c.internalClient.StreamingTranslateSpeech(ctx, opts...) } @@ -278,6 +280,8 @@ func (c *speechTranslationGRPCClient) StreamingTranslateSpeech(ctx context.Conte // StreamingTranslateSpeech performs bidirectional streaming speech translation: receive results while // sending audio. This method is only available via the gRPC API (not REST). +// +// This method is not supported for the REST transport. func (c *speechTranslationRESTClient) StreamingTranslateSpeech(ctx context.Context, opts ...gax.CallOption) (mediatranslationpb.SpeechTranslationService_StreamingTranslateSpeechClient, error) { return nil, fmt.Errorf("StreamingTranslateSpeech not yet supported for REST clients") } diff --git a/memcache/apiv1/cloud_memcache_client.go b/memcache/apiv1/cloud_memcache_client.go index a5a3c5adde37..b8a2561abdde 100644 --- a/memcache/apiv1/cloud_memcache_client.go +++ b/memcache/apiv1/cloud_memcache_client.go @@ -17,9 +17,12 @@ package memcache import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,14 +30,17 @@ import ( lroauto "cloud.google.com/go/longrunning/autogen" memcachepb "cloud.google.com/go/memcache/apiv1/memcachepb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -89,6 +95,25 @@ func defaultCloudMemcacheCallOptions() *CloudMemcacheCallOptions { } } +func defaultCloudMemcacheRESTCallOptions() *CloudMemcacheCallOptions { + return &CloudMemcacheCallOptions{ + ListInstances: []gax.CallOption{}, + GetInstance: []gax.CallOption{}, + CreateInstance: []gax.CallOption{}, + UpdateInstance: []gax.CallOption{}, + UpdateParameters: []gax.CallOption{}, + DeleteInstance: []gax.CallOption{}, + ApplyParameters: []gax.CallOption{}, + RescheduleMaintenance: []gax.CallOption{}, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + CancelOperation: []gax.CallOption{}, + DeleteOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalCloudMemcacheClient is an interface that defines the methods available from Cloud Memorystore for Memcached API. type internalCloudMemcacheClient interface { Close() error @@ -405,6 +430,107 @@ func (c *cloudMemcacheGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type cloudMemcacheRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing CloudMemcacheClient + CallOptions **CloudMemcacheCallOptions +} + +// NewCloudMemcacheRESTClient creates a new cloud memcache rest client. +// +// Configures and manages Cloud Memorystore for Memcached instances. +// +// The memcache.googleapis.com service implements the Google Cloud Memorystore +// for Memcached API and defines the following resource model for managing +// Memorystore Memcached (also called Memcached below) instances: +// +// The service works with a collection of cloud projects, named: /projects/* +// +// Each project has a collection of available locations, named: /locations/* +// +// Each location has a collection of Memcached instances, named: +// /instances/* +// +// As such, Memcached instances are resources of the form: +// /projects/{project_id}/locations/{location_id}/instances/{instance_id} +// +// Note that location_id must be a GCP region; for example: +// +// projects/my-memcached-project/locations/us-central1/instances/my-memcached +func NewCloudMemcacheRESTClient(ctx context.Context, opts ...option.ClientOption) (*CloudMemcacheClient, error) { + clientOpts := append(defaultCloudMemcacheRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultCloudMemcacheRESTCallOptions() + c := &cloudMemcacheRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &CloudMemcacheClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultCloudMemcacheRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://memcache.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://memcache.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://memcache.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *cloudMemcacheRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *cloudMemcacheRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *cloudMemcacheRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *cloudMemcacheGRPCClient) ListInstances(ctx context.Context, req *memcachepb.ListInstancesRequest, opts ...gax.CallOption) *InstanceIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -766,137 +892,1115 @@ func (c *cloudMemcacheGRPCClient) ListOperations(ctx context.Context, req *longr return it } -// ApplyParametersOperation manages a long-running operation from ApplyParameters. -type ApplyParametersOperation struct { - lro *longrunning.Operation -} +// ListInstances lists Instances in a given location. +func (c *cloudMemcacheRESTClient) ListInstances(ctx context.Context, req *memcachepb.ListInstancesRequest, opts ...gax.CallOption) *InstanceIterator { + it := &InstanceIterator{} + req = proto.Clone(req).(*memcachepb.ListInstancesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*memcachepb.Instance, string, error) { + resp := &memcachepb.ListInstancesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/instances", req.GetParent()) -// ApplyParametersOperation returns a new ApplyParametersOperation from a given name. -// The name must be that of a previously created ApplyParametersOperation, possibly from a different process. -func (c *cloudMemcacheGRPCClient) ApplyParametersOperation(name string) *ApplyParametersOperation { - return &ApplyParametersOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *ApplyParametersOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*memcachepb.Instance, error) { - var resp memcachepb.Instance - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { - return nil, err + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetInstances(), resp.GetNextPageToken(), nil } - return &resp, nil -} -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *ApplyParametersOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*memcachepb.Instance, error) { - var resp memcachepb.Instance - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { - return nil, err - } - if !op.Done() { - return nil, 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 } - return &resp, nil + + it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it } -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *ApplyParametersOperation) Metadata() (*memcachepb.OperationMetadata, error) { - var meta memcachepb.OperationMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { +// GetInstance gets details of a single Instance. +func (c *cloudMemcacheRESTClient) GetInstance(ctx context.Context, req *memcachepb.GetInstanceRequest, opts ...gax.CallOption) (*memcachepb.Instance, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - return &meta, nil -} + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) -// Done reports whether the long-running operation has completed. -func (op *ApplyParametersOperation) Done() bool { - return op.lro.Done() -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") -// 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 *ApplyParametersOperation) Name() string { - return op.lro.Name() -} + baseUrl.RawQuery = params.Encode() -// CreateInstanceOperation manages a long-running operation from CreateInstance. -type CreateInstanceOperation struct { - lro *longrunning.Operation -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) -// CreateInstanceOperation returns a new CreateInstanceOperation from a given name. -// The name must be that of a previously created CreateInstanceOperation, possibly from a different process. -func (c *cloudMemcacheGRPCClient) CreateInstanceOperation(name string) *CreateInstanceOperation { - return &CreateInstanceOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetInstance[0:len((*c.CallOptions).GetInstance):len((*c.CallOptions).GetInstance)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &memcachepb.Instance{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *CreateInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*memcachepb.Instance, error) { - var resp memcachepb.Instance - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { - return nil, err + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e } - return &resp, nil + return resp, nil } -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *CreateInstanceOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*memcachepb.Instance, error) { - var resp memcachepb.Instance - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { +// CreateInstance creates a new Instance in a given location. +func (c *cloudMemcacheRESTClient) CreateInstance(ctx context.Context, req *memcachepb.CreateInstanceRequest, opts ...gax.CallOption) (*CreateInstanceOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetInstance() + jsonReq, err := m.Marshal(body) + if err != nil { return nil, err } - if !op.Done() { - return nil, nil - } - return &resp, nil -} -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *CreateInstanceOperation) Metadata() (*memcachepb.OperationMetadata, error) { - var meta memcachepb.OperationMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - return &meta, nil -} + baseUrl.Path += fmt.Sprintf("/v1/%v/instances", req.GetParent()) -// Done reports whether the long-running operation has completed. -func (op *CreateInstanceOperation) Done() bool { - return op.lro.Done() -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("instanceId", fmt.Sprintf("%v", req.GetInstanceId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateInstance updates an existing Instance in a given project and location. +func (c *cloudMemcacheRESTClient) UpdateInstance(ctx context.Context, req *memcachepb.UpdateInstanceRequest, opts ...gax.CallOption) (*UpdateInstanceOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetInstance() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetInstance().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "instance.name", url.QueryEscape(req.GetInstance().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateParameters updates the defined Memcached parameters for an existing instance. +// This method only stages the parameters, it must be followed by +// ApplyParameters to apply the parameters to nodes of the Memcached +// instance. +func (c *cloudMemcacheRESTClient) UpdateParameters(ctx context.Context, req *memcachepb.UpdateParametersRequest, opts ...gax.CallOption) (*UpdateParametersOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:updateParameters", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateParametersOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteInstance deletes a single Instance. +func (c *cloudMemcacheRESTClient) DeleteInstance(ctx context.Context, req *memcachepb.DeleteInstanceRequest, opts ...gax.CallOption) (*DeleteInstanceOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ApplyParameters ApplyParameters restarts the set of specified nodes in order to update +// them to the current set of parameters for the Memcached Instance. +func (c *cloudMemcacheRESTClient) ApplyParameters(ctx context.Context, req *memcachepb.ApplyParametersRequest, opts ...gax.CallOption) (*ApplyParametersOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:applyParameters", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &ApplyParametersOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// RescheduleMaintenance reschedules upcoming maintenance event. +func (c *cloudMemcacheRESTClient) RescheduleMaintenance(ctx context.Context, req *memcachepb.RescheduleMaintenanceRequest, opts ...gax.CallOption) (*RescheduleMaintenanceOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:rescheduleMaintenance", req.GetInstance()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "instance", url.QueryEscape(req.GetInstance()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &RescheduleMaintenanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetLocation gets information about a location. +func (c *cloudMemcacheRESTClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *cloudMemcacheRESTClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *cloudMemcacheRESTClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// DeleteOperation is a utility method from google.longrunning.Operations. +func (c *cloudMemcacheRESTClient) DeleteOperation(ctx context.Context, req *longrunningpb.DeleteOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *cloudMemcacheRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *cloudMemcacheRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// ApplyParametersOperation manages a long-running operation from ApplyParameters. +type ApplyParametersOperation struct { + lro *longrunning.Operation + pollPath string +} + +// ApplyParametersOperation returns a new ApplyParametersOperation from a given name. +// The name must be that of a previously created ApplyParametersOperation, possibly from a different process. +func (c *cloudMemcacheGRPCClient) ApplyParametersOperation(name string) *ApplyParametersOperation { + return &ApplyParametersOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// ApplyParametersOperation returns a new ApplyParametersOperation from a given name. +// The name must be that of a previously created ApplyParametersOperation, possibly from a different process. +func (c *cloudMemcacheRESTClient) ApplyParametersOperation(name string) *ApplyParametersOperation { + override := fmt.Sprintf("/v1/%s", name) + return &ApplyParametersOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *ApplyParametersOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*memcachepb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp memcachepb.Instance + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *ApplyParametersOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*memcachepb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp memcachepb.Instance + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *ApplyParametersOperation) Metadata() (*memcachepb.OperationMetadata, error) { + var meta memcachepb.OperationMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *ApplyParametersOperation) Done() bool { + return op.lro.Done() +} + +// 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 *ApplyParametersOperation) Name() string { + return op.lro.Name() +} + +// CreateInstanceOperation manages a long-running operation from CreateInstance. +type CreateInstanceOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateInstanceOperation returns a new CreateInstanceOperation from a given name. +// The name must be that of a previously created CreateInstanceOperation, possibly from a different process. +func (c *cloudMemcacheGRPCClient) CreateInstanceOperation(name string) *CreateInstanceOperation { + return &CreateInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateInstanceOperation returns a new CreateInstanceOperation from a given name. +// The name must be that of a previously created CreateInstanceOperation, possibly from a different process. +func (c *cloudMemcacheRESTClient) CreateInstanceOperation(name string) *CreateInstanceOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CreateInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*memcachepb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp memcachepb.Instance + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *CreateInstanceOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*memcachepb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp memcachepb.Instance + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *CreateInstanceOperation) Metadata() (*memcachepb.OperationMetadata, error) { + var meta memcachepb.OperationMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *CreateInstanceOperation) Done() bool { + return op.lro.Done() +} // 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. @@ -906,7 +2010,8 @@ func (op *CreateInstanceOperation) Name() string { // DeleteInstanceOperation manages a long-running operation from DeleteInstance. type DeleteInstanceOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteInstanceOperation returns a new DeleteInstanceOperation from a given name. @@ -917,10 +2022,21 @@ func (c *cloudMemcacheGRPCClient) DeleteInstanceOperation(name string) *DeleteIn } } +// DeleteInstanceOperation returns a new DeleteInstanceOperation from a given name. +// The name must be that of a previously created DeleteInstanceOperation, possibly from a different process. +func (c *cloudMemcacheRESTClient) DeleteInstanceOperation(name string) *DeleteInstanceOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -934,6 +2050,7 @@ func (op *DeleteInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOpt // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteInstanceOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -964,7 +2081,8 @@ func (op *DeleteInstanceOperation) Name() string { // RescheduleMaintenanceOperation manages a long-running operation from RescheduleMaintenance. type RescheduleMaintenanceOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // RescheduleMaintenanceOperation returns a new RescheduleMaintenanceOperation from a given name. @@ -975,10 +2093,21 @@ func (c *cloudMemcacheGRPCClient) RescheduleMaintenanceOperation(name string) *R } } +// RescheduleMaintenanceOperation returns a new RescheduleMaintenanceOperation from a given name. +// The name must be that of a previously created RescheduleMaintenanceOperation, possibly from a different process. +func (c *cloudMemcacheRESTClient) RescheduleMaintenanceOperation(name string) *RescheduleMaintenanceOperation { + override := fmt.Sprintf("/v1/%s", name) + return &RescheduleMaintenanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *RescheduleMaintenanceOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*memcachepb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp memcachepb.Instance if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -996,6 +2125,7 @@ func (op *RescheduleMaintenanceOperation) Wait(ctx context.Context, opts ...gax. // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *RescheduleMaintenanceOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*memcachepb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp memcachepb.Instance if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1033,7 +2163,8 @@ func (op *RescheduleMaintenanceOperation) Name() string { // UpdateInstanceOperation manages a long-running operation from UpdateInstance. type UpdateInstanceOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateInstanceOperation returns a new UpdateInstanceOperation from a given name. @@ -1044,10 +2175,21 @@ func (c *cloudMemcacheGRPCClient) UpdateInstanceOperation(name string) *UpdateIn } } +// UpdateInstanceOperation returns a new UpdateInstanceOperation from a given name. +// The name must be that of a previously created UpdateInstanceOperation, possibly from a different process. +func (c *cloudMemcacheRESTClient) UpdateInstanceOperation(name string) *UpdateInstanceOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*memcachepb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp memcachepb.Instance if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1065,6 +2207,7 @@ func (op *UpdateInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOpt // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateInstanceOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*memcachepb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp memcachepb.Instance if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1102,7 +2245,8 @@ func (op *UpdateInstanceOperation) Name() string { // UpdateParametersOperation manages a long-running operation from UpdateParameters. type UpdateParametersOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateParametersOperation returns a new UpdateParametersOperation from a given name. @@ -1113,10 +2257,21 @@ func (c *cloudMemcacheGRPCClient) UpdateParametersOperation(name string) *Update } } +// UpdateParametersOperation returns a new UpdateParametersOperation from a given name. +// The name must be that of a previously created UpdateParametersOperation, possibly from a different process. +func (c *cloudMemcacheRESTClient) UpdateParametersOperation(name string) *UpdateParametersOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateParametersOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateParametersOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*memcachepb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp memcachepb.Instance if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1134,6 +2289,7 @@ func (op *UpdateParametersOperation) Wait(ctx context.Context, opts ...gax.CallO // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateParametersOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*memcachepb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp memcachepb.Instance if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/memcache/apiv1/cloud_memcache_client_example_test.go b/memcache/apiv1/cloud_memcache_client_example_test.go index e07ba5e8dbc3..3ffc4520bcc0 100644 --- a/memcache/apiv1/cloud_memcache_client_example_test.go +++ b/memcache/apiv1/cloud_memcache_client_example_test.go @@ -43,6 +43,23 @@ func ExampleNewCloudMemcacheClient() { _ = c } +func ExampleNewCloudMemcacheRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := memcache.NewCloudMemcacheRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleCloudMemcacheClient_ListInstances() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/memcache/apiv1/doc.go b/memcache/apiv1/doc.go index 3b2daa090b2f..7ffc0b13c0fb 100644 --- a/memcache/apiv1/doc.go +++ b/memcache/apiv1/doc.go @@ -87,6 +87,8 @@ package memcache // import "cloud.google.com/go/memcache/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -175,3 +177,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/memcache/apiv1/gapic_metadata.json b/memcache/apiv1/gapic_metadata.json index b4738a80fb96..4dd529be80ad 100644 --- a/memcache/apiv1/gapic_metadata.json +++ b/memcache/apiv1/gapic_metadata.json @@ -81,6 +81,81 @@ ] } } + }, + "rest": { + "libraryClient": "CloudMemcacheClient", + "rpcs": { + "ApplyParameters": { + "methods": [ + "ApplyParameters" + ] + }, + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "CreateInstance": { + "methods": [ + "CreateInstance" + ] + }, + "DeleteInstance": { + "methods": [ + "DeleteInstance" + ] + }, + "DeleteOperation": { + "methods": [ + "DeleteOperation" + ] + }, + "GetInstance": { + "methods": [ + "GetInstance" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ListInstances": { + "methods": [ + "ListInstances" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "RescheduleMaintenance": { + "methods": [ + "RescheduleMaintenance" + ] + }, + "UpdateInstance": { + "methods": [ + "UpdateInstance" + ] + }, + "UpdateParameters": { + "methods": [ + "UpdateParameters" + ] + } + } } } } diff --git a/memcache/apiv1/memcachepb/cloud_memcache.pb.go b/memcache/apiv1/memcachepb/cloud_memcache.pb.go index 9a15796a126b..8684bc59c86f 100644 --- a/memcache/apiv1/memcachepb/cloud_memcache.pb.go +++ b/memcache/apiv1/memcachepb/cloud_memcache.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/memcache/v1/cloud_memcache.proto package memcachepb @@ -335,8 +335,7 @@ type Instance struct { // Required. Unique name of the resource in this scope including project and // location using the form: - // - // `projects/{project_id}/locations/{location_id}/instances/{instance_id}` + // `projects/{project_id}/locations/{location_id}/instances/{instance_id}` // // Note: Memcached instances are managed and addressed at the regional level // so `location_id` here refers to a Google Cloud region; however, users may @@ -686,7 +685,7 @@ func (x *WeeklyMaintenanceWindow) GetDay() dayofweek.DayOfWeek { if x != nil { return x.Day } - return dayofweek.DayOfWeek_DAY_OF_WEEK_UNSPECIFIED + return dayofweek.DayOfWeek(0) } func (x *WeeklyMaintenanceWindow) GetStartTime() *timeofday.TimeOfDay { @@ -778,9 +777,7 @@ type RescheduleMaintenanceRequest struct { unknownFields protoimpl.UnknownFields // Required. Memcache instance resource name using the form: - // - // `projects/{project_id}/locations/{location_id}/instances/{instance_id}` - // + // `projects/{project_id}/locations/{location_id}/instances/{instance_id}` // where `location_id` refers to a GCP region. Instance string `protobuf:"bytes,1,opt,name=instance,proto3" json:"instance,omitempty"` // Required. If reschedule type is SPECIFIC_TIME, must set up schedule_time as well. @@ -851,9 +848,7 @@ type ListInstancesRequest struct { unknownFields protoimpl.UnknownFields // Required. The resource name of the instance location using the form: - // - // `projects/{project_id}/locations/{location_id}` - // + // `projects/{project_id}/locations/{location_id}` // where `location_id` refers to a GCP region Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // The maximum number of items to return. @@ -1019,9 +1014,7 @@ type GetInstanceRequest struct { unknownFields protoimpl.UnknownFields // Required. Memcached instance resource name in the format: - // - // `projects/{project_id}/locations/{location_id}/instances/{instance_id}` - // + // `projects/{project_id}/locations/{location_id}/instances/{instance_id}` // where `location_id` refers to a GCP region Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` } @@ -1072,9 +1065,7 @@ type CreateInstanceRequest struct { unknownFields protoimpl.UnknownFields // Required. The resource name of the instance location using the form: - // - // `projects/{project_id}/locations/{location_id}` - // + // `projects/{project_id}/locations/{location_id}` // where `location_id` refers to a GCP region Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // Required. The logical name of the Memcached instance in the user @@ -1153,7 +1144,7 @@ type UpdateInstanceRequest struct { // Required. Mask of fields to update. // - // - `displayName` + // * `displayName` UpdateMask *fieldmaskpb.FieldMask `protobuf:"bytes,1,opt,name=update_mask,json=updateMask,proto3" json:"update_mask,omitempty"` // Required. A Memcached Instance. // Only fields specified in update_mask are updated. @@ -1213,9 +1204,7 @@ type DeleteInstanceRequest struct { unknownFields protoimpl.UnknownFields // Required. Memcached instance resource name in the format: - // - // `projects/{project_id}/locations/{location_id}/instances/{instance_id}` - // + // `projects/{project_id}/locations/{location_id}/instances/{instance_id}` // where `location_id` refers to a GCP region Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` } diff --git a/memcache/apiv1beta2/cloud_memcache_client.go b/memcache/apiv1beta2/cloud_memcache_client.go index d04a719e94d7..b2e1ea293822 100644 --- a/memcache/apiv1beta2/cloud_memcache_client.go +++ b/memcache/apiv1beta2/cloud_memcache_client.go @@ -954,6 +954,7 @@ func (c *cloudMemcacheRESTClient) ListInstances(ctx context.Context, req *memcac baseUrl.Path += fmt.Sprintf("/v1beta2/%v/instances", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1033,6 +1034,11 @@ func (c *cloudMemcacheRESTClient) GetInstance(ctx context.Context, req *memcache } baseUrl.Path += fmt.Sprintf("/v1beta2/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1094,6 +1100,7 @@ func (c *cloudMemcacheRESTClient) CreateInstance(ctx context.Context, req *memca baseUrl.Path += fmt.Sprintf("/v1beta2/%v/instances", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("instanceId", fmt.Sprintf("%v", req.GetInstanceId())) baseUrl.RawQuery = params.Encode() @@ -1163,6 +1170,7 @@ func (c *cloudMemcacheRESTClient) UpdateInstance(ctx context.Context, req *memca baseUrl.Path += fmt.Sprintf("/v1beta2/%v", req.GetResource().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -1239,6 +1247,11 @@ func (c *cloudMemcacheRESTClient) UpdateParameters(ctx context.Context, req *mem } baseUrl.Path += fmt.Sprintf("/v1beta2/%v:updateParameters", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1296,6 +1309,11 @@ func (c *cloudMemcacheRESTClient) DeleteInstance(ctx context.Context, req *memca } baseUrl.Path += fmt.Sprintf("/v1beta2/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1360,6 +1378,11 @@ func (c *cloudMemcacheRESTClient) ApplyParameters(ctx context.Context, req *memc } baseUrl.Path += fmt.Sprintf("/v1beta2/%v:applyParameters", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1423,6 +1446,11 @@ func (c *cloudMemcacheRESTClient) ApplySoftwareUpdate(ctx context.Context, req * } baseUrl.Path += fmt.Sprintf("/v1beta2/%v:applySoftwareUpdate", req.GetInstance()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "instance", url.QueryEscape(req.GetInstance()))) @@ -1486,6 +1514,11 @@ func (c *cloudMemcacheRESTClient) RescheduleMaintenance(ctx context.Context, req } baseUrl.Path += fmt.Sprintf("/v1beta2/%v:rescheduleMaintenance", req.GetInstance()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "instance", url.QueryEscape(req.GetInstance()))) @@ -1543,6 +1576,11 @@ func (c *cloudMemcacheRESTClient) GetLocation(ctx context.Context, req *location } baseUrl.Path += fmt.Sprintf("/v1beta2/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1610,6 +1648,7 @@ func (c *cloudMemcacheRESTClient) ListLocations(ctx context.Context, req *locati baseUrl.Path += fmt.Sprintf("/v1beta2/%v/locations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1692,6 +1731,11 @@ func (c *cloudMemcacheRESTClient) CancelOperation(ctx context.Context, req *long } baseUrl.Path += fmt.Sprintf("/v1beta2/%v:cancel", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1727,6 +1771,11 @@ func (c *cloudMemcacheRESTClient) DeleteOperation(ctx context.Context, req *long } baseUrl.Path += fmt.Sprintf("/v1beta2/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1762,6 +1811,11 @@ func (c *cloudMemcacheRESTClient) GetOperation(ctx context.Context, req *longrun } baseUrl.Path += fmt.Sprintf("/v1beta2/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1829,6 +1883,7 @@ func (c *cloudMemcacheRESTClient) ListOperations(ctx context.Context, req *longr baseUrl.Path += fmt.Sprintf("/v1beta2/%v/operations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/memcache/apiv1beta2/memcachepb/cloud_memcache.pb.go b/memcache/apiv1beta2/memcachepb/cloud_memcache.pb.go index 9c43af59f7c3..ad10d2617c50 100644 --- a/memcache/apiv1beta2/memcachepb/cloud_memcache.pb.go +++ b/memcache/apiv1beta2/memcachepb/cloud_memcache.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/memcache/v1beta2/cloud_memcache.proto package memcachepb @@ -335,8 +335,7 @@ type Instance struct { // Required. Unique name of the resource in this scope including project and // location using the form: - // - // `projects/{project_id}/locations/{location_id}/instances/{instance_id}` + // `projects/{project_id}/locations/{location_id}/instances/{instance_id}` // // Note: Memcached instances are managed and addressed at the regional level // so `location_id` here refers to a Google Cloud region; however, users may @@ -695,7 +694,7 @@ func (x *WeeklyMaintenanceWindow) GetDay() dayofweek.DayOfWeek { if x != nil { return x.Day } - return dayofweek.DayOfWeek_DAY_OF_WEEK_UNSPECIFIED + return dayofweek.DayOfWeek(0) } func (x *WeeklyMaintenanceWindow) GetStartTime() *timeofday.TimeOfDay { @@ -787,9 +786,7 @@ type ListInstancesRequest struct { unknownFields protoimpl.UnknownFields // Required. The resource name of the instance location using the form: - // - // `projects/{project_id}/locations/{location_id}` - // + // `projects/{project_id}/locations/{location_id}` // where `location_id` refers to a GCP region Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // The maximum number of items to return. @@ -955,9 +952,7 @@ type GetInstanceRequest struct { unknownFields protoimpl.UnknownFields // Required. Memcached instance resource name in the format: - // - // `projects/{project_id}/locations/{location_id}/instances/{instance_id}` - // + // `projects/{project_id}/locations/{location_id}/instances/{instance_id}` // where `location_id` refers to a GCP region Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` } @@ -1008,9 +1003,7 @@ type CreateInstanceRequest struct { unknownFields protoimpl.UnknownFields // Required. The resource name of the instance location using the form: - // - // `projects/{project_id}/locations/{location_id}` - // + // `projects/{project_id}/locations/{location_id}` // where `location_id` refers to a GCP region Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // Required. The logical name of the Memcached instance in the user @@ -1089,7 +1082,7 @@ type UpdateInstanceRequest struct { // Required. Mask of fields to update. // - // - `displayName` + // * `displayName` UpdateMask *fieldmaskpb.FieldMask `protobuf:"bytes,1,opt,name=update_mask,json=updateMask,proto3" json:"update_mask,omitempty"` // Required. A Memcached [Instance] resource. // Only fields specified in update_mask are updated. @@ -1149,9 +1142,7 @@ type DeleteInstanceRequest struct { unknownFields protoimpl.UnknownFields // Required. Memcached instance resource name in the format: - // - // `projects/{project_id}/locations/{location_id}/instances/{instance_id}` - // + // `projects/{project_id}/locations/{location_id}/instances/{instance_id}` // where `location_id` refers to a GCP region Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` } @@ -1202,9 +1193,7 @@ type RescheduleMaintenanceRequest struct { unknownFields protoimpl.UnknownFields // Required. Memcache instance resource name using the form: - // - // `projects/{project_id}/locations/{location_id}/instances/{instance_id}` - // + // `projects/{project_id}/locations/{location_id}/instances/{instance_id}` // where `location_id` refers to a GCP region. Instance string `protobuf:"bytes,1,opt,name=instance,proto3" json:"instance,omitempty"` // Required. If reschedule type is SPECIFIC_TIME, must set up schedule_time as well. diff --git a/metastore/apiv1/dataproc_metastore_client.go b/metastore/apiv1/dataproc_metastore_client.go index f8d465a91ca4..edb611a8d9de 100644 --- a/metastore/apiv1/dataproc_metastore_client.go +++ b/metastore/apiv1/dataproc_metastore_client.go @@ -17,9 +17,12 @@ package metastore import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,16 +30,19 @@ import ( lroauto "cloud.google.com/go/longrunning/autogen" metastorepb "cloud.google.com/go/metastore/apiv1/metastorepb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" iampb "google.golang.org/genproto/googleapis/iam/v1" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -169,6 +175,88 @@ func defaultDataprocMetastoreCallOptions() *DataprocMetastoreCallOptions { } } +func defaultDataprocMetastoreRESTCallOptions() *DataprocMetastoreCallOptions { + return &DataprocMetastoreCallOptions{ + ListServices: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetService: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateService: []gax.CallOption{}, + UpdateService: []gax.CallOption{}, + DeleteService: []gax.CallOption{}, + ListMetadataImports: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetMetadataImport: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateMetadataImport: []gax.CallOption{}, + UpdateMetadataImport: []gax.CallOption{}, + ExportMetadata: []gax.CallOption{}, + RestoreService: []gax.CallOption{}, + ListBackups: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetBackup: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateBackup: []gax.CallOption{}, + DeleteBackup: []gax.CallOption{}, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + GetIamPolicy: []gax.CallOption{}, + SetIamPolicy: []gax.CallOption{}, + TestIamPermissions: []gax.CallOption{}, + DeleteOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalDataprocMetastoreClient is an interface that defines the methods available from Dataproc Metastore API. type internalDataprocMetastoreClient interface { Close() error @@ -573,6 +661,108 @@ func (c *dataprocMetastoreGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type dataprocMetastoreRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing DataprocMetastoreClient + CallOptions **DataprocMetastoreCallOptions +} + +// NewDataprocMetastoreRESTClient creates a new dataproc metastore rest client. +// +// Configures and manages metastore services. +// Metastore services are fully managed, highly available, autoscaled, +// autohealing, OSS-native deployments of technical metadata management +// software. Each metastore service exposes a network endpoint through which +// metadata queries are served. Metadata queries can originate from a variety +// of sources, including Apache Hive, Apache Presto, and Apache Spark. +// +// The Dataproc Metastore API defines the following resource model: +// +// The service works with a collection of Google Cloud projects, named: +// /projects/* +// +// Each project has a collection of available locations, named: /locations/* +// (a location must refer to a Google Cloud region) +// +// Each location has a collection of services, named: /services/* +// +// Dataproc Metastore services are resources with names of the form: +// +// /projects/{project_number}/locations/{location_id}/services/{service_id}. +func NewDataprocMetastoreRESTClient(ctx context.Context, opts ...option.ClientOption) (*DataprocMetastoreClient, error) { + clientOpts := append(defaultDataprocMetastoreRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultDataprocMetastoreRESTCallOptions() + c := &dataprocMetastoreRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &DataprocMetastoreClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultDataprocMetastoreRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://metastore.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://metastore.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://metastore.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *dataprocMetastoreRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *dataprocMetastoreRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *dataprocMetastoreRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *dataprocMetastoreGRPCClient) ListServices(ctx context.Context, req *metastorepb.ListServicesRequest, opts ...gax.CallOption) *ServiceIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1178,78 +1368,1730 @@ func (c *dataprocMetastoreGRPCClient) ListOperations(ctx context.Context, req *l return it } -// CreateBackupOperation manages a long-running operation from CreateBackup. -type CreateBackupOperation struct { - lro *longrunning.Operation -} +// ListServices lists services in a project and location. +func (c *dataprocMetastoreRESTClient) ListServices(ctx context.Context, req *metastorepb.ListServicesRequest, opts ...gax.CallOption) *ServiceIterator { + it := &ServiceIterator{} + req = proto.Clone(req).(*metastorepb.ListServicesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*metastorepb.Service, string, error) { + resp := &metastorepb.ListServicesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/services", req.GetParent()) -// CreateBackupOperation returns a new CreateBackupOperation from a given name. -// The name must be that of a previously created CreateBackupOperation, possibly from a different process. -func (c *dataprocMetastoreGRPCClient) CreateBackupOperation(name string) *CreateBackupOperation { - return &CreateBackupOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetServices(), resp.GetNextPageToken(), nil } -} -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *CreateBackupOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*metastorepb.Backup, error) { - var resp metastorepb.Backup - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { - return nil, err + 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 } - return &resp, nil + + it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it } -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *CreateBackupOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*metastorepb.Backup, error) { - var resp metastorepb.Backup - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { +// GetService gets the details of a single service. +func (c *dataprocMetastoreRESTClient) GetService(ctx context.Context, req *metastorepb.GetServiceRequest, opts ...gax.CallOption) (*metastorepb.Service, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - if !op.Done() { - return nil, nil + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetService[0:len((*c.CallOptions).GetService):len((*c.CallOptions).GetService)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &metastorepb.Service{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e } - return &resp, nil + return resp, nil } -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *CreateBackupOperation) Metadata() (*metastorepb.OperationMetadata, error) { - var meta metastorepb.OperationMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { +// CreateService creates a metastore service in a project and location. +func (c *dataprocMetastoreRESTClient) CreateService(ctx context.Context, req *metastorepb.CreateServiceRequest, opts ...gax.CallOption) (*CreateServiceOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetService() + jsonReq, err := m.Marshal(body) + if err != nil { return nil, err } - return &meta, nil -} -// Done reports whether the long-running operation has completed. -func (op *CreateBackupOperation) Done() bool { - return op.lro.Done() -} + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/services", req.GetParent()) -// 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 *CreateBackupOperation) Name() string { - return op.lro.Name() -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + params.Add("serviceId", fmt.Sprintf("%v", req.GetServiceId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateServiceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateService updates the parameters of a single service. +func (c *dataprocMetastoreRESTClient) UpdateService(ctx context.Context, req *metastorepb.UpdateServiceRequest, opts ...gax.CallOption) (*UpdateServiceOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetService() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetService().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "service.name", url.QueryEscape(req.GetService().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateServiceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteService deletes a single service. +func (c *dataprocMetastoreRESTClient) DeleteService(ctx context.Context, req *metastorepb.DeleteServiceRequest, opts ...gax.CallOption) (*DeleteServiceOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteServiceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListMetadataImports lists imports in a service. +func (c *dataprocMetastoreRESTClient) ListMetadataImports(ctx context.Context, req *metastorepb.ListMetadataImportsRequest, opts ...gax.CallOption) *MetadataImportIterator { + it := &MetadataImportIterator{} + req = proto.Clone(req).(*metastorepb.ListMetadataImportsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*metastorepb.MetadataImport, string, error) { + resp := &metastorepb.ListMetadataImportsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/metadataImports", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetMetadataImports(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetMetadataImport gets details of a single import. +func (c *dataprocMetastoreRESTClient) GetMetadataImport(ctx context.Context, req *metastorepb.GetMetadataImportRequest, opts ...gax.CallOption) (*metastorepb.MetadataImport, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetMetadataImport[0:len((*c.CallOptions).GetMetadataImport):len((*c.CallOptions).GetMetadataImport)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &metastorepb.MetadataImport{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateMetadataImport creates a new MetadataImport in a given project and location. +func (c *dataprocMetastoreRESTClient) CreateMetadataImport(ctx context.Context, req *metastorepb.CreateMetadataImportRequest, opts ...gax.CallOption) (*CreateMetadataImportOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetMetadataImport() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/metadataImports", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("metadataImportId", fmt.Sprintf("%v", req.GetMetadataImportId())) + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateMetadataImportOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateMetadataImport updates a single import. +// Only the description field of MetadataImport is supported to be updated. +func (c *dataprocMetastoreRESTClient) UpdateMetadataImport(ctx context.Context, req *metastorepb.UpdateMetadataImportRequest, opts ...gax.CallOption) (*UpdateMetadataImportOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetMetadataImport() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetMetadataImport().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "metadata_import.name", url.QueryEscape(req.GetMetadataImport().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateMetadataImportOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ExportMetadata exports metadata from a service. +func (c *dataprocMetastoreRESTClient) ExportMetadata(ctx context.Context, req *metastorepb.ExportMetadataRequest, opts ...gax.CallOption) (*ExportMetadataOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:exportMetadata", req.GetService()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "service", url.QueryEscape(req.GetService()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &ExportMetadataOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// RestoreService restores a service from a backup. +func (c *dataprocMetastoreRESTClient) RestoreService(ctx context.Context, req *metastorepb.RestoreServiceRequest, opts ...gax.CallOption) (*RestoreServiceOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:restore", req.GetService()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "service", url.QueryEscape(req.GetService()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &RestoreServiceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListBackups lists backups in a service. +func (c *dataprocMetastoreRESTClient) ListBackups(ctx context.Context, req *metastorepb.ListBackupsRequest, opts ...gax.CallOption) *BackupIterator { + it := &BackupIterator{} + req = proto.Clone(req).(*metastorepb.ListBackupsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*metastorepb.Backup, string, error) { + resp := &metastorepb.ListBackupsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/backups", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetBackups(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetBackup gets details of a single backup. +func (c *dataprocMetastoreRESTClient) GetBackup(ctx context.Context, req *metastorepb.GetBackupRequest, opts ...gax.CallOption) (*metastorepb.Backup, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetBackup[0:len((*c.CallOptions).GetBackup):len((*c.CallOptions).GetBackup)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &metastorepb.Backup{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateBackup creates a new backup in a given project and location. +func (c *dataprocMetastoreRESTClient) CreateBackup(ctx context.Context, req *metastorepb.CreateBackupRequest, opts ...gax.CallOption) (*CreateBackupOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetBackup() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/backups", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("backupId", fmt.Sprintf("%v", req.GetBackupId())) + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateBackupOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteBackup deletes a single backup. +func (c *dataprocMetastoreRESTClient) DeleteBackup(ctx context.Context, req *metastorepb.DeleteBackupRequest, opts ...gax.CallOption) (*DeleteBackupOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteBackupOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetLocation gets information about a location. +func (c *dataprocMetastoreRESTClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *dataprocMetastoreRESTClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetIamPolicy gets the access control policy for a resource. Returns an empty policy +// if the resource exists and does not have a policy set. +func (c *dataprocMetastoreRESTClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:getIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetOptions().GetRequestedPolicyVersion() != 0 { + params.Add("options.requestedPolicyVersion", fmt.Sprintf("%v", req.GetOptions().GetRequestedPolicyVersion())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SetIamPolicy sets the access control policy on the specified resource. Replaces +// any existing policy. +// +// Can return NOT_FOUND, INVALID_ARGUMENT, and PERMISSION_DENIED +// errors. +func (c *dataprocMetastoreRESTClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:setIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// TestIamPermissions returns permissions that a caller has on the specified resource. If the +// resource does not exist, this will return an empty set of +// permissions, not a NOT_FOUND error. +// +// Note: This operation is designed to be used for building +// permission-aware UIs and command-line tools, not for authorization +// checking. This operation may “fail open” without warning. +func (c *dataprocMetastoreRESTClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:testIamPermissions", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.TestIamPermissionsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteOperation is a utility method from google.longrunning.Operations. +func (c *dataprocMetastoreRESTClient) DeleteOperation(ctx context.Context, req *longrunningpb.DeleteOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *dataprocMetastoreRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *dataprocMetastoreRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CreateBackupOperation manages a long-running operation from CreateBackup. +type CreateBackupOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateBackupOperation returns a new CreateBackupOperation from a given name. +// The name must be that of a previously created CreateBackupOperation, possibly from a different process. +func (c *dataprocMetastoreGRPCClient) CreateBackupOperation(name string) *CreateBackupOperation { + return &CreateBackupOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateBackupOperation returns a new CreateBackupOperation from a given name. +// The name must be that of a previously created CreateBackupOperation, possibly from a different process. +func (c *dataprocMetastoreRESTClient) CreateBackupOperation(name string) *CreateBackupOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateBackupOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CreateBackupOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*metastorepb.Backup, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp metastorepb.Backup + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *CreateBackupOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*metastorepb.Backup, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp metastorepb.Backup + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *CreateBackupOperation) Metadata() (*metastorepb.OperationMetadata, error) { + var meta metastorepb.OperationMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *CreateBackupOperation) Done() bool { + return op.lro.Done() +} + +// 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 *CreateBackupOperation) Name() string { + return op.lro.Name() +} // CreateMetadataImportOperation manages a long-running operation from CreateMetadataImport. type CreateMetadataImportOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateMetadataImportOperation returns a new CreateMetadataImportOperation from a given name. @@ -1260,10 +3102,21 @@ func (c *dataprocMetastoreGRPCClient) CreateMetadataImportOperation(name string) } } +// CreateMetadataImportOperation returns a new CreateMetadataImportOperation from a given name. +// The name must be that of a previously created CreateMetadataImportOperation, possibly from a different process. +func (c *dataprocMetastoreRESTClient) CreateMetadataImportOperation(name string) *CreateMetadataImportOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateMetadataImportOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateMetadataImportOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*metastorepb.MetadataImport, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp metastorepb.MetadataImport if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1281,6 +3134,7 @@ func (op *CreateMetadataImportOperation) Wait(ctx context.Context, opts ...gax.C // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateMetadataImportOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*metastorepb.MetadataImport, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp metastorepb.MetadataImport if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1318,7 +3172,8 @@ func (op *CreateMetadataImportOperation) Name() string { // CreateServiceOperation manages a long-running operation from CreateService. type CreateServiceOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateServiceOperation returns a new CreateServiceOperation from a given name. @@ -1329,10 +3184,21 @@ func (c *dataprocMetastoreGRPCClient) CreateServiceOperation(name string) *Creat } } +// CreateServiceOperation returns a new CreateServiceOperation from a given name. +// The name must be that of a previously created CreateServiceOperation, possibly from a different process. +func (c *dataprocMetastoreRESTClient) CreateServiceOperation(name string) *CreateServiceOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateServiceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateServiceOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*metastorepb.Service, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp metastorepb.Service if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1350,6 +3216,7 @@ func (op *CreateServiceOperation) Wait(ctx context.Context, opts ...gax.CallOpti // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateServiceOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*metastorepb.Service, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp metastorepb.Service if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1387,7 +3254,8 @@ func (op *CreateServiceOperation) Name() string { // DeleteBackupOperation manages a long-running operation from DeleteBackup. type DeleteBackupOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteBackupOperation returns a new DeleteBackupOperation from a given name. @@ -1398,10 +3266,21 @@ func (c *dataprocMetastoreGRPCClient) DeleteBackupOperation(name string) *Delete } } +// DeleteBackupOperation returns a new DeleteBackupOperation from a given name. +// The name must be that of a previously created DeleteBackupOperation, possibly from a different process. +func (c *dataprocMetastoreRESTClient) DeleteBackupOperation(name string) *DeleteBackupOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteBackupOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteBackupOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -1415,6 +3294,7 @@ func (op *DeleteBackupOperation) Wait(ctx context.Context, opts ...gax.CallOptio // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteBackupOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -1445,7 +3325,8 @@ func (op *DeleteBackupOperation) Name() string { // DeleteServiceOperation manages a long-running operation from DeleteService. type DeleteServiceOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteServiceOperation returns a new DeleteServiceOperation from a given name. @@ -1456,10 +3337,21 @@ func (c *dataprocMetastoreGRPCClient) DeleteServiceOperation(name string) *Delet } } +// DeleteServiceOperation returns a new DeleteServiceOperation from a given name. +// The name must be that of a previously created DeleteServiceOperation, possibly from a different process. +func (c *dataprocMetastoreRESTClient) DeleteServiceOperation(name string) *DeleteServiceOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteServiceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteServiceOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -1473,6 +3365,7 @@ func (op *DeleteServiceOperation) Wait(ctx context.Context, opts ...gax.CallOpti // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteServiceOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -1503,7 +3396,8 @@ func (op *DeleteServiceOperation) Name() string { // ExportMetadataOperation manages a long-running operation from ExportMetadata. type ExportMetadataOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // ExportMetadataOperation returns a new ExportMetadataOperation from a given name. @@ -1514,10 +3408,21 @@ func (c *dataprocMetastoreGRPCClient) ExportMetadataOperation(name string) *Expo } } +// ExportMetadataOperation returns a new ExportMetadataOperation from a given name. +// The name must be that of a previously created ExportMetadataOperation, possibly from a different process. +func (c *dataprocMetastoreRESTClient) ExportMetadataOperation(name string) *ExportMetadataOperation { + override := fmt.Sprintf("/v1/%s", name) + return &ExportMetadataOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *ExportMetadataOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*metastorepb.MetadataExport, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp metastorepb.MetadataExport if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1535,6 +3440,7 @@ func (op *ExportMetadataOperation) Wait(ctx context.Context, opts ...gax.CallOpt // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *ExportMetadataOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*metastorepb.MetadataExport, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp metastorepb.MetadataExport if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1572,7 +3478,8 @@ func (op *ExportMetadataOperation) Name() string { // RestoreServiceOperation manages a long-running operation from RestoreService. type RestoreServiceOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // RestoreServiceOperation returns a new RestoreServiceOperation from a given name. @@ -1583,10 +3490,21 @@ func (c *dataprocMetastoreGRPCClient) RestoreServiceOperation(name string) *Rest } } +// RestoreServiceOperation returns a new RestoreServiceOperation from a given name. +// The name must be that of a previously created RestoreServiceOperation, possibly from a different process. +func (c *dataprocMetastoreRESTClient) RestoreServiceOperation(name string) *RestoreServiceOperation { + override := fmt.Sprintf("/v1/%s", name) + return &RestoreServiceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *RestoreServiceOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*metastorepb.Restore, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp metastorepb.Restore if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1604,6 +3522,7 @@ func (op *RestoreServiceOperation) Wait(ctx context.Context, opts ...gax.CallOpt // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *RestoreServiceOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*metastorepb.Restore, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp metastorepb.Restore if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1641,7 +3560,8 @@ func (op *RestoreServiceOperation) Name() string { // UpdateMetadataImportOperation manages a long-running operation from UpdateMetadataImport. type UpdateMetadataImportOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateMetadataImportOperation returns a new UpdateMetadataImportOperation from a given name. @@ -1652,10 +3572,21 @@ func (c *dataprocMetastoreGRPCClient) UpdateMetadataImportOperation(name string) } } +// UpdateMetadataImportOperation returns a new UpdateMetadataImportOperation from a given name. +// The name must be that of a previously created UpdateMetadataImportOperation, possibly from a different process. +func (c *dataprocMetastoreRESTClient) UpdateMetadataImportOperation(name string) *UpdateMetadataImportOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateMetadataImportOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateMetadataImportOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*metastorepb.MetadataImport, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp metastorepb.MetadataImport if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1673,6 +3604,7 @@ func (op *UpdateMetadataImportOperation) Wait(ctx context.Context, opts ...gax.C // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateMetadataImportOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*metastorepb.MetadataImport, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp metastorepb.MetadataImport if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1710,7 +3642,8 @@ func (op *UpdateMetadataImportOperation) Name() string { // UpdateServiceOperation manages a long-running operation from UpdateService. type UpdateServiceOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateServiceOperation returns a new UpdateServiceOperation from a given name. @@ -1721,10 +3654,21 @@ func (c *dataprocMetastoreGRPCClient) UpdateServiceOperation(name string) *Updat } } +// UpdateServiceOperation returns a new UpdateServiceOperation from a given name. +// The name must be that of a previously created UpdateServiceOperation, possibly from a different process. +func (c *dataprocMetastoreRESTClient) UpdateServiceOperation(name string) *UpdateServiceOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateServiceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateServiceOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*metastorepb.Service, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp metastorepb.Service if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1742,6 +3686,7 @@ func (op *UpdateServiceOperation) Wait(ctx context.Context, opts ...gax.CallOpti // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateServiceOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*metastorepb.Service, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp metastorepb.Service if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/metastore/apiv1/dataproc_metastore_client_example_test.go b/metastore/apiv1/dataproc_metastore_client_example_test.go index 1864a721dc08..13c73000b6e3 100644 --- a/metastore/apiv1/dataproc_metastore_client_example_test.go +++ b/metastore/apiv1/dataproc_metastore_client_example_test.go @@ -44,6 +44,23 @@ func ExampleNewDataprocMetastoreClient() { _ = c } +func ExampleNewDataprocMetastoreRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := metastore.NewDataprocMetastoreRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleDataprocMetastoreClient_ListServices() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/metastore/apiv1/dataproc_metastore_federation_client.go b/metastore/apiv1/dataproc_metastore_federation_client.go index 60bd7dc8df04..d57b87852d00 100644 --- a/metastore/apiv1/dataproc_metastore_federation_client.go +++ b/metastore/apiv1/dataproc_metastore_federation_client.go @@ -17,9 +17,12 @@ package metastore import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,15 +30,18 @@ import ( lroauto "cloud.google.com/go/longrunning/autogen" metastorepb "cloud.google.com/go/metastore/apiv1/metastorepb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" iampb "google.golang.org/genproto/googleapis/iam/v1" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -88,6 +94,24 @@ func defaultDataprocMetastoreFederationCallOptions() *DataprocMetastoreFederatio } } +func defaultDataprocMetastoreFederationRESTCallOptions() *DataprocMetastoreFederationCallOptions { + return &DataprocMetastoreFederationCallOptions{ + ListFederations: []gax.CallOption{}, + GetFederation: []gax.CallOption{}, + CreateFederation: []gax.CallOption{}, + UpdateFederation: []gax.CallOption{}, + DeleteFederation: []gax.CallOption{}, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + GetIamPolicy: []gax.CallOption{}, + SetIamPolicy: []gax.CallOption{}, + TestIamPermissions: []gax.CallOption{}, + DeleteOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalDataprocMetastoreFederationClient is an interface that defines the methods available from Dataproc Metastore API. type internalDataprocMetastoreFederationClient interface { Close() error @@ -383,6 +407,105 @@ func (c *dataprocMetastoreFederationGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type dataprocMetastoreFederationRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing DataprocMetastoreFederationClient + CallOptions **DataprocMetastoreFederationCallOptions +} + +// NewDataprocMetastoreFederationRESTClient creates a new dataproc metastore federation rest client. +// +// Configures and manages metastore federation services. +// Dataproc Metastore Federation Service allows federating a collection of +// backend metastores like BigQuery, Dataplex Lakes, and other Dataproc +// Metastores. The Federation Service exposes a gRPC URL through which metadata +// from the backend metastores are served at query time. +// +// The Dataproc Metastore Federation API defines the following resource model: +// +// The service works with a collection of Google Cloud projects. +// +// Each project has a collection of available locations. +// +// Each location has a collection of federations. +// +// Dataproc Metastore Federations are resources with names of the +// form: +// projects/{project_number}/locations/{location_id}/federations/{federation_id}. +func NewDataprocMetastoreFederationRESTClient(ctx context.Context, opts ...option.ClientOption) (*DataprocMetastoreFederationClient, error) { + clientOpts := append(defaultDataprocMetastoreFederationRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultDataprocMetastoreFederationRESTCallOptions() + c := &dataprocMetastoreFederationRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &DataprocMetastoreFederationClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultDataprocMetastoreFederationRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://metastore.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://metastore.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://metastore.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *dataprocMetastoreFederationRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *dataprocMetastoreFederationRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *dataprocMetastoreFederationRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *dataprocMetastoreFederationGRPCClient) ListFederations(ctx context.Context, req *metastorepb.ListFederationsRequest, opts ...gax.CallOption) *FederationIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -690,137 +813,1071 @@ func (c *dataprocMetastoreFederationGRPCClient) ListOperations(ctx context.Conte return it } -// CreateFederationOperation manages a long-running operation from CreateFederation. -type CreateFederationOperation struct { - lro *longrunning.Operation -} +// ListFederations lists federations in a project and location. +func (c *dataprocMetastoreFederationRESTClient) ListFederations(ctx context.Context, req *metastorepb.ListFederationsRequest, opts ...gax.CallOption) *FederationIterator { + it := &FederationIterator{} + req = proto.Clone(req).(*metastorepb.ListFederationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*metastorepb.Federation, string, error) { + resp := &metastorepb.ListFederationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/federations", req.GetParent()) -// CreateFederationOperation returns a new CreateFederationOperation from a given name. -// The name must be that of a previously created CreateFederationOperation, possibly from a different process. -func (c *dataprocMetastoreFederationGRPCClient) CreateFederationOperation(name string) *CreateFederationOperation { - return &CreateFederationOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *CreateFederationOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*metastorepb.Federation, error) { - var resp metastorepb.Federation - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { - return nil, err + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetFederations(), resp.GetNextPageToken(), nil } - return &resp, nil -} -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *CreateFederationOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*metastorepb.Federation, error) { - var resp metastorepb.Federation - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { - return nil, err - } - if !op.Done() { - return nil, 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 } - return &resp, nil + + it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it } -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *CreateFederationOperation) Metadata() (*metastorepb.OperationMetadata, error) { - var meta metastorepb.OperationMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { +// GetFederation gets the details of a single federation. +func (c *dataprocMetastoreFederationRESTClient) GetFederation(ctx context.Context, req *metastorepb.GetFederationRequest, opts ...gax.CallOption) (*metastorepb.Federation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - return &meta, nil -} + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) -// Done reports whether the long-running operation has completed. -func (op *CreateFederationOperation) Done() bool { - return op.lro.Done() -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") -// 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 *CreateFederationOperation) Name() string { - return op.lro.Name() -} + baseUrl.RawQuery = params.Encode() -// DeleteFederationOperation manages a long-running operation from DeleteFederation. -type DeleteFederationOperation struct { - lro *longrunning.Operation -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) -// DeleteFederationOperation returns a new DeleteFederationOperation from a given name. -// The name must be that of a previously created DeleteFederationOperation, possibly from a different process. -func (c *dataprocMetastoreFederationGRPCClient) DeleteFederationOperation(name string) *DeleteFederationOperation { - return &DeleteFederationOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetFederation[0:len((*c.CallOptions).GetFederation):len((*c.CallOptions).GetFederation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &metastorepb.Federation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *DeleteFederationOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { - return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) -} + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *DeleteFederationOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { - return op.lro.Poll(ctx, nil, opts...) + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil } -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *DeleteFederationOperation) Metadata() (*metastorepb.OperationMetadata, error) { - var meta metastorepb.OperationMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { +// CreateFederation creates a metastore federation in a project and location. +func (c *dataprocMetastoreFederationRESTClient) CreateFederation(ctx context.Context, req *metastorepb.CreateFederationRequest, opts ...gax.CallOption) (*CreateFederationOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetFederation() + jsonReq, err := m.Marshal(body) + if err != nil { return nil, err } - return &meta, nil -} -// Done reports whether the long-running operation has completed. -func (op *DeleteFederationOperation) Done() bool { - return op.lro.Done() -} + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/federations", req.GetParent()) -// 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 *DeleteFederationOperation) Name() string { - return op.lro.Name() -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("federationId", fmt.Sprintf("%v", req.GetFederationId())) + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } -// UpdateFederationOperation manages a long-running operation from UpdateFederation. -type UpdateFederationOperation struct { - lro *longrunning.Operation -} + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateFederationOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateFederation updates the fields of a federation. +func (c *dataprocMetastoreFederationRESTClient) UpdateFederation(ctx context.Context, req *metastorepb.UpdateFederationRequest, opts ...gax.CallOption) (*UpdateFederationOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetFederation() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetFederation().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "federation.name", url.QueryEscape(req.GetFederation().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateFederationOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteFederation deletes a single federation. +func (c *dataprocMetastoreFederationRESTClient) DeleteFederation(ctx context.Context, req *metastorepb.DeleteFederationRequest, opts ...gax.CallOption) (*DeleteFederationOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteFederationOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetLocation gets information about a location. +func (c *dataprocMetastoreFederationRESTClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *dataprocMetastoreFederationRESTClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetIamPolicy gets the access control policy for a resource. Returns an empty policy +// if the resource exists and does not have a policy set. +func (c *dataprocMetastoreFederationRESTClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:getIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetOptions().GetRequestedPolicyVersion() != 0 { + params.Add("options.requestedPolicyVersion", fmt.Sprintf("%v", req.GetOptions().GetRequestedPolicyVersion())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SetIamPolicy sets the access control policy on the specified resource. Replaces +// any existing policy. +// +// Can return NOT_FOUND, INVALID_ARGUMENT, and PERMISSION_DENIED +// errors. +func (c *dataprocMetastoreFederationRESTClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:setIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// TestIamPermissions returns permissions that a caller has on the specified resource. If the +// resource does not exist, this will return an empty set of +// permissions, not a NOT_FOUND error. +// +// Note: This operation is designed to be used for building +// permission-aware UIs and command-line tools, not for authorization +// checking. This operation may “fail open” without warning. +func (c *dataprocMetastoreFederationRESTClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:testIamPermissions", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.TestIamPermissionsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteOperation is a utility method from google.longrunning.Operations. +func (c *dataprocMetastoreFederationRESTClient) DeleteOperation(ctx context.Context, req *longrunningpb.DeleteOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *dataprocMetastoreFederationRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *dataprocMetastoreFederationRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CreateFederationOperation manages a long-running operation from CreateFederation. +type CreateFederationOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateFederationOperation returns a new CreateFederationOperation from a given name. +// The name must be that of a previously created CreateFederationOperation, possibly from a different process. +func (c *dataprocMetastoreFederationGRPCClient) CreateFederationOperation(name string) *CreateFederationOperation { + return &CreateFederationOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateFederationOperation returns a new CreateFederationOperation from a given name. +// The name must be that of a previously created CreateFederationOperation, possibly from a different process. +func (c *dataprocMetastoreFederationRESTClient) CreateFederationOperation(name string) *CreateFederationOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateFederationOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CreateFederationOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*metastorepb.Federation, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp metastorepb.Federation + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *CreateFederationOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*metastorepb.Federation, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp metastorepb.Federation + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *CreateFederationOperation) Metadata() (*metastorepb.OperationMetadata, error) { + var meta metastorepb.OperationMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *CreateFederationOperation) Done() bool { + return op.lro.Done() +} + +// 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 *CreateFederationOperation) Name() string { + return op.lro.Name() +} + +// DeleteFederationOperation manages a long-running operation from DeleteFederation. +type DeleteFederationOperation struct { + lro *longrunning.Operation + pollPath string +} + +// DeleteFederationOperation returns a new DeleteFederationOperation from a given name. +// The name must be that of a previously created DeleteFederationOperation, possibly from a different process. +func (c *dataprocMetastoreFederationGRPCClient) DeleteFederationOperation(name string) *DeleteFederationOperation { + return &DeleteFederationOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// DeleteFederationOperation returns a new DeleteFederationOperation from a given name. +// The name must be that of a previously created DeleteFederationOperation, possibly from a different process. +func (c *dataprocMetastoreFederationRESTClient) DeleteFederationOperation(name string) *DeleteFederationOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteFederationOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *DeleteFederationOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *DeleteFederationOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + return op.lro.Poll(ctx, nil, opts...) +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *DeleteFederationOperation) Metadata() (*metastorepb.OperationMetadata, error) { + var meta metastorepb.OperationMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *DeleteFederationOperation) Done() bool { + return op.lro.Done() +} + +// 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 *DeleteFederationOperation) Name() string { + return op.lro.Name() +} + +// UpdateFederationOperation manages a long-running operation from UpdateFederation. +type UpdateFederationOperation struct { + lro *longrunning.Operation + pollPath string +} // UpdateFederationOperation returns a new UpdateFederationOperation from a given name. // The name must be that of a previously created UpdateFederationOperation, possibly from a different process. @@ -830,10 +1887,21 @@ func (c *dataprocMetastoreFederationGRPCClient) UpdateFederationOperation(name s } } +// UpdateFederationOperation returns a new UpdateFederationOperation from a given name. +// The name must be that of a previously created UpdateFederationOperation, possibly from a different process. +func (c *dataprocMetastoreFederationRESTClient) UpdateFederationOperation(name string) *UpdateFederationOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateFederationOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateFederationOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*metastorepb.Federation, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp metastorepb.Federation if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -851,6 +1919,7 @@ func (op *UpdateFederationOperation) Wait(ctx context.Context, opts ...gax.CallO // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateFederationOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*metastorepb.Federation, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp metastorepb.Federation if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/metastore/apiv1/dataproc_metastore_federation_client_example_test.go b/metastore/apiv1/dataproc_metastore_federation_client_example_test.go index 998dbabc30f5..fe64dd57a938 100644 --- a/metastore/apiv1/dataproc_metastore_federation_client_example_test.go +++ b/metastore/apiv1/dataproc_metastore_federation_client_example_test.go @@ -44,6 +44,23 @@ func ExampleNewDataprocMetastoreFederationClient() { _ = c } +func ExampleNewDataprocMetastoreFederationRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := metastore.NewDataprocMetastoreFederationRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleDataprocMetastoreFederationClient_ListFederations() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/metastore/apiv1/doc.go b/metastore/apiv1/doc.go index 76c7a401e70a..5d97185d8869 100644 --- a/metastore/apiv1/doc.go +++ b/metastore/apiv1/doc.go @@ -87,6 +87,8 @@ package metastore // import "cloud.google.com/go/metastore/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -175,3 +177,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/metastore/apiv1/gapic_metadata.json b/metastore/apiv1/gapic_metadata.json index a0a6cfc65449..b65cfc38cdf1 100644 --- a/metastore/apiv1/gapic_metadata.json +++ b/metastore/apiv1/gapic_metadata.json @@ -126,6 +126,126 @@ ] } } + }, + "rest": { + "libraryClient": "DataprocMetastoreClient", + "rpcs": { + "CreateBackup": { + "methods": [ + "CreateBackup" + ] + }, + "CreateMetadataImport": { + "methods": [ + "CreateMetadataImport" + ] + }, + "CreateService": { + "methods": [ + "CreateService" + ] + }, + "DeleteBackup": { + "methods": [ + "DeleteBackup" + ] + }, + "DeleteOperation": { + "methods": [ + "DeleteOperation" + ] + }, + "DeleteService": { + "methods": [ + "DeleteService" + ] + }, + "ExportMetadata": { + "methods": [ + "ExportMetadata" + ] + }, + "GetBackup": { + "methods": [ + "GetBackup" + ] + }, + "GetIamPolicy": { + "methods": [ + "GetIamPolicy" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "GetMetadataImport": { + "methods": [ + "GetMetadataImport" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "GetService": { + "methods": [ + "GetService" + ] + }, + "ListBackups": { + "methods": [ + "ListBackups" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListMetadataImports": { + "methods": [ + "ListMetadataImports" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "ListServices": { + "methods": [ + "ListServices" + ] + }, + "RestoreService": { + "methods": [ + "RestoreService" + ] + }, + "SetIamPolicy": { + "methods": [ + "SetIamPolicy" + ] + }, + "TestIamPermissions": { + "methods": [ + "TestIamPermissions" + ] + }, + "UpdateMetadataImport": { + "methods": [ + "UpdateMetadataImport" + ] + }, + "UpdateService": { + "methods": [ + "UpdateService" + ] + } + } } } }, @@ -200,6 +320,76 @@ ] } } + }, + "rest": { + "libraryClient": "DataprocMetastoreFederationClient", + "rpcs": { + "CreateFederation": { + "methods": [ + "CreateFederation" + ] + }, + "DeleteFederation": { + "methods": [ + "DeleteFederation" + ] + }, + "DeleteOperation": { + "methods": [ + "DeleteOperation" + ] + }, + "GetFederation": { + "methods": [ + "GetFederation" + ] + }, + "GetIamPolicy": { + "methods": [ + "GetIamPolicy" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ListFederations": { + "methods": [ + "ListFederations" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "SetIamPolicy": { + "methods": [ + "SetIamPolicy" + ] + }, + "TestIamPermissions": { + "methods": [ + "TestIamPermissions" + ] + }, + "UpdateFederation": { + "methods": [ + "UpdateFederation" + ] + } + } } } } diff --git a/metastore/apiv1/metastorepb/metastore.pb.go b/metastore/apiv1/metastorepb/metastore.pb.go index 19fe1897839d..c7b69f46a22f 100644 --- a/metastore/apiv1/metastorepb/metastore.pb.go +++ b/metastore/apiv1/metastorepb/metastore.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/metastore/v1/metastore.proto package metastorepb @@ -753,7 +753,6 @@ type Service struct { // technology (the software that serves metastore queries). // // Types that are assignable to MetastoreConfig: - // // *Service_HiveMetastoreConfig MetastoreConfig isService_MetastoreConfig `protobuf_oneof:"metastore_config"` // Immutable. The relative resource name of the metastore service, in the following @@ -1058,7 +1057,7 @@ func (x *MaintenanceWindow) GetDayOfWeek() dayofweek.DayOfWeek { if x != nil { return x.DayOfWeek } - return dayofweek.DayOfWeek_DAY_OF_WEEK_UNSPECIFIED + return dayofweek.DayOfWeek(0) } // Specifies configuration information specific to running Hive metastore @@ -1216,7 +1215,6 @@ type Secret struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Value: - // // *Secret_CloudSecret Value isSecret_Value `protobuf_oneof:"value"` } @@ -1499,7 +1497,6 @@ type MetadataImport struct { // The metadata to be imported. // // Types that are assignable to Metadata: - // // *MetadataImport_DatabaseDump_ Metadata isMetadataImport_Metadata `protobuf_oneof:"metadata"` // Immutable. The relative resource name of the metadata import, of the form: @@ -1624,7 +1621,6 @@ type MetadataExport struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Destination: - // // *MetadataExport_DestinationGcsUri Destination isMetadataExport_Destination `protobuf_oneof:"destination"` // Output only. The time when the export started. @@ -3197,7 +3193,6 @@ type ExportMetadataRequest struct { // Required. Destination that metadata is exported to. // // Types that are assignable to Destination: - // // *ExportMetadataRequest_DestinationGcsFolder Destination isExportMetadataRequest_Destination `protobuf_oneof:"destination"` // Required. The relative resource name of the metastore service to run export, in the @@ -3598,7 +3593,6 @@ type NetworkConfig_Consumer struct { unknownFields protoimpl.UnknownFields // Types that are assignable to VpcResource: - // // *NetworkConfig_Consumer_Subnetwork VpcResource isNetworkConfig_Consumer_VpcResource `protobuf_oneof:"vpc_resource"` // Output only. The URI of the endpoint used to access the metastore service. diff --git a/metastore/apiv1/metastorepb/metastore_federation.pb.go b/metastore/apiv1/metastorepb/metastore_federation.pb.go index 3b40bc7068df..fda0f86ca486 100644 --- a/metastore/apiv1/metastorepb/metastore_federation.pb.go +++ b/metastore/apiv1/metastorepb/metastore_federation.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/metastore/v1/metastore_federation.proto package metastorepb @@ -309,13 +309,11 @@ type BackendMetastore struct { // metastores are listed below: // // * Dataplex - // - `projects/{project_id}/locations/{location}/lakes/{lake_id}` - // + // * `projects/{project_id}/locations/{location}/lakes/{lake_id}` // * BigQuery - // - `projects/{project_id}` - // + // * `projects/{project_id}` // * Dataproc Metastore - // - `projects/{project_id}/locations/{location}/services/{service_id}` + // * `projects/{project_id}/locations/{location}/services/{service_id}` Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // The type of the backend metastore. MetastoreType BackendMetastore_MetastoreType `protobuf:"varint,2,opt,name=metastore_type,json=metastoreType,proto3,enum=google.cloud.metastore.v1.BackendMetastore_MetastoreType" json:"metastore_type,omitempty"` diff --git a/metastore/apiv1alpha/dataproc_metastore_client.go b/metastore/apiv1alpha/dataproc_metastore_client.go index f98252cea719..35e0feb4db59 100644 --- a/metastore/apiv1alpha/dataproc_metastore_client.go +++ b/metastore/apiv1alpha/dataproc_metastore_client.go @@ -1390,6 +1390,7 @@ func (c *dataprocMetastoreRESTClient) ListServices(ctx context.Context, req *met baseUrl.Path += fmt.Sprintf("/v1alpha/%v/services", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1469,6 +1470,11 @@ func (c *dataprocMetastoreRESTClient) GetService(ctx context.Context, req *metas } baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1530,6 +1536,7 @@ func (c *dataprocMetastoreRESTClient) CreateService(ctx context.Context, req *me baseUrl.Path += fmt.Sprintf("/v1alpha/%v/services", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetRequestId() != "" { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -1602,6 +1609,7 @@ func (c *dataprocMetastoreRESTClient) UpdateService(ctx context.Context, req *me baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetService().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetRequestId() != "" { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -1673,6 +1681,7 @@ func (c *dataprocMetastoreRESTClient) DeleteService(ctx context.Context, req *me baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetRequestId() != "" { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -1750,6 +1759,7 @@ func (c *dataprocMetastoreRESTClient) ListMetadataImports(ctx context.Context, r baseUrl.Path += fmt.Sprintf("/v1alpha/%v/metadataImports", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1829,6 +1839,11 @@ func (c *dataprocMetastoreRESTClient) GetMetadataImport(ctx context.Context, req } baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1890,6 +1905,7 @@ func (c *dataprocMetastoreRESTClient) CreateMetadataImport(ctx context.Context, baseUrl.Path += fmt.Sprintf("/v1alpha/%v/metadataImports", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("metadataImportId", fmt.Sprintf("%v", req.GetMetadataImportId())) if req.GetRequestId() != "" { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) @@ -1963,6 +1979,7 @@ func (c *dataprocMetastoreRESTClient) UpdateMetadataImport(ctx context.Context, baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetMetadataImport().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetRequestId() != "" { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -2039,6 +2056,11 @@ func (c *dataprocMetastoreRESTClient) ExportMetadata(ctx context.Context, req *m } baseUrl.Path += fmt.Sprintf("/v1alpha/%v:exportMetadata", req.GetService()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "service", url.QueryEscape(req.GetService()))) @@ -2102,6 +2124,11 @@ func (c *dataprocMetastoreRESTClient) RestoreService(ctx context.Context, req *m } baseUrl.Path += fmt.Sprintf("/v1alpha/%v:restore", req.GetService()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "service", url.QueryEscape(req.GetService()))) @@ -2173,6 +2200,7 @@ func (c *dataprocMetastoreRESTClient) ListBackups(ctx context.Context, req *meta baseUrl.Path += fmt.Sprintf("/v1alpha/%v/backups", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -2252,6 +2280,11 @@ func (c *dataprocMetastoreRESTClient) GetBackup(ctx context.Context, req *metast } baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2313,6 +2346,7 @@ func (c *dataprocMetastoreRESTClient) CreateBackup(ctx context.Context, req *met baseUrl.Path += fmt.Sprintf("/v1alpha/%v/backups", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("backupId", fmt.Sprintf("%v", req.GetBackupId())) if req.GetRequestId() != "" { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) @@ -2378,6 +2412,7 @@ func (c *dataprocMetastoreRESTClient) DeleteBackup(ctx context.Context, req *met baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetRequestId() != "" { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -2441,6 +2476,11 @@ func (c *dataprocMetastoreRESTClient) GetLocation(ctx context.Context, req *loca } baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2508,6 +2548,7 @@ func (c *dataprocMetastoreRESTClient) ListLocations(ctx context.Context, req *lo baseUrl.Path += fmt.Sprintf("/v1alpha/%v/locations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -2586,6 +2627,7 @@ func (c *dataprocMetastoreRESTClient) GetIamPolicy(ctx context.Context, req *iam baseUrl.Path += fmt.Sprintf("/v1alpha/%v:getIamPolicy", req.GetResource()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetOptions().GetRequestedPolicyVersion() != 0 { params.Add("options.requestedPolicyVersion", fmt.Sprintf("%v", req.GetOptions().GetRequestedPolicyVersion())) } @@ -2655,6 +2697,11 @@ func (c *dataprocMetastoreRESTClient) SetIamPolicy(ctx context.Context, req *iam } baseUrl.Path += fmt.Sprintf("/v1alpha/%v:setIamPolicy", req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) @@ -2720,6 +2767,11 @@ func (c *dataprocMetastoreRESTClient) TestIamPermissions(ctx context.Context, re } baseUrl.Path += fmt.Sprintf("/v1alpha/%v:testIamPermissions", req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) @@ -2773,6 +2825,11 @@ func (c *dataprocMetastoreRESTClient) DeleteOperation(ctx context.Context, req * } baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2808,6 +2865,11 @@ func (c *dataprocMetastoreRESTClient) GetOperation(ctx context.Context, req *lon } baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2875,6 +2937,7 @@ func (c *dataprocMetastoreRESTClient) ListOperations(ctx context.Context, req *l baseUrl.Path += fmt.Sprintf("/v1alpha/%v/operations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/metastore/apiv1alpha/dataproc_metastore_federation_client.go b/metastore/apiv1alpha/dataproc_metastore_federation_client.go index 144c7e286749..acfe1baa5b89 100644 --- a/metastore/apiv1alpha/dataproc_metastore_federation_client.go +++ b/metastore/apiv1alpha/dataproc_metastore_federation_client.go @@ -835,6 +835,7 @@ func (c *dataprocMetastoreFederationRESTClient) ListFederations(ctx context.Cont baseUrl.Path += fmt.Sprintf("/v1alpha/%v/federations", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -914,6 +915,11 @@ func (c *dataprocMetastoreFederationRESTClient) GetFederation(ctx context.Contex } baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -975,6 +981,7 @@ func (c *dataprocMetastoreFederationRESTClient) CreateFederation(ctx context.Con baseUrl.Path += fmt.Sprintf("/v1alpha/%v/federations", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("federationId", fmt.Sprintf("%v", req.GetFederationId())) if req.GetRequestId() != "" { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) @@ -1047,6 +1054,7 @@ func (c *dataprocMetastoreFederationRESTClient) UpdateFederation(ctx context.Con baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetFederation().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetRequestId() != "" { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -1118,6 +1126,7 @@ func (c *dataprocMetastoreFederationRESTClient) DeleteFederation(ctx context.Con baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetRequestId() != "" { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -1181,6 +1190,11 @@ func (c *dataprocMetastoreFederationRESTClient) GetLocation(ctx context.Context, } baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1248,6 +1262,7 @@ func (c *dataprocMetastoreFederationRESTClient) ListLocations(ctx context.Contex baseUrl.Path += fmt.Sprintf("/v1alpha/%v/locations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1326,6 +1341,7 @@ func (c *dataprocMetastoreFederationRESTClient) GetIamPolicy(ctx context.Context baseUrl.Path += fmt.Sprintf("/v1alpha/%v:getIamPolicy", req.GetResource()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetOptions().GetRequestedPolicyVersion() != 0 { params.Add("options.requestedPolicyVersion", fmt.Sprintf("%v", req.GetOptions().GetRequestedPolicyVersion())) } @@ -1395,6 +1411,11 @@ func (c *dataprocMetastoreFederationRESTClient) SetIamPolicy(ctx context.Context } baseUrl.Path += fmt.Sprintf("/v1alpha/%v:setIamPolicy", req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) @@ -1460,6 +1481,11 @@ func (c *dataprocMetastoreFederationRESTClient) TestIamPermissions(ctx context.C } baseUrl.Path += fmt.Sprintf("/v1alpha/%v:testIamPermissions", req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) @@ -1513,6 +1539,11 @@ func (c *dataprocMetastoreFederationRESTClient) DeleteOperation(ctx context.Cont } baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1548,6 +1579,11 @@ func (c *dataprocMetastoreFederationRESTClient) GetOperation(ctx context.Context } baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1615,6 +1651,7 @@ func (c *dataprocMetastoreFederationRESTClient) ListOperations(ctx context.Conte baseUrl.Path += fmt.Sprintf("/v1alpha/%v/operations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/metastore/apiv1alpha/metastorepb/metastore.pb.go b/metastore/apiv1alpha/metastorepb/metastore.pb.go index 905f17d62bb7..4bfd93f907fe 100644 --- a/metastore/apiv1alpha/metastorepb/metastore.pb.go +++ b/metastore/apiv1alpha/metastorepb/metastore.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/metastore/v1alpha/metastore.proto package metastorepb @@ -806,7 +806,6 @@ type Service struct { // technology (the software that serves metastore queries). // // Types that are assignable to MetastoreConfig: - // // *Service_HiveMetastoreConfig MetastoreConfig isService_MetastoreConfig `protobuf_oneof:"metastore_config"` // Immutable. The relative resource name of the metastore service, in the @@ -1334,7 +1333,7 @@ func (x *MaintenanceWindow) GetDayOfWeek() dayofweek.DayOfWeek { if x != nil { return x.DayOfWeek } - return dayofweek.DayOfWeek_DAY_OF_WEEK_UNSPECIFIED + return dayofweek.DayOfWeek(0) } // Specifies configuration information specific to running Hive metastore @@ -1518,7 +1517,6 @@ type Secret struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Value: - // // *Secret_CloudSecret Value isSecret_Value `protobuf_oneof:"value"` } @@ -1874,7 +1872,6 @@ type MetadataImport struct { // The metadata to be imported. // // Types that are assignable to Metadata: - // // *MetadataImport_DatabaseDump_ Metadata isMetadataImport_Metadata `protobuf_oneof:"metadata"` // Immutable. The relative resource name of the metadata import, of the form: @@ -1999,7 +1996,6 @@ type MetadataExport struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Destination: - // // *MetadataExport_DestinationGcsUri Destination isMetadataExport_Destination `protobuf_oneof:"destination"` // Output only. The time when the export started. @@ -3594,7 +3590,6 @@ type ExportMetadataRequest struct { // Required. Destination that metadata is exported to. // // Types that are assignable to Destination: - // // *ExportMetadataRequest_DestinationGcsFolder Destination isExportMetadataRequest_Destination `protobuf_oneof:"destination"` // Required. The relative resource name of the metastore service to run @@ -3997,7 +3992,6 @@ type NetworkConfig_Consumer struct { unknownFields protoimpl.UnknownFields // Types that are assignable to VpcResource: - // // *NetworkConfig_Consumer_Subnetwork VpcResource isNetworkConfig_Consumer_VpcResource `protobuf_oneof:"vpc_resource"` // Output only. The URI of the endpoint used to access the metastore diff --git a/metastore/apiv1alpha/metastorepb/metastore_federation.pb.go b/metastore/apiv1alpha/metastorepb/metastore_federation.pb.go index e7c3b3b20431..e795f7c6d2f7 100644 --- a/metastore/apiv1alpha/metastorepb/metastore_federation.pb.go +++ b/metastore/apiv1alpha/metastorepb/metastore_federation.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/metastore/v1alpha/metastore_federation.proto package metastorepb @@ -313,13 +313,11 @@ type BackendMetastore struct { // metastores are listed below: // // * Dataplex - // - `projects/{project_id}/locations/{location}/lakes/{lake_id}` - // + // * `projects/{project_id}/locations/{location}/lakes/{lake_id}` // * BigQuery - // - `projects/{project_id}` - // + // * `projects/{project_id}` // * Dataproc Metastore - // - `projects/{project_id}/locations/{location}/services/{service_id}` + // * `projects/{project_id}/locations/{location}/services/{service_id}` Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // The type of the backend metastore. MetastoreType BackendMetastore_MetastoreType `protobuf:"varint,2,opt,name=metastore_type,json=metastoreType,proto3,enum=google.cloud.metastore.v1alpha.BackendMetastore_MetastoreType" json:"metastore_type,omitempty"` diff --git a/metastore/apiv1beta/dataproc_metastore_client.go b/metastore/apiv1beta/dataproc_metastore_client.go index 5f9937afb45d..317773c3fb76 100644 --- a/metastore/apiv1beta/dataproc_metastore_client.go +++ b/metastore/apiv1beta/dataproc_metastore_client.go @@ -1390,6 +1390,7 @@ func (c *dataprocMetastoreRESTClient) ListServices(ctx context.Context, req *met baseUrl.Path += fmt.Sprintf("/v1beta/%v/services", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1469,6 +1470,11 @@ func (c *dataprocMetastoreRESTClient) GetService(ctx context.Context, req *metas } baseUrl.Path += fmt.Sprintf("/v1beta/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1530,6 +1536,7 @@ func (c *dataprocMetastoreRESTClient) CreateService(ctx context.Context, req *me baseUrl.Path += fmt.Sprintf("/v1beta/%v/services", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetRequestId() != "" { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -1602,6 +1609,7 @@ func (c *dataprocMetastoreRESTClient) UpdateService(ctx context.Context, req *me baseUrl.Path += fmt.Sprintf("/v1beta/%v", req.GetService().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetRequestId() != "" { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -1673,6 +1681,7 @@ func (c *dataprocMetastoreRESTClient) DeleteService(ctx context.Context, req *me baseUrl.Path += fmt.Sprintf("/v1beta/%v", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetRequestId() != "" { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -1750,6 +1759,7 @@ func (c *dataprocMetastoreRESTClient) ListMetadataImports(ctx context.Context, r baseUrl.Path += fmt.Sprintf("/v1beta/%v/metadataImports", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1829,6 +1839,11 @@ func (c *dataprocMetastoreRESTClient) GetMetadataImport(ctx context.Context, req } baseUrl.Path += fmt.Sprintf("/v1beta/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1890,6 +1905,7 @@ func (c *dataprocMetastoreRESTClient) CreateMetadataImport(ctx context.Context, baseUrl.Path += fmt.Sprintf("/v1beta/%v/metadataImports", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("metadataImportId", fmt.Sprintf("%v", req.GetMetadataImportId())) if req.GetRequestId() != "" { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) @@ -1963,6 +1979,7 @@ func (c *dataprocMetastoreRESTClient) UpdateMetadataImport(ctx context.Context, baseUrl.Path += fmt.Sprintf("/v1beta/%v", req.GetMetadataImport().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetRequestId() != "" { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -2039,6 +2056,11 @@ func (c *dataprocMetastoreRESTClient) ExportMetadata(ctx context.Context, req *m } baseUrl.Path += fmt.Sprintf("/v1beta/%v:exportMetadata", req.GetService()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "service", url.QueryEscape(req.GetService()))) @@ -2102,6 +2124,11 @@ func (c *dataprocMetastoreRESTClient) RestoreService(ctx context.Context, req *m } baseUrl.Path += fmt.Sprintf("/v1beta/%v:restore", req.GetService()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "service", url.QueryEscape(req.GetService()))) @@ -2173,6 +2200,7 @@ func (c *dataprocMetastoreRESTClient) ListBackups(ctx context.Context, req *meta baseUrl.Path += fmt.Sprintf("/v1beta/%v/backups", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -2252,6 +2280,11 @@ func (c *dataprocMetastoreRESTClient) GetBackup(ctx context.Context, req *metast } baseUrl.Path += fmt.Sprintf("/v1beta/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2313,6 +2346,7 @@ func (c *dataprocMetastoreRESTClient) CreateBackup(ctx context.Context, req *met baseUrl.Path += fmt.Sprintf("/v1beta/%v/backups", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("backupId", fmt.Sprintf("%v", req.GetBackupId())) if req.GetRequestId() != "" { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) @@ -2378,6 +2412,7 @@ func (c *dataprocMetastoreRESTClient) DeleteBackup(ctx context.Context, req *met baseUrl.Path += fmt.Sprintf("/v1beta/%v", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetRequestId() != "" { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -2441,6 +2476,11 @@ func (c *dataprocMetastoreRESTClient) GetLocation(ctx context.Context, req *loca } baseUrl.Path += fmt.Sprintf("/v1beta/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2508,6 +2548,7 @@ func (c *dataprocMetastoreRESTClient) ListLocations(ctx context.Context, req *lo baseUrl.Path += fmt.Sprintf("/v1beta/%v/locations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -2586,6 +2627,7 @@ func (c *dataprocMetastoreRESTClient) GetIamPolicy(ctx context.Context, req *iam baseUrl.Path += fmt.Sprintf("/v1beta/%v:getIamPolicy", req.GetResource()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetOptions().GetRequestedPolicyVersion() != 0 { params.Add("options.requestedPolicyVersion", fmt.Sprintf("%v", req.GetOptions().GetRequestedPolicyVersion())) } @@ -2655,6 +2697,11 @@ func (c *dataprocMetastoreRESTClient) SetIamPolicy(ctx context.Context, req *iam } baseUrl.Path += fmt.Sprintf("/v1beta/%v:setIamPolicy", req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) @@ -2720,6 +2767,11 @@ func (c *dataprocMetastoreRESTClient) TestIamPermissions(ctx context.Context, re } baseUrl.Path += fmt.Sprintf("/v1beta/%v:testIamPermissions", req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) @@ -2773,6 +2825,11 @@ func (c *dataprocMetastoreRESTClient) DeleteOperation(ctx context.Context, req * } baseUrl.Path += fmt.Sprintf("/v1beta/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2808,6 +2865,11 @@ func (c *dataprocMetastoreRESTClient) GetOperation(ctx context.Context, req *lon } baseUrl.Path += fmt.Sprintf("/v1beta/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2875,6 +2937,7 @@ func (c *dataprocMetastoreRESTClient) ListOperations(ctx context.Context, req *l baseUrl.Path += fmt.Sprintf("/v1beta/%v/operations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/metastore/apiv1beta/dataproc_metastore_federation_client.go b/metastore/apiv1beta/dataproc_metastore_federation_client.go index fe42066774b7..7996fdedc995 100644 --- a/metastore/apiv1beta/dataproc_metastore_federation_client.go +++ b/metastore/apiv1beta/dataproc_metastore_federation_client.go @@ -835,6 +835,7 @@ func (c *dataprocMetastoreFederationRESTClient) ListFederations(ctx context.Cont baseUrl.Path += fmt.Sprintf("/v1beta/%v/federations", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -914,6 +915,11 @@ func (c *dataprocMetastoreFederationRESTClient) GetFederation(ctx context.Contex } baseUrl.Path += fmt.Sprintf("/v1beta/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -975,6 +981,7 @@ func (c *dataprocMetastoreFederationRESTClient) CreateFederation(ctx context.Con baseUrl.Path += fmt.Sprintf("/v1beta/%v/federations", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("federationId", fmt.Sprintf("%v", req.GetFederationId())) if req.GetRequestId() != "" { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) @@ -1047,6 +1054,7 @@ func (c *dataprocMetastoreFederationRESTClient) UpdateFederation(ctx context.Con baseUrl.Path += fmt.Sprintf("/v1beta/%v", req.GetFederation().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetRequestId() != "" { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -1118,6 +1126,7 @@ func (c *dataprocMetastoreFederationRESTClient) DeleteFederation(ctx context.Con baseUrl.Path += fmt.Sprintf("/v1beta/%v", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetRequestId() != "" { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -1181,6 +1190,11 @@ func (c *dataprocMetastoreFederationRESTClient) GetLocation(ctx context.Context, } baseUrl.Path += fmt.Sprintf("/v1beta/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1248,6 +1262,7 @@ func (c *dataprocMetastoreFederationRESTClient) ListLocations(ctx context.Contex baseUrl.Path += fmt.Sprintf("/v1beta/%v/locations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1326,6 +1341,7 @@ func (c *dataprocMetastoreFederationRESTClient) GetIamPolicy(ctx context.Context baseUrl.Path += fmt.Sprintf("/v1beta/%v:getIamPolicy", req.GetResource()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetOptions().GetRequestedPolicyVersion() != 0 { params.Add("options.requestedPolicyVersion", fmt.Sprintf("%v", req.GetOptions().GetRequestedPolicyVersion())) } @@ -1395,6 +1411,11 @@ func (c *dataprocMetastoreFederationRESTClient) SetIamPolicy(ctx context.Context } baseUrl.Path += fmt.Sprintf("/v1beta/%v:setIamPolicy", req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) @@ -1460,6 +1481,11 @@ func (c *dataprocMetastoreFederationRESTClient) TestIamPermissions(ctx context.C } baseUrl.Path += fmt.Sprintf("/v1beta/%v:testIamPermissions", req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) @@ -1513,6 +1539,11 @@ func (c *dataprocMetastoreFederationRESTClient) DeleteOperation(ctx context.Cont } baseUrl.Path += fmt.Sprintf("/v1beta/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1548,6 +1579,11 @@ func (c *dataprocMetastoreFederationRESTClient) GetOperation(ctx context.Context } baseUrl.Path += fmt.Sprintf("/v1beta/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1615,6 +1651,7 @@ func (c *dataprocMetastoreFederationRESTClient) ListOperations(ctx context.Conte baseUrl.Path += fmt.Sprintf("/v1beta/%v/operations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/metastore/apiv1beta/metastorepb/metastore.pb.go b/metastore/apiv1beta/metastorepb/metastore.pb.go index aebce2dfb6fc..34f798622502 100644 --- a/metastore/apiv1beta/metastorepb/metastore.pb.go +++ b/metastore/apiv1beta/metastorepb/metastore.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/metastore/v1beta/metastore.proto package metastorepb @@ -806,7 +806,6 @@ type Service struct { // technology (the software that serves metastore queries). // // Types that are assignable to MetastoreConfig: - // // *Service_HiveMetastoreConfig MetastoreConfig isService_MetastoreConfig `protobuf_oneof:"metastore_config"` // Immutable. The relative resource name of the metastore service, in the @@ -1334,7 +1333,7 @@ func (x *MaintenanceWindow) GetDayOfWeek() dayofweek.DayOfWeek { if x != nil { return x.DayOfWeek } - return dayofweek.DayOfWeek_DAY_OF_WEEK_UNSPECIFIED + return dayofweek.DayOfWeek(0) } // Specifies configuration information specific to running Hive metastore @@ -1518,7 +1517,6 @@ type Secret struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Value: - // // *Secret_CloudSecret Value isSecret_Value `protobuf_oneof:"value"` } @@ -1874,7 +1872,6 @@ type MetadataImport struct { // The metadata to be imported. // // Types that are assignable to Metadata: - // // *MetadataImport_DatabaseDump_ Metadata isMetadataImport_Metadata `protobuf_oneof:"metadata"` // Immutable. The relative resource name of the metadata import, of the form: @@ -1999,7 +1996,6 @@ type MetadataExport struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Destination: - // // *MetadataExport_DestinationGcsUri Destination isMetadataExport_Destination `protobuf_oneof:"destination"` // Output only. The time when the export started. @@ -3594,7 +3590,6 @@ type ExportMetadataRequest struct { // Required. Destination that metadata is exported to. // // Types that are assignable to Destination: - // // *ExportMetadataRequest_DestinationGcsFolder Destination isExportMetadataRequest_Destination `protobuf_oneof:"destination"` // Required. The relative resource name of the metastore service to run @@ -3997,7 +3992,6 @@ type NetworkConfig_Consumer struct { unknownFields protoimpl.UnknownFields // Types that are assignable to VpcResource: - // // *NetworkConfig_Consumer_Subnetwork VpcResource isNetworkConfig_Consumer_VpcResource `protobuf_oneof:"vpc_resource"` // Output only. The URI of the endpoint used to access the metastore @@ -4070,7 +4064,7 @@ type NetworkConfig_Consumer_Subnetwork struct { // be at least one IP address available in the subnet's primary range. The // subnet is specified in the following form: // - // `projects/{project_number}/regions/{region_id}/subnetworks/{subnetwork_id} + // `projects/{project_number}/regions/{region_id}/subnetworks/{subnetwork_id}` Subnetwork string `protobuf:"bytes,1,opt,name=subnetwork,proto3,oneof"` } diff --git a/metastore/apiv1beta/metastorepb/metastore_federation.pb.go b/metastore/apiv1beta/metastorepb/metastore_federation.pb.go index 56ca97662301..16dc54e4af8a 100644 --- a/metastore/apiv1beta/metastorepb/metastore_federation.pb.go +++ b/metastore/apiv1beta/metastorepb/metastore_federation.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/metastore/v1beta/metastore_federation.proto package metastorepb @@ -313,13 +313,11 @@ type BackendMetastore struct { // metastores are listed below: // // * Dataplex - // - `projects/{project_id}/locations/{location}/lakes/{lake_id}` - // + // * `projects/{project_id}/locations/{location}/lakes/{lake_id}` // * BigQuery - // - `projects/{project_id}` - // + // * `projects/{project_id}` // * Dataproc Metastore - // - `projects/{project_id}/locations/{location}/services/{service_id}` + // * `projects/{project_id}/locations/{location}/services/{service_id}` Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // The type of the backend metastore. MetastoreType BackendMetastore_MetastoreType `protobuf:"varint,2,opt,name=metastore_type,json=metastoreType,proto3,enum=google.cloud.metastore.v1beta.BackendMetastore_MetastoreType" json:"metastore_type,omitempty"` diff --git a/monitoring/apiv3/v2/alert_policy_client.go b/monitoring/apiv3/v2/alert_policy_client.go index 6c9ecc0b5388..49e0f752fbf4 100644 --- a/monitoring/apiv3/v2/alert_policy_client.go +++ b/monitoring/apiv3/v2/alert_policy_client.go @@ -17,21 +17,27 @@ package monitoring import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" monitoringpb "cloud.google.com/go/monitoring/apiv3/v2/monitoringpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -98,6 +104,43 @@ func defaultAlertPolicyCallOptions() *AlertPolicyCallOptions { } } +func defaultAlertPolicyRESTCallOptions() *AlertPolicyCallOptions { + return &AlertPolicyCallOptions{ + ListAlertPolicies: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 30000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetAlertPolicy: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 30000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateAlertPolicy: []gax.CallOption{}, + DeleteAlertPolicy: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 30000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UpdateAlertPolicy: []gax.CallOption{}, + } +} + // internalAlertPolicyClient is an interface that defines the methods available from Cloud Monitoring API. type internalAlertPolicyClient interface { Close() error @@ -270,6 +313,82 @@ func (c *alertPolicyGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type alertPolicyRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing AlertPolicyClient + CallOptions **AlertPolicyCallOptions +} + +// NewAlertPolicyRESTClient creates a new alert policy service rest client. +// +// The AlertPolicyService API is used to manage (list, create, delete, +// edit) alert policies in Cloud Monitoring. An alerting policy is +// a description of the conditions under which some aspect of your +// system is considered to be “unhealthy” and the ways to notify +// people or services about this state. In addition to using this API, alert +// policies can also be managed through +// Cloud Monitoring (at https://cloud.google.com/monitoring/docs/), +// which can be reached by clicking the “Monitoring” tab in +// Cloud console (at https://console.cloud.google.com/). +func NewAlertPolicyRESTClient(ctx context.Context, opts ...option.ClientOption) (*AlertPolicyClient, error) { + clientOpts := append(defaultAlertPolicyRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultAlertPolicyRESTCallOptions() + c := &alertPolicyRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &AlertPolicyClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultAlertPolicyRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://monitoring.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://monitoring.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://monitoring.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *alertPolicyRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *alertPolicyRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *alertPolicyRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *alertPolicyGRPCClient) ListAlertPolicies(ctx context.Context, req *monitoringpb.ListAlertPoliciesRequest, opts ...gax.CallOption) *AlertPolicyIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -399,6 +518,338 @@ func (c *alertPolicyGRPCClient) UpdateAlertPolicy(ctx context.Context, req *moni return resp, nil } +// ListAlertPolicies lists the existing alerting policies for the workspace. +func (c *alertPolicyRESTClient) ListAlertPolicies(ctx context.Context, req *monitoringpb.ListAlertPoliciesRequest, opts ...gax.CallOption) *AlertPolicyIterator { + it := &AlertPolicyIterator{} + req = proto.Clone(req).(*monitoringpb.ListAlertPoliciesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*monitoringpb.AlertPolicy, string, error) { + resp := &monitoringpb.ListAlertPoliciesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/alertPolicies", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetAlertPolicies(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetAlertPolicy gets a single alerting policy. +func (c *alertPolicyRESTClient) GetAlertPolicy(ctx context.Context, req *monitoringpb.GetAlertPolicyRequest, opts ...gax.CallOption) (*monitoringpb.AlertPolicy, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetAlertPolicy[0:len((*c.CallOptions).GetAlertPolicy):len((*c.CallOptions).GetAlertPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &monitoringpb.AlertPolicy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateAlertPolicy creates a new alerting policy. +func (c *alertPolicyRESTClient) CreateAlertPolicy(ctx context.Context, req *monitoringpb.CreateAlertPolicyRequest, opts ...gax.CallOption) (*monitoringpb.AlertPolicy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetAlertPolicy() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/alertPolicies", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateAlertPolicy[0:len((*c.CallOptions).CreateAlertPolicy):len((*c.CallOptions).CreateAlertPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &monitoringpb.AlertPolicy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteAlertPolicy deletes an alerting policy. +func (c *alertPolicyRESTClient) DeleteAlertPolicy(ctx context.Context, req *monitoringpb.DeleteAlertPolicyRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// UpdateAlertPolicy updates an alerting policy. You can either replace the entire policy with +// a new one or replace only certain fields in the current alerting policy by +// specifying the fields to be updated via updateMask. Returns the +// updated alerting policy. +func (c *alertPolicyRESTClient) UpdateAlertPolicy(ctx context.Context, req *monitoringpb.UpdateAlertPolicyRequest, opts ...gax.CallOption) (*monitoringpb.AlertPolicy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetAlertPolicy() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetAlertPolicy().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "alert_policy.name", url.QueryEscape(req.GetAlertPolicy().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateAlertPolicy[0:len((*c.CallOptions).UpdateAlertPolicy):len((*c.CallOptions).UpdateAlertPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &monitoringpb.AlertPolicy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + // AlertPolicyIterator manages a stream of *monitoringpb.AlertPolicy. type AlertPolicyIterator struct { items []*monitoringpb.AlertPolicy diff --git a/monitoring/apiv3/v2/alert_policy_client_example_test.go b/monitoring/apiv3/v2/alert_policy_client_example_test.go index f24386303e59..20613d3689ae 100644 --- a/monitoring/apiv3/v2/alert_policy_client_example_test.go +++ b/monitoring/apiv3/v2/alert_policy_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewAlertPolicyClient() { _ = c } +func ExampleNewAlertPolicyRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := monitoring.NewAlertPolicyRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleAlertPolicyClient_ListAlertPolicies() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/monitoring/apiv3/v2/doc.go b/monitoring/apiv3/v2/doc.go index f94ea8053c88..d46fbbb5a680 100644 --- a/monitoring/apiv3/v2/doc.go +++ b/monitoring/apiv3/v2/doc.go @@ -86,6 +86,8 @@ package monitoring // import "cloud.google.com/go/monitoring/apiv3/v2" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -177,3 +179,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/monitoring/apiv3/v2/gapic_metadata.json b/monitoring/apiv3/v2/gapic_metadata.json index ad03f6ffbcf3..3615d01f56c7 100644 --- a/monitoring/apiv3/v2/gapic_metadata.json +++ b/monitoring/apiv3/v2/gapic_metadata.json @@ -36,6 +36,36 @@ ] } } + }, + "rest": { + "libraryClient": "AlertPolicyClient", + "rpcs": { + "CreateAlertPolicy": { + "methods": [ + "CreateAlertPolicy" + ] + }, + "DeleteAlertPolicy": { + "methods": [ + "DeleteAlertPolicy" + ] + }, + "GetAlertPolicy": { + "methods": [ + "GetAlertPolicy" + ] + }, + "ListAlertPolicies": { + "methods": [ + "ListAlertPolicies" + ] + }, + "UpdateAlertPolicy": { + "methods": [ + "UpdateAlertPolicy" + ] + } + } } } }, @@ -75,6 +105,41 @@ ] } } + }, + "rest": { + "libraryClient": "GroupClient", + "rpcs": { + "CreateGroup": { + "methods": [ + "CreateGroup" + ] + }, + "DeleteGroup": { + "methods": [ + "DeleteGroup" + ] + }, + "GetGroup": { + "methods": [ + "GetGroup" + ] + }, + "ListGroupMembers": { + "methods": [ + "ListGroupMembers" + ] + }, + "ListGroups": { + "methods": [ + "ListGroups" + ] + }, + "UpdateGroup": { + "methods": [ + "UpdateGroup" + ] + } + } } } }, @@ -129,6 +194,56 @@ ] } } + }, + "rest": { + "libraryClient": "MetricClient", + "rpcs": { + "CreateMetricDescriptor": { + "methods": [ + "CreateMetricDescriptor" + ] + }, + "CreateServiceTimeSeries": { + "methods": [ + "CreateServiceTimeSeries" + ] + }, + "CreateTimeSeries": { + "methods": [ + "CreateTimeSeries" + ] + }, + "DeleteMetricDescriptor": { + "methods": [ + "DeleteMetricDescriptor" + ] + }, + "GetMetricDescriptor": { + "methods": [ + "GetMetricDescriptor" + ] + }, + "GetMonitoredResourceDescriptor": { + "methods": [ + "GetMonitoredResourceDescriptor" + ] + }, + "ListMetricDescriptors": { + "methods": [ + "ListMetricDescriptors" + ] + }, + "ListMonitoredResourceDescriptors": { + "methods": [ + "ListMonitoredResourceDescriptors" + ] + }, + "ListTimeSeries": { + "methods": [ + "ListTimeSeries" + ] + } + } } } }, @@ -188,6 +303,61 @@ ] } } + }, + "rest": { + "libraryClient": "NotificationChannelClient", + "rpcs": { + "CreateNotificationChannel": { + "methods": [ + "CreateNotificationChannel" + ] + }, + "DeleteNotificationChannel": { + "methods": [ + "DeleteNotificationChannel" + ] + }, + "GetNotificationChannel": { + "methods": [ + "GetNotificationChannel" + ] + }, + "GetNotificationChannelDescriptor": { + "methods": [ + "GetNotificationChannelDescriptor" + ] + }, + "GetNotificationChannelVerificationCode": { + "methods": [ + "GetNotificationChannelVerificationCode" + ] + }, + "ListNotificationChannelDescriptors": { + "methods": [ + "ListNotificationChannelDescriptors" + ] + }, + "ListNotificationChannels": { + "methods": [ + "ListNotificationChannels" + ] + }, + "SendNotificationChannelVerificationCode": { + "methods": [ + "SendNotificationChannelVerificationCode" + ] + }, + "UpdateNotificationChannel": { + "methods": [ + "UpdateNotificationChannel" + ] + }, + "VerifyNotificationChannel": { + "methods": [ + "VerifyNotificationChannel" + ] + } + } } } }, @@ -202,6 +372,16 @@ ] } } + }, + "rest": { + "libraryClient": "QueryClient", + "rpcs": { + "QueryTimeSeries": { + "methods": [ + "QueryTimeSeries" + ] + } + } } } }, @@ -261,6 +441,61 @@ ] } } + }, + "rest": { + "libraryClient": "ServiceMonitoringClient", + "rpcs": { + "CreateService": { + "methods": [ + "CreateService" + ] + }, + "CreateServiceLevelObjective": { + "methods": [ + "CreateServiceLevelObjective" + ] + }, + "DeleteService": { + "methods": [ + "DeleteService" + ] + }, + "DeleteServiceLevelObjective": { + "methods": [ + "DeleteServiceLevelObjective" + ] + }, + "GetService": { + "methods": [ + "GetService" + ] + }, + "GetServiceLevelObjective": { + "methods": [ + "GetServiceLevelObjective" + ] + }, + "ListServiceLevelObjectives": { + "methods": [ + "ListServiceLevelObjectives" + ] + }, + "ListServices": { + "methods": [ + "ListServices" + ] + }, + "UpdateService": { + "methods": [ + "UpdateService" + ] + }, + "UpdateServiceLevelObjective": { + "methods": [ + "UpdateServiceLevelObjective" + ] + } + } } } }, @@ -300,6 +535,41 @@ ] } } + }, + "rest": { + "libraryClient": "UptimeCheckClient", + "rpcs": { + "CreateUptimeCheckConfig": { + "methods": [ + "CreateUptimeCheckConfig" + ] + }, + "DeleteUptimeCheckConfig": { + "methods": [ + "DeleteUptimeCheckConfig" + ] + }, + "GetUptimeCheckConfig": { + "methods": [ + "GetUptimeCheckConfig" + ] + }, + "ListUptimeCheckConfigs": { + "methods": [ + "ListUptimeCheckConfigs" + ] + }, + "ListUptimeCheckIps": { + "methods": [ + "ListUptimeCheckIps" + ] + }, + "UpdateUptimeCheckConfig": { + "methods": [ + "UpdateUptimeCheckConfig" + ] + } + } } } } diff --git a/monitoring/apiv3/v2/group_client.go b/monitoring/apiv3/v2/group_client.go index 4375e1b467fb..d21ded3e125e 100644 --- a/monitoring/apiv3/v2/group_client.go +++ b/monitoring/apiv3/v2/group_client.go @@ -17,22 +17,28 @@ package monitoring import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" monitoringpb "cloud.google.com/go/monitoring/apiv3/v2/monitoringpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" monitoredrespb "google.golang.org/genproto/googleapis/api/monitoredres" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -121,6 +127,62 @@ func defaultGroupCallOptions() *GroupCallOptions { } } +func defaultGroupRESTCallOptions() *GroupCallOptions { + return &GroupCallOptions{ + ListGroups: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 30000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetGroup: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 30000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateGroup: []gax.CallOption{}, + UpdateGroup: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 30000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeleteGroup: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 30000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListGroupMembers: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 30000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + } +} + // internalGroupClient is an interface that defines the methods available from Cloud Monitoring API. type internalGroupClient interface { Close() error @@ -303,6 +365,85 @@ func (c *groupGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type groupRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing GroupClient + CallOptions **GroupCallOptions +} + +// NewGroupRESTClient creates a new group service rest client. +// +// The Group API lets you inspect and manage your +// groups (at #google.monitoring.v3.Group). +// +// A group is a named filter that is used to identify +// a collection of monitored resources. Groups are typically used to +// mirror the physical and/or logical topology of the environment. +// Because group membership is computed dynamically, monitored +// resources that are started in the future are automatically placed +// in matching groups. By using a group to name monitored resources in, +// for example, an alert policy, the target of that alert policy is +// updated automatically as monitored resources are added and removed +// from the infrastructure. +func NewGroupRESTClient(ctx context.Context, opts ...option.ClientOption) (*GroupClient, error) { + clientOpts := append(defaultGroupRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultGroupRESTCallOptions() + c := &groupRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &GroupClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultGroupRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://monitoring.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://monitoring.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://monitoring.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *groupRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *groupRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *groupRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *groupGRPCClient) ListGroups(ctx context.Context, req *monitoringpb.ListGroupsRequest, opts ...gax.CallOption) *GroupIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -477,6 +618,446 @@ func (c *groupGRPCClient) ListGroupMembers(ctx context.Context, req *monitoringp return it } +// ListGroups lists the existing groups. +func (c *groupRESTClient) ListGroups(ctx context.Context, req *monitoringpb.ListGroupsRequest, opts ...gax.CallOption) *GroupIterator { + it := &GroupIterator{} + req = proto.Clone(req).(*monitoringpb.ListGroupsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*monitoringpb.Group, string, error) { + resp := &monitoringpb.ListGroupsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/groups", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetAncestorsOfGroup() != "" { + params.Add("ancestorsOfGroup", fmt.Sprintf("%v", req.GetAncestorsOfGroup())) + } + if req.GetChildrenOfGroup() != "" { + params.Add("childrenOfGroup", fmt.Sprintf("%v", req.GetChildrenOfGroup())) + } + if req.GetDescendantsOfGroup() != "" { + params.Add("descendantsOfGroup", fmt.Sprintf("%v", req.GetDescendantsOfGroup())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetGroup(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetGroup gets a single group. +func (c *groupRESTClient) GetGroup(ctx context.Context, req *monitoringpb.GetGroupRequest, opts ...gax.CallOption) (*monitoringpb.Group, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetGroup[0:len((*c.CallOptions).GetGroup):len((*c.CallOptions).GetGroup)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &monitoringpb.Group{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateGroup creates a new group. +func (c *groupRESTClient) CreateGroup(ctx context.Context, req *monitoringpb.CreateGroupRequest, opts ...gax.CallOption) (*monitoringpb.Group, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetGroup() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/groups", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateGroup[0:len((*c.CallOptions).CreateGroup):len((*c.CallOptions).CreateGroup)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &monitoringpb.Group{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateGroup updates an existing group. +// You can change any group attributes except name. +func (c *groupRESTClient) UpdateGroup(ctx context.Context, req *monitoringpb.UpdateGroupRequest, opts ...gax.CallOption) (*monitoringpb.Group, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetGroup() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetGroup().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "group.name", url.QueryEscape(req.GetGroup().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateGroup[0:len((*c.CallOptions).UpdateGroup):len((*c.CallOptions).UpdateGroup)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &monitoringpb.Group{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PUT", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteGroup deletes an existing group. +func (c *groupRESTClient) DeleteGroup(ctx context.Context, req *monitoringpb.DeleteGroupRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRecursive() { + params.Add("recursive", fmt.Sprintf("%v", req.GetRecursive())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// ListGroupMembers lists the monitored resources that are members of a group. +func (c *groupRESTClient) ListGroupMembers(ctx context.Context, req *monitoringpb.ListGroupMembersRequest, opts ...gax.CallOption) *MonitoredResourceIterator { + it := &MonitoredResourceIterator{} + req = proto.Clone(req).(*monitoringpb.ListGroupMembersRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*monitoredrespb.MonitoredResource, string, error) { + resp := &monitoringpb.ListGroupMembersResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/members", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetInterval().GetEndTime() != nil { + endTime, err := protojson.Marshal(req.GetInterval().GetEndTime()) + if err != nil { + return nil, "", err + } + params.Add("interval.endTime", string(endTime)) + } + if req.GetInterval().GetStartTime() != nil { + startTime, err := protojson.Marshal(req.GetInterval().GetStartTime()) + if err != nil { + return nil, "", err + } + params.Add("interval.startTime", string(startTime)) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetMembers(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + // GroupIterator manages a stream of *monitoringpb.Group. type GroupIterator struct { items []*monitoringpb.Group diff --git a/monitoring/apiv3/v2/group_client_example_test.go b/monitoring/apiv3/v2/group_client_example_test.go index b4b7e802e941..a1fd7e0f82f8 100644 --- a/monitoring/apiv3/v2/group_client_example_test.go +++ b/monitoring/apiv3/v2/group_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewGroupClient() { _ = c } +func ExampleNewGroupRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := monitoring.NewGroupRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleGroupClient_ListGroups() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/monitoring/apiv3/v2/metric_client.go b/monitoring/apiv3/v2/metric_client.go index 872d6d3743c6..6caf7952afb5 100644 --- a/monitoring/apiv3/v2/metric_client.go +++ b/monitoring/apiv3/v2/metric_client.go @@ -17,23 +17,29 @@ package monitoring import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" monitoringpb "cloud.google.com/go/monitoring/apiv3/v2/monitoringpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" metricpb "google.golang.org/genproto/googleapis/api/metric" monitoredrespb "google.golang.org/genproto/googleapis/api/monitoredres" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -138,6 +144,74 @@ func defaultMetricCallOptions() *MetricCallOptions { } } +func defaultMetricRESTCallOptions() *MetricCallOptions { + return &MetricCallOptions{ + ListMonitoredResourceDescriptors: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 30000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetMonitoredResourceDescriptor: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 30000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListMetricDescriptors: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 30000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetMetricDescriptor: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 30000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateMetricDescriptor: []gax.CallOption{}, + DeleteMetricDescriptor: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 30000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListTimeSeries: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 30000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateTimeSeries: []gax.CallOption{}, + CreateServiceTimeSeries: []gax.CallOption{}, + } +} + // internalMetricClient is an interface that defines the methods available from Cloud Monitoring API. type internalMetricClient interface { Close() error @@ -334,6 +408,75 @@ func (c *metricGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type metricRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing MetricClient + CallOptions **MetricCallOptions +} + +// NewMetricRESTClient creates a new metric service rest client. +// +// Manages metric descriptors, monitored resource descriptors, and +// time series data. +func NewMetricRESTClient(ctx context.Context, opts ...option.ClientOption) (*MetricClient, error) { + clientOpts := append(defaultMetricRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultMetricRESTCallOptions() + c := &metricRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &MetricClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultMetricRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://monitoring.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://monitoring.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://monitoring.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *metricRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *metricRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *metricRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *metricGRPCClient) ListMonitoredResourceDescriptors(ctx context.Context, req *monitoringpb.ListMonitoredResourceDescriptorsRequest, opts ...gax.CallOption) *MonitoredResourceDescriptorIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -584,6 +727,661 @@ func (c *metricGRPCClient) CreateServiceTimeSeries(ctx context.Context, req *mon return err } +// ListMonitoredResourceDescriptors lists monitored resource descriptors that match a filter. This method does not require a Workspace. +func (c *metricRESTClient) ListMonitoredResourceDescriptors(ctx context.Context, req *monitoringpb.ListMonitoredResourceDescriptorsRequest, opts ...gax.CallOption) *MonitoredResourceDescriptorIterator { + it := &MonitoredResourceDescriptorIterator{} + req = proto.Clone(req).(*monitoringpb.ListMonitoredResourceDescriptorsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*monitoredrespb.MonitoredResourceDescriptor, string, error) { + resp := &monitoringpb.ListMonitoredResourceDescriptorsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/monitoredResourceDescriptors", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetResourceDescriptors(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetMonitoredResourceDescriptor gets a single monitored resource descriptor. This method does not require a Workspace. +func (c *metricRESTClient) GetMonitoredResourceDescriptor(ctx context.Context, req *monitoringpb.GetMonitoredResourceDescriptorRequest, opts ...gax.CallOption) (*monitoredrespb.MonitoredResourceDescriptor, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetMonitoredResourceDescriptor[0:len((*c.CallOptions).GetMonitoredResourceDescriptor):len((*c.CallOptions).GetMonitoredResourceDescriptor)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &monitoredrespb.MonitoredResourceDescriptor{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListMetricDescriptors lists metric descriptors that match a filter. This method does not require a Workspace. +func (c *metricRESTClient) ListMetricDescriptors(ctx context.Context, req *monitoringpb.ListMetricDescriptorsRequest, opts ...gax.CallOption) *MetricDescriptorIterator { + it := &MetricDescriptorIterator{} + req = proto.Clone(req).(*monitoringpb.ListMetricDescriptorsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*metricpb.MetricDescriptor, string, error) { + resp := &monitoringpb.ListMetricDescriptorsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/metricDescriptors", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetMetricDescriptors(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetMetricDescriptor gets a single metric descriptor. This method does not require a Workspace. +func (c *metricRESTClient) GetMetricDescriptor(ctx context.Context, req *monitoringpb.GetMetricDescriptorRequest, opts ...gax.CallOption) (*metricpb.MetricDescriptor, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetMetricDescriptor[0:len((*c.CallOptions).GetMetricDescriptor):len((*c.CallOptions).GetMetricDescriptor)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &metricpb.MetricDescriptor{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateMetricDescriptor creates a new metric descriptor. +// The creation is executed asynchronously and callers may check the returned +// operation to track its progress. +// User-created metric descriptors define +// custom metrics (at https://cloud.google.com/monitoring/custom-metrics). +func (c *metricRESTClient) CreateMetricDescriptor(ctx context.Context, req *monitoringpb.CreateMetricDescriptorRequest, opts ...gax.CallOption) (*metricpb.MetricDescriptor, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetMetricDescriptor() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/metricDescriptors", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateMetricDescriptor[0:len((*c.CallOptions).CreateMetricDescriptor):len((*c.CallOptions).CreateMetricDescriptor)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &metricpb.MetricDescriptor{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteMetricDescriptor deletes a metric descriptor. Only user-created +// custom metrics (at https://cloud.google.com/monitoring/custom-metrics) can be +// deleted. +func (c *metricRESTClient) DeleteMetricDescriptor(ctx context.Context, req *monitoringpb.DeleteMetricDescriptorRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// ListTimeSeries lists time series that match a filter. This method does not require a Workspace. +func (c *metricRESTClient) ListTimeSeries(ctx context.Context, req *monitoringpb.ListTimeSeriesRequest, opts ...gax.CallOption) *TimeSeriesIterator { + it := &TimeSeriesIterator{} + req = proto.Clone(req).(*monitoringpb.ListTimeSeriesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*monitoringpb.TimeSeries, string, error) { + resp := &monitoringpb.ListTimeSeriesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/timeSeries", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetAggregation().GetAlignmentPeriod() != nil { + alignmentPeriod, err := protojson.Marshal(req.GetAggregation().GetAlignmentPeriod()) + if err != nil { + return nil, "", err + } + params.Add("aggregation.alignmentPeriod", string(alignmentPeriod)) + } + if req.GetAggregation().GetCrossSeriesReducer() != 0 { + params.Add("aggregation.crossSeriesReducer", fmt.Sprintf("%v", req.GetAggregation().GetCrossSeriesReducer())) + } + if items := req.GetAggregation().GetGroupByFields(); len(items) > 0 { + for _, item := range items { + params.Add("aggregation.groupByFields", fmt.Sprintf("%v", item)) + } + } + if req.GetAggregation().GetPerSeriesAligner() != 0 { + params.Add("aggregation.perSeriesAligner", fmt.Sprintf("%v", req.GetAggregation().GetPerSeriesAligner())) + } + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + if req.GetInterval().GetEndTime() != nil { + endTime, err := protojson.Marshal(req.GetInterval().GetEndTime()) + if err != nil { + return nil, "", err + } + params.Add("interval.endTime", string(endTime)) + } + if req.GetInterval().GetStartTime() != nil { + startTime, err := protojson.Marshal(req.GetInterval().GetStartTime()) + if err != nil { + return nil, "", err + } + params.Add("interval.startTime", string(startTime)) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + if req.GetSecondaryAggregation().GetAlignmentPeriod() != nil { + alignmentPeriod, err := protojson.Marshal(req.GetSecondaryAggregation().GetAlignmentPeriod()) + if err != nil { + return nil, "", err + } + params.Add("secondaryAggregation.alignmentPeriod", string(alignmentPeriod)) + } + if req.GetSecondaryAggregation().GetCrossSeriesReducer() != 0 { + params.Add("secondaryAggregation.crossSeriesReducer", fmt.Sprintf("%v", req.GetSecondaryAggregation().GetCrossSeriesReducer())) + } + if items := req.GetSecondaryAggregation().GetGroupByFields(); len(items) > 0 { + for _, item := range items { + params.Add("secondaryAggregation.groupByFields", fmt.Sprintf("%v", item)) + } + } + if req.GetSecondaryAggregation().GetPerSeriesAligner() != 0 { + params.Add("secondaryAggregation.perSeriesAligner", fmt.Sprintf("%v", req.GetSecondaryAggregation().GetPerSeriesAligner())) + } + params.Add("view", fmt.Sprintf("%v", req.GetView())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetTimeSeries(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CreateTimeSeries creates or adds data to one or more time series. +// The response is empty if all time series in the request were written. +// If any time series could not be written, a corresponding failure message is +// included in the error response. +func (c *metricRESTClient) CreateTimeSeries(ctx context.Context, req *monitoringpb.CreateTimeSeriesRequest, opts ...gax.CallOption) error { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/timeSeries", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// CreateServiceTimeSeries creates or adds data to one or more service time series. A service time +// series is a time series for a metric from a Google Cloud service. The +// response is empty if all time series in the request were written. If any +// time series could not be written, a corresponding failure message is +// included in the error response. This endpoint rejects writes to +// user-defined metrics. +// This method is only for use by Google Cloud services. Use +// projects.timeSeries.create +// instead. +func (c *metricRESTClient) CreateServiceTimeSeries(ctx context.Context, req *monitoringpb.CreateTimeSeriesRequest, opts ...gax.CallOption) error { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/timeSeries:createService", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + // MetricDescriptorIterator manages a stream of *metricpb.MetricDescriptor. type MetricDescriptorIterator struct { items []*metricpb.MetricDescriptor diff --git a/monitoring/apiv3/v2/metric_client_example_test.go b/monitoring/apiv3/v2/metric_client_example_test.go index b594bf92edea..4b34477a2288 100644 --- a/monitoring/apiv3/v2/metric_client_example_test.go +++ b/monitoring/apiv3/v2/metric_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewMetricClient() { _ = c } +func ExampleNewMetricRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := monitoring.NewMetricRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleMetricClient_ListMonitoredResourceDescriptors() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/monitoring/apiv3/v2/monitoringpb/alert.pb.go b/monitoring/apiv3/v2/monitoringpb/alert.pb.go index 1b823204f981..901250c912f3 100644 --- a/monitoring/apiv3/v2/monitoringpb/alert.pb.go +++ b/monitoring/apiv3/v2/monitoringpb/alert.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/monitoring/v3/alert.proto package monitoringpb @@ -176,7 +176,7 @@ type AlertPolicy struct { // Required if the policy exists. The resource name for this policy. The // format is: // - // projects/[PROJECT_ID_OR_NUMBER]/alertPolicies/[ALERT_POLICY_ID] + // projects/[PROJECT_ID_OR_NUMBER]/alertPolicies/[ALERT_POLICY_ID] // // `[ALERT_POLICY_ID]` is assigned by Cloud Monitoring when the policy // is created. When calling the @@ -233,7 +233,7 @@ type AlertPolicy struct { // [google.monitoring.v3.NotificationChannelService.ListNotificationChannels] // method. The format of the entries in this field is: // - // projects/[PROJECT_ID_OR_NUMBER]/notificationChannels/[CHANNEL_ID] + // projects/[PROJECT_ID_OR_NUMBER]/notificationChannels/[CHANNEL_ID] NotificationChannels []string `protobuf:"bytes,14,rep,name=notification_channels,json=notificationChannels,proto3" json:"notification_channels,omitempty"` // A read-only record of the creation of the alerting policy. If provided // in a call to create or update, this field will be ignored. @@ -437,7 +437,7 @@ type AlertPolicy_Condition struct { // Required if the condition exists. The unique resource name for this // condition. Its format is: // - // projects/[PROJECT_ID_OR_NUMBER]/alertPolicies/[POLICY_ID]/conditions/[CONDITION_ID] + // projects/[PROJECT_ID_OR_NUMBER]/alertPolicies/[POLICY_ID]/conditions/[CONDITION_ID] // // `[CONDITION_ID]` is assigned by Cloud Monitoring when the // condition is created as part of a new or updated alerting policy. @@ -467,7 +467,6 @@ type AlertPolicy_Condition struct { // Only one of the following condition types will be specified. // // Types that are assignable to Condition: - // // *AlertPolicy_Condition_ConditionThreshold // *AlertPolicy_Condition_ConditionAbsent // *AlertPolicy_Condition_ConditionMatchedLog @@ -663,7 +662,6 @@ type AlertPolicy_Condition_Trigger struct { // A type of trigger. // // Types that are assignable to Type: - // // *AlertPolicy_Condition_Trigger_Count // *AlertPolicy_Condition_Trigger_Percent Type isAlertPolicy_Condition_Trigger_Type `protobuf_oneof:"type"` diff --git a/monitoring/apiv3/v2/monitoringpb/alert_service.pb.go b/monitoring/apiv3/v2/monitoringpb/alert_service.pb.go index 93e481095c37..11710feea296 100644 --- a/monitoring/apiv3/v2/monitoringpb/alert_service.pb.go +++ b/monitoring/apiv3/v2/monitoringpb/alert_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/monitoring/v3/alert_service.proto package monitoringpb @@ -51,7 +51,7 @@ type CreateAlertPolicyRequest struct { // Required. The [project](https://cloud.google.com/monitoring/api/v3#project_name) in // which to create the alerting policy. The format is: // - // projects/[PROJECT_ID_OR_NUMBER] + // projects/[PROJECT_ID_OR_NUMBER] // // Note that this field names the parent container in which the alerting // policy will be written, not the name of the created policy. |name| must be @@ -121,7 +121,7 @@ type GetAlertPolicyRequest struct { // Required. The alerting policy to retrieve. The format is: // - // projects/[PROJECT_ID_OR_NUMBER]/alertPolicies/[ALERT_POLICY_ID] + // projects/[PROJECT_ID_OR_NUMBER]/alertPolicies/[ALERT_POLICY_ID] Name string `protobuf:"bytes,3,opt,name=name,proto3" json:"name,omitempty"` } @@ -173,7 +173,7 @@ type ListAlertPoliciesRequest struct { // Required. The [project](https://cloud.google.com/monitoring/api/v3#project_name) // whose alert policies are to be listed. The format is: // - // projects/[PROJECT_ID_OR_NUMBER] + // projects/[PROJECT_ID_OR_NUMBER] // // Note that this field names the parent container in which the alerting // policies to be listed are stored. To retrieve a single alerting policy @@ -359,10 +359,10 @@ type UpdateAlertPolicyRequest struct { // existing policy. It is the same as deleting the existing policy and // adding the supplied policy, except for the following: // - // - The new policy will have the same `[ALERT_POLICY_ID]` as the former + // + The new policy will have the same `[ALERT_POLICY_ID]` as the former // policy. This gives you continuity with the former policy in your // notifications and incidents. - // - Conditions in the new policy will keep their former `[CONDITION_ID]` if + // + Conditions in the new policy will keep their former `[CONDITION_ID]` if // the supplied condition includes the `name` field with that // `[CONDITION_ID]`. If the supplied condition omits the `name` field, // then a new `[CONDITION_ID]` is created. @@ -428,7 +428,7 @@ type DeleteAlertPolicyRequest struct { // Required. The alerting policy to delete. The format is: // - // projects/[PROJECT_ID_OR_NUMBER]/alertPolicies/[ALERT_POLICY_ID] + // projects/[PROJECT_ID_OR_NUMBER]/alertPolicies/[ALERT_POLICY_ID] // // For more information, see [AlertPolicy][google.monitoring.v3.AlertPolicy]. Name string `protobuf:"bytes,3,opt,name=name,proto3" json:"name,omitempty"` diff --git a/monitoring/apiv3/v2/monitoringpb/common.pb.go b/monitoring/apiv3/v2/monitoringpb/common.pb.go index 2ee80c11fa3e..a908751ae390 100644 --- a/monitoring/apiv3/v2/monitoringpb/common.pb.go +++ b/monitoring/apiv3/v2/monitoringpb/common.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/monitoring/v3/common.proto package monitoringpb @@ -547,7 +547,6 @@ type TypedValue struct { // The typed value field. // // Types that are assignable to Value: - // // *TypedValue_BoolValue // *TypedValue_Int64Value // *TypedValue_DoubleValue diff --git a/monitoring/apiv3/v2/monitoringpb/dropped_labels.pb.go b/monitoring/apiv3/v2/monitoringpb/dropped_labels.pb.go index 90ec564bdb6a..a6a14c7e306c 100644 --- a/monitoring/apiv3/v2/monitoringpb/dropped_labels.pb.go +++ b/monitoring/apiv3/v2/monitoringpb/dropped_labels.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/monitoring/v3/dropped_labels.proto package monitoringpb diff --git a/monitoring/apiv3/v2/monitoringpb/group.pb.go b/monitoring/apiv3/v2/monitoringpb/group.pb.go index fc38be341fe0..297043aeafd6 100644 --- a/monitoring/apiv3/v2/monitoringpb/group.pb.go +++ b/monitoring/apiv3/v2/monitoringpb/group.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/monitoring/v3/group.proto package monitoringpb @@ -69,7 +69,7 @@ type Group struct { // Output only. The name of this group. The format is: // - // projects/[PROJECT_ID_OR_NUMBER]/groups/[GROUP_ID] + // projects/[PROJECT_ID_OR_NUMBER]/groups/[GROUP_ID] // // When creating a group, this field is ignored and a new name is created // consisting of the project specified in the call to `CreateGroup` @@ -79,7 +79,7 @@ type Group struct { DisplayName string `protobuf:"bytes,2,opt,name=display_name,json=displayName,proto3" json:"display_name,omitempty"` // The name of the group's parent, if it has one. The format is: // - // projects/[PROJECT_ID_OR_NUMBER]/groups/[GROUP_ID] + // projects/[PROJECT_ID_OR_NUMBER]/groups/[GROUP_ID] // // For groups with no parent, `parent_name` is the empty string, `""`. ParentName string `protobuf:"bytes,3,opt,name=parent_name,json=parentName,proto3" json:"parent_name,omitempty"` diff --git a/monitoring/apiv3/v2/monitoringpb/group_service.pb.go b/monitoring/apiv3/v2/monitoringpb/group_service.pb.go index d7c61bd7a5f6..0ec42e67226b 100644 --- a/monitoring/apiv3/v2/monitoringpb/group_service.pb.go +++ b/monitoring/apiv3/v2/monitoringpb/group_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/monitoring/v3/group_service.proto package monitoringpb @@ -51,14 +51,13 @@ type ListGroupsRequest struct { // Required. The [project](https://cloud.google.com/monitoring/api/v3#project_name) // whose groups are to be listed. The format is: // - // projects/[PROJECT_ID_OR_NUMBER] + // projects/[PROJECT_ID_OR_NUMBER] Name string `protobuf:"bytes,7,opt,name=name,proto3" json:"name,omitempty"` // An optional filter consisting of a single group name. The filters limit // the groups returned based on their parent-child relationship with the // specified group. If no filter is specified, all groups are returned. // // Types that are assignable to Filter: - // // *ListGroupsRequest_ChildrenOfGroup // *ListGroupsRequest_AncestorsOfGroup // *ListGroupsRequest_DescendantsOfGroup @@ -159,7 +158,7 @@ type isListGroupsRequest_Filter interface { type ListGroupsRequest_ChildrenOfGroup struct { // A group name. The format is: // - // projects/[PROJECT_ID_OR_NUMBER]/groups/[GROUP_ID] + // projects/[PROJECT_ID_OR_NUMBER]/groups/[GROUP_ID] // // Returns groups whose `parent_name` field contains the group // name. If no groups have this parent, the results are empty. @@ -169,7 +168,7 @@ type ListGroupsRequest_ChildrenOfGroup struct { type ListGroupsRequest_AncestorsOfGroup struct { // A group name. The format is: // - // projects/[PROJECT_ID_OR_NUMBER]/groups/[GROUP_ID] + // projects/[PROJECT_ID_OR_NUMBER]/groups/[GROUP_ID] // // Returns groups that are ancestors of the specified group. // The groups are returned in order, starting with the immediate parent and @@ -181,7 +180,7 @@ type ListGroupsRequest_AncestorsOfGroup struct { type ListGroupsRequest_DescendantsOfGroup struct { // A group name. The format is: // - // projects/[PROJECT_ID_OR_NUMBER]/groups/[GROUP_ID] + // projects/[PROJECT_ID_OR_NUMBER]/groups/[GROUP_ID] // // Returns the descendants of the specified group. This is a superset of // the results returned by the `children_of_group` filter, and includes @@ -263,7 +262,7 @@ type GetGroupRequest struct { // Required. The group to retrieve. The format is: // - // projects/[PROJECT_ID_OR_NUMBER]/groups/[GROUP_ID] + // projects/[PROJECT_ID_OR_NUMBER]/groups/[GROUP_ID] Name string `protobuf:"bytes,3,opt,name=name,proto3" json:"name,omitempty"` } @@ -315,7 +314,7 @@ type CreateGroupRequest struct { // Required. The [project](https://cloud.google.com/monitoring/api/v3#project_name) in // which to create the group. The format is: // - // projects/[PROJECT_ID_OR_NUMBER] + // projects/[PROJECT_ID_OR_NUMBER] Name string `protobuf:"bytes,4,opt,name=name,proto3" json:"name,omitempty"` // Required. A group definition. It is an error to define the `name` field because // the system assigns the name. @@ -445,7 +444,7 @@ type DeleteGroupRequest struct { // Required. The group to delete. The format is: // - // projects/[PROJECT_ID_OR_NUMBER]/groups/[GROUP_ID] + // projects/[PROJECT_ID_OR_NUMBER]/groups/[GROUP_ID] Name string `protobuf:"bytes,3,opt,name=name,proto3" json:"name,omitempty"` // If this field is true, then the request means to delete a group with all // its descendants. Otherwise, the request means to delete a group only when @@ -507,7 +506,7 @@ type ListGroupMembersRequest struct { // Required. The group whose members are listed. The format is: // - // projects/[PROJECT_ID_OR_NUMBER]/groups/[GROUP_ID] + // projects/[PROJECT_ID_OR_NUMBER]/groups/[GROUP_ID] Name string `protobuf:"bytes,7,opt,name=name,proto3" json:"name,omitempty"` // A positive number that is the maximum number of results to return. PageSize int32 `protobuf:"varint,3,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"` @@ -522,7 +521,7 @@ type ListGroupMembersRequest struct { // example, to return only resources representing Compute Engine VM instances, // use this filter: // - // `resource.type = "gce_instance"` + // `resource.type = "gce_instance"` Filter string `protobuf:"bytes,5,opt,name=filter,proto3" json:"filter,omitempty"` // An optional time interval for which results should be returned. Only // members that were part of the group during the specified interval are diff --git a/monitoring/apiv3/v2/monitoringpb/metric.pb.go b/monitoring/apiv3/v2/monitoringpb/metric.pb.go index 217c35125639..1e37923dba4a 100644 --- a/monitoring/apiv3/v2/monitoringpb/metric.pb.go +++ b/monitoring/apiv3/v2/monitoringpb/metric.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/monitoring/v3/metric.proto package monitoringpb @@ -214,14 +214,14 @@ func (x *TimeSeries) GetMetricKind() metric.MetricDescriptor_MetricKind { if x != nil { return x.MetricKind } - return metric.MetricDescriptor_METRIC_KIND_UNSPECIFIED + return metric.MetricDescriptor_MetricKind(0) } func (x *TimeSeries) GetValueType() metric.MetricDescriptor_ValueType { if x != nil { return x.ValueType } - return metric.MetricDescriptor_VALUE_TYPE_UNSPECIFIED + return metric.MetricDescriptor_ValueType(0) } func (x *TimeSeries) GetPoints() []*Point { @@ -367,7 +367,6 @@ type LabelValue struct { // The label value can be a bool, int64, or string. // // Types that are assignable to Value: - // // *LabelValue_BoolValue // *LabelValue_Int64Value // *LabelValue_StringValue @@ -698,14 +697,14 @@ func (x *TimeSeriesDescriptor_ValueDescriptor) GetValueType() metric.MetricDescr if x != nil { return x.ValueType } - return metric.MetricDescriptor_VALUE_TYPE_UNSPECIFIED + return metric.MetricDescriptor_ValueType(0) } func (x *TimeSeriesDescriptor_ValueDescriptor) GetMetricKind() metric.MetricDescriptor_MetricKind { if x != nil { return x.MetricKind } - return metric.MetricDescriptor_METRIC_KIND_UNSPECIFIED + return metric.MetricDescriptor_MetricKind(0) } func (x *TimeSeriesDescriptor_ValueDescriptor) GetUnit() string { diff --git a/monitoring/apiv3/v2/monitoringpb/metric_service.pb.go b/monitoring/apiv3/v2/monitoringpb/metric_service.pb.go index abf7710514a2..f0bd9fb40b14 100644 --- a/monitoring/apiv3/v2/monitoringpb/metric_service.pb.go +++ b/monitoring/apiv3/v2/monitoringpb/metric_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/monitoring/v3/metric_service.proto package monitoringpb @@ -104,14 +104,14 @@ type ListMonitoredResourceDescriptorsRequest struct { // Required. The [project](https://cloud.google.com/monitoring/api/v3#project_name) on // which to execute the request. The format is: // - // projects/[PROJECT_ID_OR_NUMBER] + // projects/[PROJECT_ID_OR_NUMBER] Name string `protobuf:"bytes,5,opt,name=name,proto3" json:"name,omitempty"` // An optional [filter](https://cloud.google.com/monitoring/api/v3/filters) // describing the descriptors to be returned. The filter can reference the // descriptor's type and labels. For example, the following filter returns // only Google Compute Engine descriptors that have an `id` label: // - // resource.type = starts_with("gce_") AND resource.label:id + // resource.type = starts_with("gce_") AND resource.label:id Filter string `protobuf:"bytes,2,opt,name=filter,proto3" json:"filter,omitempty"` // A positive number that is the maximum number of results to return. PageSize int32 `protobuf:"varint,3,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"` @@ -250,7 +250,7 @@ type GetMonitoredResourceDescriptorRequest struct { // Required. The monitored resource descriptor to get. The format is: // - // projects/[PROJECT_ID_OR_NUMBER]/monitoredResourceDescriptors/[RESOURCE_TYPE] + // projects/[PROJECT_ID_OR_NUMBER]/monitoredResourceDescriptors/[RESOURCE_TYPE] // // The `[RESOURCE_TYPE]` is a predefined type, such as // `cloudsql_database`. @@ -305,7 +305,7 @@ type ListMetricDescriptorsRequest struct { // Required. The [project](https://cloud.google.com/monitoring/api/v3#project_name) on // which to execute the request. The format is: // - // projects/[PROJECT_ID_OR_NUMBER] + // projects/[PROJECT_ID_OR_NUMBER] Name string `protobuf:"bytes,5,opt,name=name,proto3" json:"name,omitempty"` // If this field is empty, all custom and // system-defined metric descriptors are returned. @@ -314,7 +314,7 @@ type ListMetricDescriptorsRequest struct { // returned. For example, the following filter matches all // [custom metrics](https://cloud.google.com/monitoring/custom-metrics): // - // metric.type = starts_with("custom.googleapis.com/") + // metric.type = starts_with("custom.googleapis.com/") Filter string `protobuf:"bytes,2,opt,name=filter,proto3" json:"filter,omitempty"` // A positive number that is the maximum number of results to return. PageSize int32 `protobuf:"varint,3,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"` @@ -453,7 +453,7 @@ type GetMetricDescriptorRequest struct { // Required. The metric descriptor on which to execute the request. The format is: // - // projects/[PROJECT_ID_OR_NUMBER]/metricDescriptors/[METRIC_ID] + // projects/[PROJECT_ID_OR_NUMBER]/metricDescriptors/[METRIC_ID] // // An example value of `[METRIC_ID]` is // `"compute.googleapis.com/instance/disk/read_bytes_count"`. @@ -508,8 +508,7 @@ type CreateMetricDescriptorRequest struct { // Required. The [project](https://cloud.google.com/monitoring/api/v3#project_name) on // which to execute the request. The format is: // 4 - // - // projects/[PROJECT_ID_OR_NUMBER] + // projects/[PROJECT_ID_OR_NUMBER] Name string `protobuf:"bytes,3,opt,name=name,proto3" json:"name,omitempty"` // Required. The new [custom metric](https://cloud.google.com/monitoring/custom-metrics) // descriptor. @@ -570,7 +569,7 @@ type DeleteMetricDescriptorRequest struct { // Required. The metric descriptor on which to execute the request. The format is: // - // projects/[PROJECT_ID_OR_NUMBER]/metricDescriptors/[METRIC_ID] + // projects/[PROJECT_ID_OR_NUMBER]/metricDescriptors/[METRIC_ID] // // An example of `[METRIC_ID]` is: // `"custom.googleapis.com/my_test_metric"`. @@ -625,17 +624,17 @@ type ListTimeSeriesRequest struct { // Required. The [project](https://cloud.google.com/monitoring/api/v3#project_name), // organization or folder on which to execute the request. The format is: // - // projects/[PROJECT_ID_OR_NUMBER] - // organizations/[ORGANIZATION_ID] - // folders/[FOLDER_ID] + // projects/[PROJECT_ID_OR_NUMBER] + // organizations/[ORGANIZATION_ID] + // folders/[FOLDER_ID] Name string `protobuf:"bytes,10,opt,name=name,proto3" json:"name,omitempty"` // Required. A [monitoring filter](https://cloud.google.com/monitoring/api/v3/filters) // that specifies which time series should be returned. The filter must // specify a single metric type, and can additionally specify metric labels // and other information. For example: // - // metric.type = "compute.googleapis.com/instance/cpu/usage_time" AND - // metric.labels.instance_name = "my-instance-name" + // metric.type = "compute.googleapis.com/instance/cpu/usage_time" AND + // metric.labels.instance_name = "my-instance-name" Filter string `protobuf:"bytes,2,opt,name=filter,proto3" json:"filter,omitempty"` // Required. The time interval for which results should be returned. Only time series // that contain data points in the specified interval are included @@ -855,7 +854,7 @@ type CreateTimeSeriesRequest struct { // Required. The [project](https://cloud.google.com/monitoring/api/v3#project_name) on // which to execute the request. The format is: // - // projects/[PROJECT_ID_OR_NUMBER] + // projects/[PROJECT_ID_OR_NUMBER] Name string `protobuf:"bytes,3,opt,name=name,proto3" json:"name,omitempty"` // Required. The new data to be added to a list of time series. // Adds at most one data point to each of several time series. The new data @@ -1053,7 +1052,7 @@ type QueryTimeSeriesRequest struct { // Required. The [project](https://cloud.google.com/monitoring/api/v3#project_name) on // which to execute the request. The format is: // - // projects/[PROJECT_ID_OR_NUMBER] + // projects/[PROJECT_ID_OR_NUMBER] Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Required. The query in the [Monitoring Query // Language](https://cloud.google.com/monitoring/mql/reference) format. diff --git a/monitoring/apiv3/v2/monitoringpb/mutation_record.pb.go b/monitoring/apiv3/v2/monitoringpb/mutation_record.pb.go index b7d10ef82ef1..e8a8eaa57ffb 100644 --- a/monitoring/apiv3/v2/monitoringpb/mutation_record.pb.go +++ b/monitoring/apiv3/v2/monitoringpb/mutation_record.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/monitoring/v3/mutation_record.proto package monitoringpb diff --git a/monitoring/apiv3/v2/monitoringpb/notification.pb.go b/monitoring/apiv3/v2/monitoringpb/notification.pb.go index a030a5bcb67c..551a0a91f633 100644 --- a/monitoring/apiv3/v2/monitoringpb/notification.pb.go +++ b/monitoring/apiv3/v2/monitoringpb/notification.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/monitoring/v3/notification.proto package monitoringpb @@ -114,7 +114,7 @@ type NotificationChannelDescriptor struct { // The full REST resource name for this descriptor. The format is: // - // projects/[PROJECT_ID_OR_NUMBER]/notificationChannelDescriptors/[TYPE] + // projects/[PROJECT_ID_OR_NUMBER]/notificationChannelDescriptors/[TYPE] // // In the above, `[TYPE]` is the value of the `type` field. Name string `protobuf:"bytes,6,opt,name=name,proto3" json:"name,omitempty"` @@ -223,7 +223,7 @@ func (x *NotificationChannelDescriptor) GetLaunchStage() api.LaunchStage { if x != nil { return x.LaunchStage } - return api.LaunchStage_LAUNCH_STAGE_UNSPECIFIED + return api.LaunchStage(0) } // A `NotificationChannel` is a medium through which an alert is @@ -241,7 +241,7 @@ type NotificationChannel struct { Type string `protobuf:"bytes,1,opt,name=type,proto3" json:"type,omitempty"` // The full REST resource name for this channel. The format is: // - // projects/[PROJECT_ID_OR_NUMBER]/notificationChannels/[CHANNEL_ID] + // projects/[PROJECT_ID_OR_NUMBER]/notificationChannels/[CHANNEL_ID] // // The `[CHANNEL_ID]` is automatically assigned by the server on creation. Name string `protobuf:"bytes,6,opt,name=name,proto3" json:"name,omitempty"` diff --git a/monitoring/apiv3/v2/monitoringpb/notification_service.pb.go b/monitoring/apiv3/v2/monitoringpb/notification_service.pb.go index 6ccc289a7ad3..b4ee3c2e3832 100644 --- a/monitoring/apiv3/v2/monitoringpb/notification_service.pb.go +++ b/monitoring/apiv3/v2/monitoringpb/notification_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/monitoring/v3/notification_service.proto package monitoringpb @@ -52,7 +52,7 @@ type ListNotificationChannelDescriptorsRequest struct { // Required. The REST resource name of the parent from which to retrieve // the notification channel descriptors. The expected syntax is: // - // projects/[PROJECT_ID_OR_NUMBER] + // projects/[PROJECT_ID_OR_NUMBER] // // Note that this // [names](https://cloud.google.com/monitoring/api/v3#project_name) the parent @@ -194,7 +194,7 @@ type GetNotificationChannelDescriptorRequest struct { // Required. The channel type for which to execute the request. The format is: // - // projects/[PROJECT_ID_OR_NUMBER]/notificationChannelDescriptors/[CHANNEL_TYPE] + // projects/[PROJECT_ID_OR_NUMBER]/notificationChannelDescriptors/[CHANNEL_TYPE] Name string `protobuf:"bytes,3,opt,name=name,proto3" json:"name,omitempty"` } @@ -246,7 +246,7 @@ type CreateNotificationChannelRequest struct { // Required. The [project](https://cloud.google.com/monitoring/api/v3#project_name) on // which to execute the request. The format is: // - // projects/[PROJECT_ID_OR_NUMBER] + // projects/[PROJECT_ID_OR_NUMBER] // // This names the container into which the channel will be // written, this does not name the newly created channel. The resulting @@ -312,7 +312,7 @@ type ListNotificationChannelsRequest struct { // Required. The [project](https://cloud.google.com/monitoring/api/v3#project_name) on // which to execute the request. The format is: // - // projects/[PROJECT_ID_OR_NUMBER] + // projects/[PROJECT_ID_OR_NUMBER] // // This names the container // in which to look for the notification channels; it does not name a @@ -490,7 +490,7 @@ type GetNotificationChannelRequest struct { // Required. The channel for which to execute the request. The format is: // - // projects/[PROJECT_ID_OR_NUMBER]/notificationChannels/[CHANNEL_ID] + // projects/[PROJECT_ID_OR_NUMBER]/notificationChannels/[CHANNEL_ID] Name string `protobuf:"bytes,3,opt,name=name,proto3" json:"name,omitempty"` } @@ -602,7 +602,7 @@ type DeleteNotificationChannelRequest struct { // Required. The channel for which to execute the request. The format is: // - // projects/[PROJECT_ID_OR_NUMBER]/notificationChannels/[CHANNEL_ID] + // projects/[PROJECT_ID_OR_NUMBER]/notificationChannels/[CHANNEL_ID] Name string `protobuf:"bytes,3,opt,name=name,proto3" json:"name,omitempty"` // If true, the notification channel will be deleted regardless of its // use in alert policies (the policies will be updated to remove the diff --git a/monitoring/apiv3/v2/monitoringpb/query_service.pb.go b/monitoring/apiv3/v2/monitoringpb/query_service.pb.go index 42046afd5e6b..016a9a7e71f8 100644 --- a/monitoring/apiv3/v2/monitoringpb/query_service.pb.go +++ b/monitoring/apiv3/v2/monitoringpb/query_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/monitoring/v3/query_service.proto package monitoringpb diff --git a/monitoring/apiv3/v2/monitoringpb/service.pb.go b/monitoring/apiv3/v2/monitoringpb/service.pb.go index 75beee4ba91e..f11ebcbc2271 100644 --- a/monitoring/apiv3/v2/monitoringpb/service.pb.go +++ b/monitoring/apiv3/v2/monitoringpb/service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/monitoring/v3/service.proto package monitoringpb @@ -110,14 +110,13 @@ type Service struct { // Resource name for this Service. The format is: // - // projects/[PROJECT_ID_OR_NUMBER]/services/[SERVICE_ID] + // projects/[PROJECT_ID_OR_NUMBER]/services/[SERVICE_ID] Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Name used for UI elements listing this Service. DisplayName string `protobuf:"bytes,2,opt,name=display_name,json=displayName,proto3" json:"display_name,omitempty"` // REQUIRED. Service-identifying atoms specifying the underlying service. // // Types that are assignable to Identifier: - // // *Service_Custom_ // *Service_AppEngine_ // *Service_CloudEndpoints_ @@ -306,7 +305,7 @@ type ServiceLevelObjective struct { // Resource name for this `ServiceLevelObjective`. The format is: // - // projects/[PROJECT_ID_OR_NUMBER]/services/[SERVICE_ID]/serviceLevelObjectives/[SLO_NAME] + // projects/[PROJECT_ID_OR_NUMBER]/services/[SERVICE_ID]/serviceLevelObjectives/[SLO_NAME] Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Name used for UI elements listing this SLO. DisplayName string `protobuf:"bytes,11,opt,name=display_name,json=displayName,proto3" json:"display_name,omitempty"` @@ -320,7 +319,6 @@ type ServiceLevelObjective struct { // The time period over which the objective will be evaluated. // // Types that are assignable to Period: - // // *ServiceLevelObjective_RollingPeriod // *ServiceLevelObjective_CalendarPeriod Period isServiceLevelObjective_Period `protobuf_oneof:"period"` @@ -411,7 +409,7 @@ func (x *ServiceLevelObjective) GetCalendarPeriod() calendarperiod.CalendarPerio if x, ok := x.GetPeriod().(*ServiceLevelObjective_CalendarPeriod); ok { return x.CalendarPeriod } - return calendarperiod.CalendarPeriod_CALENDAR_PERIOD_UNSPECIFIED + return calendarperiod.CalendarPeriod(0) } func (x *ServiceLevelObjective) GetUserLabels() map[string]string { @@ -465,7 +463,6 @@ type ServiceLevelIndicator struct { // time windows // // Types that are assignable to Type: - // // *ServiceLevelIndicator_BasicSli // *ServiceLevelIndicator_RequestBased // *ServiceLevelIndicator_WindowsBased @@ -589,7 +586,6 @@ type BasicSli struct { // This SLI can be evaluated on the basis of availability or latency. // // Types that are assignable to SliCriteria: - // // *BasicSli_Availability // *BasicSli_Latency SliCriteria isBasicSli_SliCriteria `protobuf_oneof:"sli_criteria"` @@ -757,7 +753,6 @@ type RequestBasedSli struct { // The means to compute a ratio of `good_service` to `total_service`. // // Types that are assignable to Method: - // // *RequestBasedSli_GoodTotalRatio // *RequestBasedSli_DistributionCut Method isRequestBasedSli_Method `protobuf_oneof:"method"` @@ -996,7 +991,6 @@ type WindowsBasedSli struct { // The criterion to use for evaluating window goodness. // // Types that are assignable to WindowCriterion: - // // *WindowsBasedSli_GoodBadMetricFilter // *WindowsBasedSli_GoodTotalRatioThreshold // *WindowsBasedSli_MetricMeanInRange @@ -1640,7 +1634,6 @@ type WindowsBasedSli_PerformanceThreshold struct { // performance over a window. // // Types that are assignable to Type: - // // *WindowsBasedSli_PerformanceThreshold_Performance // *WindowsBasedSli_PerformanceThreshold_BasicSliPerformance Type isWindowsBasedSli_PerformanceThreshold_Type `protobuf_oneof:"type"` diff --git a/monitoring/apiv3/v2/monitoringpb/service_service.pb.go b/monitoring/apiv3/v2/monitoringpb/service_service.pb.go index 50a22ccf5796..8f9d73e946b6 100644 --- a/monitoring/apiv3/v2/monitoringpb/service_service.pb.go +++ b/monitoring/apiv3/v2/monitoringpb/service_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/monitoring/v3/service_service.proto package monitoringpb @@ -51,7 +51,7 @@ type CreateServiceRequest struct { // Required. Resource [name](https://cloud.google.com/monitoring/api/v3#project_name) of // the parent workspace. The format is: // - // projects/[PROJECT_ID_OR_NUMBER] + // projects/[PROJECT_ID_OR_NUMBER] Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // Optional. The Service id to use for this Service. If omitted, an id will be // generated instead. Must match the pattern `[a-z0-9\-]+` @@ -121,7 +121,7 @@ type GetServiceRequest struct { // Required. Resource name of the `Service`. The format is: // - // projects/[PROJECT_ID_OR_NUMBER]/services/[SERVICE_ID] + // projects/[PROJECT_ID_OR_NUMBER]/services/[SERVICE_ID] Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` } @@ -174,22 +174,22 @@ type ListServicesRequest struct { // [project](https://cloud.google.com/monitoring/api/v3#project_name) or a // Monitoring Workspace. The formats are: // - // projects/[PROJECT_ID_OR_NUMBER] - // workspaces/[HOST_PROJECT_ID_OR_NUMBER] + // projects/[PROJECT_ID_OR_NUMBER] + // workspaces/[HOST_PROJECT_ID_OR_NUMBER] Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // A filter specifying what `Service`s to return. The filter currently // supports the following fields: // - // - `identifier_case` - // - `app_engine.module_id` - // - `cloud_endpoints.service` (reserved for future use) - // - `mesh_istio.mesh_uid` - // - `mesh_istio.service_namespace` - // - `mesh_istio.service_name` - // - `cluster_istio.location` (deprecated) - // - `cluster_istio.cluster_name` (deprecated) - // - `cluster_istio.service_namespace` (deprecated) - // - `cluster_istio.service_name` (deprecated) + // - `identifier_case` + // - `app_engine.module_id` + // - `cloud_endpoints.service` (reserved for future use) + // - `mesh_istio.mesh_uid` + // - `mesh_istio.service_namespace` + // - `mesh_istio.service_name` + // - `cluster_istio.location` (deprecated) + // - `cluster_istio.cluster_name` (deprecated) + // - `cluster_istio.service_namespace` (deprecated) + // - `cluster_istio.service_name` (deprecated) // // `identifier_case` refers to which option in the identifier oneof is // populated. For example, the filter `identifier_case = "CUSTOM"` would match @@ -393,7 +393,7 @@ type DeleteServiceRequest struct { // Required. Resource name of the `Service` to delete. The format is: // - // projects/[PROJECT_ID_OR_NUMBER]/services/[SERVICE_ID] + // projects/[PROJECT_ID_OR_NUMBER]/services/[SERVICE_ID] Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` } @@ -444,7 +444,7 @@ type CreateServiceLevelObjectiveRequest struct { // Required. Resource name of the parent `Service`. The format is: // - // projects/[PROJECT_ID_OR_NUMBER]/services/[SERVICE_ID] + // projects/[PROJECT_ID_OR_NUMBER]/services/[SERVICE_ID] Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // Optional. The ServiceLevelObjective id to use for this // ServiceLevelObjective. If omitted, an id will be generated instead. Must @@ -517,7 +517,7 @@ type GetServiceLevelObjectiveRequest struct { // Required. Resource name of the `ServiceLevelObjective` to get. The format is: // - // projects/[PROJECT_ID_OR_NUMBER]/services/[SERVICE_ID]/serviceLevelObjectives/[SLO_NAME] + // projects/[PROJECT_ID_OR_NUMBER]/services/[SERVICE_ID]/serviceLevelObjectives/[SLO_NAME] Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // View of the `ServiceLevelObjective` to return. If `DEFAULT`, return the // `ServiceLevelObjective` as originally defined. If `EXPLICIT` and the @@ -581,8 +581,8 @@ type ListServiceLevelObjectivesRequest struct { // Required. Resource name of the parent containing the listed SLOs, either a // project or a Monitoring Workspace. The formats are: // - // projects/[PROJECT_ID_OR_NUMBER]/services/[SERVICE_ID] - // workspaces/[HOST_PROJECT_ID_OR_NUMBER]/services/- + // projects/[PROJECT_ID_OR_NUMBER]/services/[SERVICE_ID] + // workspaces/[HOST_PROJECT_ID_OR_NUMBER]/services/- Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // A filter specifying what `ServiceLevelObjective`s to return. Filter string `protobuf:"bytes,2,opt,name=filter,proto3" json:"filter,omitempty"` @@ -794,7 +794,7 @@ type DeleteServiceLevelObjectiveRequest struct { // Required. Resource name of the `ServiceLevelObjective` to delete. The format is: // - // projects/[PROJECT_ID_OR_NUMBER]/services/[SERVICE_ID]/serviceLevelObjectives/[SLO_NAME] + // projects/[PROJECT_ID_OR_NUMBER]/services/[SERVICE_ID]/serviceLevelObjectives/[SLO_NAME] Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` } diff --git a/monitoring/apiv3/v2/monitoringpb/span_context.pb.go b/monitoring/apiv3/v2/monitoringpb/span_context.pb.go index a8ccf2dc5c7c..8fe425f0ef47 100644 --- a/monitoring/apiv3/v2/monitoringpb/span_context.pb.go +++ b/monitoring/apiv3/v2/monitoringpb/span_context.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/monitoring/v3/span_context.proto package monitoringpb @@ -49,7 +49,7 @@ type SpanContext struct { // The resource name of the span. The format is: // - // projects/[PROJECT_ID_OR_NUMBER]/traces/[TRACE_ID]/spans/[SPAN_ID] + // projects/[PROJECT_ID_OR_NUMBER]/traces/[TRACE_ID]/spans/[SPAN_ID] // // `[TRACE_ID]` is a unique identifier for a trace within a project; // it is a 32-character hexadecimal encoding of a 16-byte array. diff --git a/monitoring/apiv3/v2/monitoringpb/uptime.pb.go b/monitoring/apiv3/v2/monitoringpb/uptime.pb.go index 827fc0cdb119..b92775348486 100644 --- a/monitoring/apiv3/v2/monitoringpb/uptime.pb.go +++ b/monitoring/apiv3/v2/monitoringpb/uptime.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/monitoring/v3/uptime.proto package monitoringpb @@ -409,7 +409,7 @@ type InternalChecker struct { // A unique resource name for this InternalChecker. The format is: // - // projects/[PROJECT_ID_OR_NUMBER]/internalCheckers/[INTERNAL_CHECKER_ID] + // projects/[PROJECT_ID_OR_NUMBER]/internalCheckers/[INTERNAL_CHECKER_ID] // // `[PROJECT_ID_OR_NUMBER]` is the Stackdriver Workspace project for the // Uptime check config associated with the internal checker. @@ -514,7 +514,7 @@ type UptimeCheckConfig struct { // A unique resource name for this Uptime check configuration. The format is: // - // projects/[PROJECT_ID_OR_NUMBER]/uptimeCheckConfigs/[UPTIME_CHECK_ID] + // projects/[PROJECT_ID_OR_NUMBER]/uptimeCheckConfigs/[UPTIME_CHECK_ID] // // `[PROJECT_ID_OR_NUMBER]` is the Workspace host project associated with the // Uptime check. @@ -530,14 +530,12 @@ type UptimeCheckConfig struct { // The resource the check is checking. Required. // // Types that are assignable to Resource: - // // *UptimeCheckConfig_MonitoredResource // *UptimeCheckConfig_ResourceGroup_ Resource isUptimeCheckConfig_Resource `protobuf_oneof:"resource"` // The type of Uptime check request. // // Types that are assignable to CheckRequestType: - // // *UptimeCheckConfig_HttpCheck_ // *UptimeCheckConfig_TcpCheck_ CheckRequestType isUptimeCheckConfig_CheckRequestType `protobuf_oneof:"check_request_type"` @@ -718,13 +716,12 @@ type UptimeCheckConfig_MonitoredResource struct { // resource](https://cloud.google.com/monitoring/api/resources) associated // with the configuration. // The following monitored resource types are valid for this field: - // - // `uptime_url`, - // `gce_instance`, - // `gae_app`, - // `aws_ec2_instance`, - // `aws_elb_load_balancer` - // `k8s_service` + // `uptime_url`, + // `gce_instance`, + // `gae_app`, + // `aws_ec2_instance`, + // `aws_elb_load_balancer` + // `k8s_service` MonitoredResource *monitoredres.MonitoredResource `protobuf:"bytes,3,opt,name=monitored_resource,json=monitoredResource,proto3,oneof"` } diff --git a/monitoring/apiv3/v2/monitoringpb/uptime_service.pb.go b/monitoring/apiv3/v2/monitoringpb/uptime_service.pb.go index ae698bb6e259..87d369f666ca 100644 --- a/monitoring/apiv3/v2/monitoringpb/uptime_service.pb.go +++ b/monitoring/apiv3/v2/monitoringpb/uptime_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/monitoring/v3/uptime_service.proto package monitoringpb @@ -52,7 +52,7 @@ type ListUptimeCheckConfigsRequest struct { // [project](https://cloud.google.com/monitoring/api/v3#project_name) whose // Uptime check configurations are listed. The format is: // - // projects/[PROJECT_ID_OR_NUMBER] + // projects/[PROJECT_ID_OR_NUMBER] Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // The maximum number of results to return in a single response. The server // may further constrain the maximum number of results returned in a single @@ -198,7 +198,7 @@ type GetUptimeCheckConfigRequest struct { // Required. The Uptime check configuration to retrieve. The format is: // - // projects/[PROJECT_ID_OR_NUMBER]/uptimeCheckConfigs/[UPTIME_CHECK_ID] + // projects/[PROJECT_ID_OR_NUMBER]/uptimeCheckConfigs/[UPTIME_CHECK_ID] Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` } @@ -251,7 +251,7 @@ type CreateUptimeCheckConfigRequest struct { // [project](https://cloud.google.com/monitoring/api/v3#project_name) in which // to create the Uptime check. The format is: // - // projects/[PROJECT_ID_OR_NUMBER] + // projects/[PROJECT_ID_OR_NUMBER] Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // Required. The new Uptime check configuration. UptimeCheckConfig *UptimeCheckConfig `protobuf:"bytes,2,opt,name=uptime_check_config,json=uptimeCheckConfig,proto3" json:"uptime_check_config,omitempty"` @@ -382,7 +382,7 @@ type DeleteUptimeCheckConfigRequest struct { // Required. The Uptime check configuration to delete. The format is: // - // projects/[PROJECT_ID_OR_NUMBER]/uptimeCheckConfigs/[UPTIME_CHECK_ID] + // projects/[PROJECT_ID_OR_NUMBER]/uptimeCheckConfigs/[UPTIME_CHECK_ID] Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` } diff --git a/monitoring/apiv3/v2/notification_channel_client.go b/monitoring/apiv3/v2/notification_channel_client.go index 240bdbebd58d..3407b0360653 100644 --- a/monitoring/apiv3/v2/notification_channel_client.go +++ b/monitoring/apiv3/v2/notification_channel_client.go @@ -17,21 +17,27 @@ package monitoring import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" monitoringpb "cloud.google.com/go/monitoring/apiv3/v2/monitoringpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -148,6 +154,84 @@ func defaultNotificationChannelCallOptions() *NotificationChannelCallOptions { } } +func defaultNotificationChannelRESTCallOptions() *NotificationChannelCallOptions { + return &NotificationChannelCallOptions{ + ListNotificationChannelDescriptors: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 30000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetNotificationChannelDescriptor: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 30000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListNotificationChannels: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 30000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetNotificationChannel: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 30000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateNotificationChannel: []gax.CallOption{}, + UpdateNotificationChannel: []gax.CallOption{}, + DeleteNotificationChannel: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 30000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + SendNotificationChannelVerificationCode: []gax.CallOption{}, + GetNotificationChannelVerificationCode: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 30000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + VerifyNotificationChannel: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 30000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + } +} + // internalNotificationChannelClient is an interface that defines the methods available from Cloud Monitoring API. type internalNotificationChannelClient interface { Close() error @@ -364,6 +448,75 @@ func (c *notificationChannelGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type notificationChannelRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing NotificationChannelClient + CallOptions **NotificationChannelCallOptions +} + +// NewNotificationChannelRESTClient creates a new notification channel service rest client. +// +// The Notification Channel API provides access to configuration that +// controls how messages related to incidents are sent. +func NewNotificationChannelRESTClient(ctx context.Context, opts ...option.ClientOption) (*NotificationChannelClient, error) { + clientOpts := append(defaultNotificationChannelRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultNotificationChannelRESTCallOptions() + c := ¬ificationChannelRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &NotificationChannelClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultNotificationChannelRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://monitoring.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://monitoring.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://monitoring.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *notificationChannelRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *notificationChannelRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *notificationChannelRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *notificationChannelGRPCClient) ListNotificationChannelDescriptors(ctx context.Context, req *monitoringpb.ListNotificationChannelDescriptorsRequest, opts ...gax.CallOption) *NotificationChannelDescriptorIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -622,6 +775,689 @@ func (c *notificationChannelGRPCClient) VerifyNotificationChannel(ctx context.Co return resp, nil } +// ListNotificationChannelDescriptors lists the descriptors for supported channel types. The use of descriptors +// makes it possible for new channel types to be dynamically added. +func (c *notificationChannelRESTClient) ListNotificationChannelDescriptors(ctx context.Context, req *monitoringpb.ListNotificationChannelDescriptorsRequest, opts ...gax.CallOption) *NotificationChannelDescriptorIterator { + it := &NotificationChannelDescriptorIterator{} + req = proto.Clone(req).(*monitoringpb.ListNotificationChannelDescriptorsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*monitoringpb.NotificationChannelDescriptor, string, error) { + resp := &monitoringpb.ListNotificationChannelDescriptorsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/notificationChannelDescriptors", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetChannelDescriptors(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetNotificationChannelDescriptor gets a single channel descriptor. The descriptor indicates which fields +// are expected / permitted for a notification channel of the given type. +func (c *notificationChannelRESTClient) GetNotificationChannelDescriptor(ctx context.Context, req *monitoringpb.GetNotificationChannelDescriptorRequest, opts ...gax.CallOption) (*monitoringpb.NotificationChannelDescriptor, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetNotificationChannelDescriptor[0:len((*c.CallOptions).GetNotificationChannelDescriptor):len((*c.CallOptions).GetNotificationChannelDescriptor)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &monitoringpb.NotificationChannelDescriptor{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListNotificationChannels lists the notification channels that have been created for the project. +func (c *notificationChannelRESTClient) ListNotificationChannels(ctx context.Context, req *monitoringpb.ListNotificationChannelsRequest, opts ...gax.CallOption) *NotificationChannelIterator { + it := &NotificationChannelIterator{} + req = proto.Clone(req).(*monitoringpb.ListNotificationChannelsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*monitoringpb.NotificationChannel, string, error) { + resp := &monitoringpb.ListNotificationChannelsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/notificationChannels", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetNotificationChannels(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetNotificationChannel gets a single notification channel. The channel includes the relevant +// configuration details with which the channel was created. However, the +// response may truncate or omit passwords, API keys, or other private key +// matter and thus the response may not be 100% identical to the information +// that was supplied in the call to the create method. +func (c *notificationChannelRESTClient) GetNotificationChannel(ctx context.Context, req *monitoringpb.GetNotificationChannelRequest, opts ...gax.CallOption) (*monitoringpb.NotificationChannel, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetNotificationChannel[0:len((*c.CallOptions).GetNotificationChannel):len((*c.CallOptions).GetNotificationChannel)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &monitoringpb.NotificationChannel{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateNotificationChannel creates a new notification channel, representing a single notification +// endpoint such as an email address, SMS number, or PagerDuty service. +func (c *notificationChannelRESTClient) CreateNotificationChannel(ctx context.Context, req *monitoringpb.CreateNotificationChannelRequest, opts ...gax.CallOption) (*monitoringpb.NotificationChannel, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetNotificationChannel() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/notificationChannels", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateNotificationChannel[0:len((*c.CallOptions).CreateNotificationChannel):len((*c.CallOptions).CreateNotificationChannel)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &monitoringpb.NotificationChannel{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateNotificationChannel updates a notification channel. Fields not specified in the field mask +// remain unchanged. +func (c *notificationChannelRESTClient) UpdateNotificationChannel(ctx context.Context, req *monitoringpb.UpdateNotificationChannelRequest, opts ...gax.CallOption) (*monitoringpb.NotificationChannel, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetNotificationChannel() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetNotificationChannel().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "notification_channel.name", url.QueryEscape(req.GetNotificationChannel().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateNotificationChannel[0:len((*c.CallOptions).UpdateNotificationChannel):len((*c.CallOptions).UpdateNotificationChannel)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &monitoringpb.NotificationChannel{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteNotificationChannel deletes a notification channel. +func (c *notificationChannelRESTClient) DeleteNotificationChannel(ctx context.Context, req *monitoringpb.DeleteNotificationChannelRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetForce() { + params.Add("force", fmt.Sprintf("%v", req.GetForce())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// SendNotificationChannelVerificationCode causes a verification code to be delivered to the channel. The code +// can then be supplied in VerifyNotificationChannel to verify the channel. +func (c *notificationChannelRESTClient) SendNotificationChannelVerificationCode(ctx context.Context, req *monitoringpb.SendNotificationChannelVerificationCodeRequest, opts ...gax.CallOption) error { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v3/%v:sendVerificationCode", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetNotificationChannelVerificationCode requests a verification code for an already verified channel that can then +// be used in a call to VerifyNotificationChannel() on a different channel +// with an equivalent identity in the same or in a different project. This +// makes it possible to copy a channel between projects without requiring +// manual reverification of the channel. If the channel is not in the +// verified state, this method will fail (in other words, this may only be +// used if the SendNotificationChannelVerificationCode and +// VerifyNotificationChannel paths have already been used to put the given +// channel into the verified state). +// +// There is no guarantee that the verification codes returned by this method +// will be of a similar structure or form as the ones that are delivered +// to the channel via SendNotificationChannelVerificationCode; while +// VerifyNotificationChannel() will recognize both the codes delivered via +// SendNotificationChannelVerificationCode() and returned from +// GetNotificationChannelVerificationCode(), it is typically the case that +// the verification codes delivered via +// SendNotificationChannelVerificationCode() will be shorter and also +// have a shorter expiration (e.g. codes such as “G-123456”) whereas +// GetVerificationCode() will typically return a much longer, websafe base +// 64 encoded string that has a longer expiration time. +func (c *notificationChannelRESTClient) GetNotificationChannelVerificationCode(ctx context.Context, req *monitoringpb.GetNotificationChannelVerificationCodeRequest, opts ...gax.CallOption) (*monitoringpb.GetNotificationChannelVerificationCodeResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v:getVerificationCode", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetNotificationChannelVerificationCode[0:len((*c.CallOptions).GetNotificationChannelVerificationCode):len((*c.CallOptions).GetNotificationChannelVerificationCode)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &monitoringpb.GetNotificationChannelVerificationCodeResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// VerifyNotificationChannel verifies a NotificationChannel by proving receipt of the code +// delivered to the channel as a result of calling +// SendNotificationChannelVerificationCode. +func (c *notificationChannelRESTClient) VerifyNotificationChannel(ctx context.Context, req *monitoringpb.VerifyNotificationChannelRequest, opts ...gax.CallOption) (*monitoringpb.NotificationChannel, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v:verify", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).VerifyNotificationChannel[0:len((*c.CallOptions).VerifyNotificationChannel):len((*c.CallOptions).VerifyNotificationChannel)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &monitoringpb.NotificationChannel{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + // NotificationChannelDescriptorIterator manages a stream of *monitoringpb.NotificationChannelDescriptor. type NotificationChannelDescriptorIterator struct { items []*monitoringpb.NotificationChannelDescriptor diff --git a/monitoring/apiv3/v2/notification_channel_client_example_test.go b/monitoring/apiv3/v2/notification_channel_client_example_test.go index f7865e9a92b8..d4da482cdaab 100644 --- a/monitoring/apiv3/v2/notification_channel_client_example_test.go +++ b/monitoring/apiv3/v2/notification_channel_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewNotificationChannelClient() { _ = c } +func ExampleNewNotificationChannelRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := monitoring.NewNotificationChannelRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleNotificationChannelClient_ListNotificationChannelDescriptors() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/monitoring/apiv3/v2/query_client.go b/monitoring/apiv3/v2/query_client.go index 0d7af17a0a00..69c6a391fe90 100644 --- a/monitoring/apiv3/v2/query_client.go +++ b/monitoring/apiv3/v2/query_client.go @@ -17,19 +17,25 @@ package monitoring import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" monitoringpb "cloud.google.com/go/monitoring/apiv3/v2/monitoringpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -58,6 +64,12 @@ func defaultQueryCallOptions() *QueryCallOptions { } } +func defaultQueryRESTCallOptions() *QueryCallOptions { + return &QueryCallOptions{ + QueryTimeSeries: []gax.CallOption{}, + } +} + // internalQueryClient is an interface that defines the methods available from Cloud Monitoring API. type internalQueryClient interface { Close() error @@ -191,6 +203,76 @@ func (c *queryGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type queryRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing QueryClient + CallOptions **QueryCallOptions +} + +// NewQueryRESTClient creates a new query service rest client. +// +// The QueryService API is used to manage time series data in Stackdriver +// Monitoring. Time series data is a collection of data points that describes +// the time-varying values of a metric. +func NewQueryRESTClient(ctx context.Context, opts ...option.ClientOption) (*QueryClient, error) { + clientOpts := append(defaultQueryRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultQueryRESTCallOptions() + c := &queryRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &QueryClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultQueryRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://monitoring.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://monitoring.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://monitoring.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *queryRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *queryRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *queryRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *queryGRPCClient) QueryTimeSeries(ctx context.Context, req *monitoringpb.QueryTimeSeriesRequest, opts ...gax.CallOption) *TimeSeriesDataIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -236,6 +318,94 @@ func (c *queryGRPCClient) QueryTimeSeries(ctx context.Context, req *monitoringpb return it } +// QueryTimeSeries queries time series using Monitoring Query Language. This method does not require a Workspace. +func (c *queryRESTClient) QueryTimeSeries(ctx context.Context, req *monitoringpb.QueryTimeSeriesRequest, opts ...gax.CallOption) *TimeSeriesDataIterator { + it := &TimeSeriesDataIterator{} + req = proto.Clone(req).(*monitoringpb.QueryTimeSeriesRequest) + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*monitoringpb.TimeSeriesData, string, error) { + resp := &monitoringpb.QueryTimeSeriesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, "", err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/timeSeries:query", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetTimeSeriesData(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + // TimeSeriesDataIterator manages a stream of *monitoringpb.TimeSeriesData. type TimeSeriesDataIterator struct { items []*monitoringpb.TimeSeriesData diff --git a/monitoring/apiv3/v2/query_client_example_test.go b/monitoring/apiv3/v2/query_client_example_test.go index d4333e8e0bb4..f264f80f3425 100644 --- a/monitoring/apiv3/v2/query_client_example_test.go +++ b/monitoring/apiv3/v2/query_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewQueryClient() { _ = c } +func ExampleNewQueryRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := monitoring.NewQueryRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleQueryClient_QueryTimeSeries() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/monitoring/apiv3/v2/service_monitoring_client.go b/monitoring/apiv3/v2/service_monitoring_client.go index 3b5b471cf7e9..4b9bda315aca 100644 --- a/monitoring/apiv3/v2/service_monitoring_client.go +++ b/monitoring/apiv3/v2/service_monitoring_client.go @@ -17,21 +17,27 @@ package monitoring import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" monitoringpb "cloud.google.com/go/monitoring/apiv3/v2/monitoringpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -138,6 +144,75 @@ func defaultServiceMonitoringCallOptions() *ServiceMonitoringCallOptions { } } +func defaultServiceMonitoringRESTCallOptions() *ServiceMonitoringCallOptions { + return &ServiceMonitoringCallOptions{ + CreateService: []gax.CallOption{}, + GetService: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 30000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListServices: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 30000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UpdateService: []gax.CallOption{}, + DeleteService: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 30000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateServiceLevelObjective: []gax.CallOption{}, + GetServiceLevelObjective: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 30000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListServiceLevelObjectives: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 30000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UpdateServiceLevelObjective: []gax.CallOption{}, + DeleteServiceLevelObjective: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 30000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + } +} + // internalServiceMonitoringClient is an interface that defines the methods available from Cloud Monitoring API. type internalServiceMonitoringClient interface { Close() error @@ -327,6 +402,77 @@ func (c *serviceMonitoringGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type serviceMonitoringRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing ServiceMonitoringClient + CallOptions **ServiceMonitoringCallOptions +} + +// NewServiceMonitoringRESTClient creates a new service monitoring service rest client. +// +// The Cloud Monitoring Service-Oriented Monitoring API has endpoints for +// managing and querying aspects of a workspace’s services. These include the +// Service's monitored resources, its Service-Level Objectives, and a taxonomy +// of categorized Health Metrics. +func NewServiceMonitoringRESTClient(ctx context.Context, opts ...option.ClientOption) (*ServiceMonitoringClient, error) { + clientOpts := append(defaultServiceMonitoringRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultServiceMonitoringRESTCallOptions() + c := &serviceMonitoringRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &ServiceMonitoringClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultServiceMonitoringRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://monitoring.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://monitoring.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://monitoring.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *serviceMonitoringRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *serviceMonitoringRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *serviceMonitoringRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *serviceMonitoringGRPCClient) CreateService(ctx context.Context, req *monitoringpb.CreateServiceRequest, opts ...gax.CallOption) (*monitoringpb.Service, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) @@ -585,6 +731,670 @@ func (c *serviceMonitoringGRPCClient) DeleteServiceLevelObjective(ctx context.Co return err } +// CreateService create a Service. +func (c *serviceMonitoringRESTClient) CreateService(ctx context.Context, req *monitoringpb.CreateServiceRequest, opts ...gax.CallOption) (*monitoringpb.Service, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetService() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/services", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetServiceId() != "" { + params.Add("serviceId", fmt.Sprintf("%v", req.GetServiceId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateService[0:len((*c.CallOptions).CreateService):len((*c.CallOptions).CreateService)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &monitoringpb.Service{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetService get the named Service. +func (c *serviceMonitoringRESTClient) GetService(ctx context.Context, req *monitoringpb.GetServiceRequest, opts ...gax.CallOption) (*monitoringpb.Service, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetService[0:len((*c.CallOptions).GetService):len((*c.CallOptions).GetService)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &monitoringpb.Service{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListServices list Services for this workspace. +func (c *serviceMonitoringRESTClient) ListServices(ctx context.Context, req *monitoringpb.ListServicesRequest, opts ...gax.CallOption) *ServiceIterator { + it := &ServiceIterator{} + req = proto.Clone(req).(*monitoringpb.ListServicesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*monitoringpb.Service, string, error) { + resp := &monitoringpb.ListServicesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/services", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetServices(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// UpdateService update this Service. +func (c *serviceMonitoringRESTClient) UpdateService(ctx context.Context, req *monitoringpb.UpdateServiceRequest, opts ...gax.CallOption) (*monitoringpb.Service, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetService() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetService().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "service.name", url.QueryEscape(req.GetService().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateService[0:len((*c.CallOptions).UpdateService):len((*c.CallOptions).UpdateService)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &monitoringpb.Service{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteService soft delete this Service. +func (c *serviceMonitoringRESTClient) DeleteService(ctx context.Context, req *monitoringpb.DeleteServiceRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// CreateServiceLevelObjective create a ServiceLevelObjective for the given Service. +func (c *serviceMonitoringRESTClient) CreateServiceLevelObjective(ctx context.Context, req *monitoringpb.CreateServiceLevelObjectiveRequest, opts ...gax.CallOption) (*monitoringpb.ServiceLevelObjective, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetServiceLevelObjective() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/serviceLevelObjectives", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetServiceLevelObjectiveId() != "" { + params.Add("serviceLevelObjectiveId", fmt.Sprintf("%v", req.GetServiceLevelObjectiveId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateServiceLevelObjective[0:len((*c.CallOptions).CreateServiceLevelObjective):len((*c.CallOptions).CreateServiceLevelObjective)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &monitoringpb.ServiceLevelObjective{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetServiceLevelObjective get a ServiceLevelObjective by name. +func (c *serviceMonitoringRESTClient) GetServiceLevelObjective(ctx context.Context, req *monitoringpb.GetServiceLevelObjectiveRequest, opts ...gax.CallOption) (*monitoringpb.ServiceLevelObjective, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetView() != 0 { + params.Add("view", fmt.Sprintf("%v", req.GetView())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetServiceLevelObjective[0:len((*c.CallOptions).GetServiceLevelObjective):len((*c.CallOptions).GetServiceLevelObjective)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &monitoringpb.ServiceLevelObjective{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListServiceLevelObjectives list the ServiceLevelObjectives for the given Service. +func (c *serviceMonitoringRESTClient) ListServiceLevelObjectives(ctx context.Context, req *monitoringpb.ListServiceLevelObjectivesRequest, opts ...gax.CallOption) *ServiceLevelObjectiveIterator { + it := &ServiceLevelObjectiveIterator{} + req = proto.Clone(req).(*monitoringpb.ListServiceLevelObjectivesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*monitoringpb.ServiceLevelObjective, string, error) { + resp := &monitoringpb.ListServiceLevelObjectivesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/serviceLevelObjectives", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + if req.GetView() != 0 { + params.Add("view", fmt.Sprintf("%v", req.GetView())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetServiceLevelObjectives(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// UpdateServiceLevelObjective update the given ServiceLevelObjective. +func (c *serviceMonitoringRESTClient) UpdateServiceLevelObjective(ctx context.Context, req *monitoringpb.UpdateServiceLevelObjectiveRequest, opts ...gax.CallOption) (*monitoringpb.ServiceLevelObjective, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetServiceLevelObjective() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetServiceLevelObjective().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "service_level_objective.name", url.QueryEscape(req.GetServiceLevelObjective().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateServiceLevelObjective[0:len((*c.CallOptions).UpdateServiceLevelObjective):len((*c.CallOptions).UpdateServiceLevelObjective)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &monitoringpb.ServiceLevelObjective{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteServiceLevelObjective delete the given ServiceLevelObjective. +func (c *serviceMonitoringRESTClient) DeleteServiceLevelObjective(ctx context.Context, req *monitoringpb.DeleteServiceLevelObjectiveRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + // ServiceIterator manages a stream of *monitoringpb.Service. type ServiceIterator struct { items []*monitoringpb.Service diff --git a/monitoring/apiv3/v2/service_monitoring_client_example_test.go b/monitoring/apiv3/v2/service_monitoring_client_example_test.go index c879c692a2ec..e8ec15c1487c 100644 --- a/monitoring/apiv3/v2/service_monitoring_client_example_test.go +++ b/monitoring/apiv3/v2/service_monitoring_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewServiceMonitoringClient() { _ = c } +func ExampleNewServiceMonitoringRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := monitoring.NewServiceMonitoringRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleServiceMonitoringClient_CreateService() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/monitoring/apiv3/v2/uptime_check_client.go b/monitoring/apiv3/v2/uptime_check_client.go index b0da1501c764..bdf3a32af588 100644 --- a/monitoring/apiv3/v2/uptime_check_client.go +++ b/monitoring/apiv3/v2/uptime_check_client.go @@ -17,21 +17,27 @@ package monitoring import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" monitoringpb "cloud.google.com/go/monitoring/apiv3/v2/monitoringpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -110,6 +116,53 @@ func defaultUptimeCheckCallOptions() *UptimeCheckCallOptions { } } +func defaultUptimeCheckRESTCallOptions() *UptimeCheckCallOptions { + return &UptimeCheckCallOptions{ + ListUptimeCheckConfigs: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 30000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetUptimeCheckConfig: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 30000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateUptimeCheckConfig: []gax.CallOption{}, + UpdateUptimeCheckConfig: []gax.CallOption{}, + DeleteUptimeCheckConfig: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 30000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListUptimeCheckIps: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 30000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + } +} + // internalUptimeCheckClient is an interface that defines the methods available from Cloud Monitoring API. type internalUptimeCheckClient interface { Close() error @@ -289,6 +342,81 @@ func (c *uptimeCheckGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type uptimeCheckRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing UptimeCheckClient + CallOptions **UptimeCheckCallOptions +} + +// NewUptimeCheckRESTClient creates a new uptime check service rest client. +// +// The UptimeCheckService API is used to manage (list, create, delete, edit) +// Uptime check configurations in the Stackdriver Monitoring product. An Uptime +// check is a piece of configuration that determines which resources and +// services to monitor for availability. These configurations can also be +// configured interactively by navigating to the [Cloud Console] +// (http://console.cloud.google.com (at http://console.cloud.google.com)), selecting the appropriate project, +// clicking on “Monitoring” on the left-hand side to navigate to Stackdriver, +// and then clicking on “Uptime”. +func NewUptimeCheckRESTClient(ctx context.Context, opts ...option.ClientOption) (*UptimeCheckClient, error) { + clientOpts := append(defaultUptimeCheckRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultUptimeCheckRESTCallOptions() + c := &uptimeCheckRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &UptimeCheckClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultUptimeCheckRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://monitoring.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://monitoring.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://monitoring.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *uptimeCheckRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *uptimeCheckRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *uptimeCheckRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *uptimeCheckGRPCClient) ListUptimeCheckConfigs(ctx context.Context, req *monitoringpb.ListUptimeCheckConfigsRequest, opts ...gax.CallOption) *UptimeCheckConfigIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -461,6 +589,423 @@ func (c *uptimeCheckGRPCClient) ListUptimeCheckIps(ctx context.Context, req *mon return it } +// ListUptimeCheckConfigs lists the existing valid Uptime check configurations for the project +// (leaving out any invalid configurations). +func (c *uptimeCheckRESTClient) ListUptimeCheckConfigs(ctx context.Context, req *monitoringpb.ListUptimeCheckConfigsRequest, opts ...gax.CallOption) *UptimeCheckConfigIterator { + it := &UptimeCheckConfigIterator{} + req = proto.Clone(req).(*monitoringpb.ListUptimeCheckConfigsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*monitoringpb.UptimeCheckConfig, string, error) { + resp := &monitoringpb.ListUptimeCheckConfigsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/uptimeCheckConfigs", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetUptimeCheckConfigs(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetUptimeCheckConfig gets a single Uptime check configuration. +func (c *uptimeCheckRESTClient) GetUptimeCheckConfig(ctx context.Context, req *monitoringpb.GetUptimeCheckConfigRequest, opts ...gax.CallOption) (*monitoringpb.UptimeCheckConfig, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetUptimeCheckConfig[0:len((*c.CallOptions).GetUptimeCheckConfig):len((*c.CallOptions).GetUptimeCheckConfig)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &monitoringpb.UptimeCheckConfig{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateUptimeCheckConfig creates a new Uptime check configuration. +func (c *uptimeCheckRESTClient) CreateUptimeCheckConfig(ctx context.Context, req *monitoringpb.CreateUptimeCheckConfigRequest, opts ...gax.CallOption) (*monitoringpb.UptimeCheckConfig, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetUptimeCheckConfig() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/uptimeCheckConfigs", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateUptimeCheckConfig[0:len((*c.CallOptions).CreateUptimeCheckConfig):len((*c.CallOptions).CreateUptimeCheckConfig)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &monitoringpb.UptimeCheckConfig{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateUptimeCheckConfig updates an Uptime check configuration. You can either replace the entire +// configuration with a new one or replace only certain fields in the current +// configuration by specifying the fields to be updated via updateMask. +// Returns the updated configuration. +func (c *uptimeCheckRESTClient) UpdateUptimeCheckConfig(ctx context.Context, req *monitoringpb.UpdateUptimeCheckConfigRequest, opts ...gax.CallOption) (*monitoringpb.UptimeCheckConfig, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetUptimeCheckConfig() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetUptimeCheckConfig().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "uptime_check_config.name", url.QueryEscape(req.GetUptimeCheckConfig().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateUptimeCheckConfig[0:len((*c.CallOptions).UpdateUptimeCheckConfig):len((*c.CallOptions).UpdateUptimeCheckConfig)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &monitoringpb.UptimeCheckConfig{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteUptimeCheckConfig deletes an Uptime check configuration. Note that this method will fail +// if the Uptime check configuration is referenced by an alert policy or +// other dependent configs that would be rendered invalid by the deletion. +func (c *uptimeCheckRESTClient) DeleteUptimeCheckConfig(ctx context.Context, req *monitoringpb.DeleteUptimeCheckConfigRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// ListUptimeCheckIps returns the list of IP addresses that checkers run from +func (c *uptimeCheckRESTClient) ListUptimeCheckIps(ctx context.Context, req *monitoringpb.ListUptimeCheckIpsRequest, opts ...gax.CallOption) *UptimeCheckIpIterator { + it := &UptimeCheckIpIterator{} + req = proto.Clone(req).(*monitoringpb.ListUptimeCheckIpsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*monitoringpb.UptimeCheckIp, string, error) { + resp := &monitoringpb.ListUptimeCheckIpsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/uptimeCheckIps") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetUptimeCheckIps(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + // UptimeCheckConfigIterator manages a stream of *monitoringpb.UptimeCheckConfig. type UptimeCheckConfigIterator struct { items []*monitoringpb.UptimeCheckConfig diff --git a/monitoring/apiv3/v2/uptime_check_client_example_test.go b/monitoring/apiv3/v2/uptime_check_client_example_test.go index 1be5618e0d18..a48f15d9004f 100644 --- a/monitoring/apiv3/v2/uptime_check_client_example_test.go +++ b/monitoring/apiv3/v2/uptime_check_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewUptimeCheckClient() { _ = c } +func ExampleNewUptimeCheckRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := monitoring.NewUptimeCheckRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleUptimeCheckClient_ListUptimeCheckConfigs() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/monitoring/dashboard/apiv1/dashboardpb/alertchart.pb.go b/monitoring/dashboard/apiv1/dashboardpb/alertchart.pb.go index 8610f67069e1..cf5d802c6d50 100644 --- a/monitoring/dashboard/apiv1/dashboardpb/alertchart.pb.go +++ b/monitoring/dashboard/apiv1/dashboardpb/alertchart.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/monitoring/dashboard/v1/alertchart.proto package dashboardpb @@ -44,7 +44,7 @@ type AlertChart struct { // Required. The resource name of the alert policy. The format is: // - // projects/[PROJECT_ID_OR_NUMBER]/alertPolicies/[ALERT_POLICY_ID] + // projects/[PROJECT_ID_OR_NUMBER]/alertPolicies/[ALERT_POLICY_ID] Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` } diff --git a/monitoring/dashboard/apiv1/dashboardpb/collapsible_group.pb.go b/monitoring/dashboard/apiv1/dashboardpb/collapsible_group.pb.go index f4ed49cfba14..9b695048475a 100644 --- a/monitoring/dashboard/apiv1/dashboardpb/collapsible_group.pb.go +++ b/monitoring/dashboard/apiv1/dashboardpb/collapsible_group.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/monitoring/dashboard/v1/collapsible_group.proto package dashboardpb diff --git a/monitoring/dashboard/apiv1/dashboardpb/common.pb.go b/monitoring/dashboard/apiv1/dashboardpb/common.pb.go index 660641387d3e..499174980b08 100644 --- a/monitoring/dashboard/apiv1/dashboardpb/common.pb.go +++ b/monitoring/dashboard/apiv1/dashboardpb/common.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/monitoring/dashboard/v1/common.proto package dashboardpb diff --git a/monitoring/dashboard/apiv1/dashboardpb/dashboard.pb.go b/monitoring/dashboard/apiv1/dashboardpb/dashboard.pb.go index 783138d89e54..d92d4aecd096 100644 --- a/monitoring/dashboard/apiv1/dashboardpb/dashboard.pb.go +++ b/monitoring/dashboard/apiv1/dashboardpb/dashboard.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/monitoring/dashboard/v1/dashboard.proto package dashboardpb @@ -58,7 +58,6 @@ type Dashboard struct { // A dashboard's root container element that defines the layout style. // // Types that are assignable to Layout: - // // *Dashboard_GridLayout // *Dashboard_MosaicLayout // *Dashboard_RowLayout diff --git a/monitoring/dashboard/apiv1/dashboardpb/dashboard_filter.pb.go b/monitoring/dashboard/apiv1/dashboardpb/dashboard_filter.pb.go index 581390ad4791..d9fea49d1850 100644 --- a/monitoring/dashboard/apiv1/dashboardpb/dashboard_filter.pb.go +++ b/monitoring/dashboard/apiv1/dashboardpb/dashboard_filter.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/monitoring/dashboard/v1/dashboard_filter.proto package dashboardpb @@ -116,7 +116,6 @@ type DashboardFilter struct { // The default value used in the filter comparison // // Types that are assignable to DefaultValue: - // // *DashboardFilter_StringValue DefaultValue isDashboardFilter_DefaultValue `protobuf_oneof:"default_value"` // The specified filter type diff --git a/monitoring/dashboard/apiv1/dashboardpb/dashboards_service.pb.go b/monitoring/dashboard/apiv1/dashboardpb/dashboards_service.pb.go index fb156d643716..06b230e442f5 100644 --- a/monitoring/dashboard/apiv1/dashboardpb/dashboards_service.pb.go +++ b/monitoring/dashboard/apiv1/dashboardpb/dashboards_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/monitoring/dashboard/v1/dashboards_service.proto package dashboardpb @@ -49,7 +49,7 @@ type CreateDashboardRequest struct { // Required. The project on which to execute the request. The format is: // - // projects/[PROJECT_ID_OR_NUMBER] + // projects/[PROJECT_ID_OR_NUMBER] // // The `[PROJECT_ID_OR_NUMBER]` must match the dashboard resource name. Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` @@ -121,7 +121,7 @@ type ListDashboardsRequest struct { // Required. The scope of the dashboards to list. The format is: // - // projects/[PROJECT_ID_OR_NUMBER] + // projects/[PROJECT_ID_OR_NUMBER] Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // A positive number that is the maximum number of results to return. // If unspecified, a default of 1000 is used. @@ -253,9 +253,9 @@ type GetDashboardRequest struct { // Required. The resource name of the Dashboard. The format is one of: // - // - `dashboards/[DASHBOARD_ID]` (for system dashboards) - // - `projects/[PROJECT_ID_OR_NUMBER]/dashboards/[DASHBOARD_ID]` - // (for custom dashboards). + // - `dashboards/[DASHBOARD_ID]` (for system dashboards) + // - `projects/[PROJECT_ID_OR_NUMBER]/dashboards/[DASHBOARD_ID]` + // (for custom dashboards). Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` } @@ -306,7 +306,7 @@ type DeleteDashboardRequest struct { // Required. The resource name of the Dashboard. The format is: // - // projects/[PROJECT_ID_OR_NUMBER]/dashboards/[DASHBOARD_ID] + // projects/[PROJECT_ID_OR_NUMBER]/dashboards/[DASHBOARD_ID] Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` } diff --git a/monitoring/dashboard/apiv1/dashboardpb/drilldowns.pb.go b/monitoring/dashboard/apiv1/dashboardpb/drilldowns.pb.go index c33ba2f2f771..9bc011875906 100644 --- a/monitoring/dashboard/apiv1/dashboardpb/drilldowns.pb.go +++ b/monitoring/dashboard/apiv1/dashboardpb/drilldowns.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/monitoring/dashboard/v1/drilldowns.proto package dashboardpb diff --git a/monitoring/dashboard/apiv1/dashboardpb/layouts.pb.go b/monitoring/dashboard/apiv1/dashboardpb/layouts.pb.go index afe52a4a2998..bb0ec60d3e54 100644 --- a/monitoring/dashboard/apiv1/dashboardpb/layouts.pb.go +++ b/monitoring/dashboard/apiv1/dashboardpb/layouts.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/monitoring/dashboard/v1/layouts.proto package dashboardpb diff --git a/monitoring/dashboard/apiv1/dashboardpb/logs_panel.pb.go b/monitoring/dashboard/apiv1/dashboardpb/logs_panel.pb.go index ad44268efd83..a206f5f41e98 100644 --- a/monitoring/dashboard/apiv1/dashboardpb/logs_panel.pb.go +++ b/monitoring/dashboard/apiv1/dashboardpb/logs_panel.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/monitoring/dashboard/v1/logs_panel.proto package dashboardpb diff --git a/monitoring/dashboard/apiv1/dashboardpb/metrics.pb.go b/monitoring/dashboard/apiv1/dashboardpb/metrics.pb.go index cda5b3bcdbd8..d644ace6974e 100644 --- a/monitoring/dashboard/apiv1/dashboardpb/metrics.pb.go +++ b/monitoring/dashboard/apiv1/dashboardpb/metrics.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/monitoring/dashboard/v1/metrics.proto package dashboardpb @@ -263,7 +263,6 @@ type TimeSeriesQuery struct { // Parameters needed to obtain data for the chart. // // Types that are assignable to Source: - // // *TimeSeriesQuery_TimeSeriesFilter // *TimeSeriesQuery_TimeSeriesFilterRatio // *TimeSeriesQuery_TimeSeriesQueryLanguage @@ -404,7 +403,6 @@ type TimeSeriesFilter struct { // Selects an optional time series filter. // // Types that are assignable to OutputFilter: - // // *TimeSeriesFilter_PickTimeSeriesFilter // *TimeSeriesFilter_StatisticalTimeSeriesFilter OutputFilter isTimeSeriesFilter_OutputFilter `protobuf_oneof:"output_filter"` @@ -524,7 +522,6 @@ type TimeSeriesFilterRatio struct { // computing the ratio. // // Types that are assignable to OutputFilter: - // // *TimeSeriesFilterRatio_PickTimeSeriesFilter // *TimeSeriesFilterRatio_StatisticalTimeSeriesFilter OutputFilter isTimeSeriesFilterRatio_OutputFilter `protobuf_oneof:"output_filter"` diff --git a/monitoring/dashboard/apiv1/dashboardpb/scorecard.pb.go b/monitoring/dashboard/apiv1/dashboardpb/scorecard.pb.go index 170950e38194..6b21356504ae 100644 --- a/monitoring/dashboard/apiv1/dashboardpb/scorecard.pb.go +++ b/monitoring/dashboard/apiv1/dashboardpb/scorecard.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/monitoring/dashboard/v1/scorecard.proto package dashboardpb @@ -51,7 +51,6 @@ type Scorecard struct { // neither is included - then a default scorecard is shown. // // Types that are assignable to DataView: - // // *Scorecard_GaugeView_ // *Scorecard_SparkChartView_ DataView isScorecard_DataView `protobuf_oneof:"data_view"` @@ -66,31 +65,26 @@ type Scorecard struct { // As an example, consider a scorecard with the following four thresholds: // // ``` - // - // { - // value: 90, - // category: 'DANGER', - // trigger: 'ABOVE', - // }, - // - // { - // value: 70, - // category: 'WARNING', - // trigger: 'ABOVE', - // }, - // - // { - // value: 10, - // category: 'DANGER', - // trigger: 'BELOW', - // }, - // - // { - // value: 20, - // category: 'WARNING', - // trigger: 'BELOW', - // } - // + // { + // value: 90, + // category: 'DANGER', + // trigger: 'ABOVE', + // }, + // { + // value: 70, + // category: 'WARNING', + // trigger: 'ABOVE', + // }, + // { + // value: 10, + // category: 'DANGER', + // trigger: 'BELOW', + // }, + // { + // value: 20, + // category: 'WARNING', + // trigger: 'BELOW', + // } // ``` // // Then: values less than or equal to 10 would put the scorecard in a DANGER diff --git a/monitoring/dashboard/apiv1/dashboardpb/service.pb.go b/monitoring/dashboard/apiv1/dashboardpb/service.pb.go index 61f1ff079816..90f0900c7b4c 100644 --- a/monitoring/dashboard/apiv1/dashboardpb/service.pb.go +++ b/monitoring/dashboard/apiv1/dashboardpb/service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/monitoring/dashboard/v1/service.proto package dashboardpb diff --git a/monitoring/dashboard/apiv1/dashboardpb/table.pb.go b/monitoring/dashboard/apiv1/dashboardpb/table.pb.go index 303358de5e76..b3918f7583c6 100644 --- a/monitoring/dashboard/apiv1/dashboardpb/table.pb.go +++ b/monitoring/dashboard/apiv1/dashboardpb/table.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/monitoring/dashboard/v1/table.proto package dashboardpb diff --git a/monitoring/dashboard/apiv1/dashboardpb/table_display_options.pb.go b/monitoring/dashboard/apiv1/dashboardpb/table_display_options.pb.go index ce69ddb0ad36..c3a54a2802b7 100644 --- a/monitoring/dashboard/apiv1/dashboardpb/table_display_options.pb.go +++ b/monitoring/dashboard/apiv1/dashboardpb/table_display_options.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/monitoring/dashboard/v1/table_display_options.proto package dashboardpb diff --git a/monitoring/dashboard/apiv1/dashboardpb/text.pb.go b/monitoring/dashboard/apiv1/dashboardpb/text.pb.go index f2ca6a29c29c..4a374998b9e6 100644 --- a/monitoring/dashboard/apiv1/dashboardpb/text.pb.go +++ b/monitoring/dashboard/apiv1/dashboardpb/text.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/monitoring/dashboard/v1/text.proto package dashboardpb diff --git a/monitoring/dashboard/apiv1/dashboardpb/widget.pb.go b/monitoring/dashboard/apiv1/dashboardpb/widget.pb.go index 69be23e05f18..9d11c222d2cb 100644 --- a/monitoring/dashboard/apiv1/dashboardpb/widget.pb.go +++ b/monitoring/dashboard/apiv1/dashboardpb/widget.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/monitoring/dashboard/v1/widget.proto package dashboardpb @@ -49,7 +49,6 @@ type Widget struct { // Content defines the component used to populate the widget. // // Types that are assignable to Content: - // // *Widget_XyChart // *Widget_Scorecard // *Widget_Text diff --git a/monitoring/dashboard/apiv1/dashboardpb/xychart.pb.go b/monitoring/dashboard/apiv1/dashboardpb/xychart.pb.go index 6bc223cb4480..176e18f53920 100644 --- a/monitoring/dashboard/apiv1/dashboardpb/xychart.pb.go +++ b/monitoring/dashboard/apiv1/dashboardpb/xychart.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/monitoring/dashboard/v1/xychart.proto package dashboardpb diff --git a/monitoring/dashboard/apiv1/dashboards_client.go b/monitoring/dashboard/apiv1/dashboards_client.go index 0bcc6cdc901e..36b96390db11 100644 --- a/monitoring/dashboard/apiv1/dashboards_client.go +++ b/monitoring/dashboard/apiv1/dashboards_client.go @@ -17,21 +17,27 @@ package dashboard import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" dashboardpb "cloud.google.com/go/monitoring/dashboard/apiv1/dashboardpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -90,6 +96,36 @@ func defaultDashboardsCallOptions() *DashboardsCallOptions { } } +func defaultDashboardsRESTCallOptions() *DashboardsCallOptions { + return &DashboardsCallOptions{ + CreateDashboard: []gax.CallOption{}, + ListDashboards: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusInternalServerError) + }), + }, + GetDashboard: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusInternalServerError) + }), + }, + DeleteDashboard: []gax.CallOption{}, + UpdateDashboard: []gax.CallOption{}, + } +} + // internalDashboardsClient is an interface that defines the methods available from Cloud Monitoring API. type internalDashboardsClient interface { Close() error @@ -262,6 +298,75 @@ func (c *dashboardsGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type dashboardsRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing DashboardsClient + CallOptions **DashboardsCallOptions +} + +// NewDashboardsRESTClient creates a new dashboards service rest client. +// +// Manages Stackdriver dashboards. A dashboard is an arrangement of data display +// widgets in a specific layout. +func NewDashboardsRESTClient(ctx context.Context, opts ...option.ClientOption) (*DashboardsClient, error) { + clientOpts := append(defaultDashboardsRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultDashboardsRESTCallOptions() + c := &dashboardsRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &DashboardsClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultDashboardsRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://monitoring.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://monitoring.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://monitoring.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *dashboardsRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *dashboardsRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *dashboardsRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *dashboardsGRPCClient) CreateDashboard(ctx context.Context, req *dashboardpb.CreateDashboardRequest, opts ...gax.CallOption) (*dashboardpb.Dashboard, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) @@ -391,6 +496,345 @@ func (c *dashboardsGRPCClient) UpdateDashboard(ctx context.Context, req *dashboa return resp, nil } +// CreateDashboard creates a new custom dashboard. For examples on how you can use this API to create dashboards, see Managing dashboards by API (at https://cloud.google.com/monitoring/dashboards/api-dashboard). +// This method requires the monitoring.dashboards.create permission on the specified project. For more information about permissions, see Cloud Identity and Access Management (at https://cloud.google.com/iam). +func (c *dashboardsRESTClient) CreateDashboard(ctx context.Context, req *dashboardpb.CreateDashboardRequest, opts ...gax.CallOption) (*dashboardpb.Dashboard, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetDashboard() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/dashboards", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateDashboard[0:len((*c.CallOptions).CreateDashboard):len((*c.CallOptions).CreateDashboard)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dashboardpb.Dashboard{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListDashboards lists the existing dashboards. +// +// This method requires the monitoring.dashboards.list permission +// on the specified project. For more information, see +// Cloud Identity and Access Management (at https://cloud.google.com/iam). +func (c *dashboardsRESTClient) ListDashboards(ctx context.Context, req *dashboardpb.ListDashboardsRequest, opts ...gax.CallOption) *DashboardIterator { + it := &DashboardIterator{} + req = proto.Clone(req).(*dashboardpb.ListDashboardsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*dashboardpb.Dashboard, string, error) { + resp := &dashboardpb.ListDashboardsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/dashboards", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetDashboards(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetDashboard fetches a specific dashboard. +// +// This method requires the monitoring.dashboards.get permission +// on the specified dashboard. For more information, see +// Cloud Identity and Access Management (at https://cloud.google.com/iam). +func (c *dashboardsRESTClient) GetDashboard(ctx context.Context, req *dashboardpb.GetDashboardRequest, opts ...gax.CallOption) (*dashboardpb.Dashboard, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetDashboard[0:len((*c.CallOptions).GetDashboard):len((*c.CallOptions).GetDashboard)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dashboardpb.Dashboard{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteDashboard deletes an existing custom dashboard. +// +// This method requires the monitoring.dashboards.delete permission +// on the specified dashboard. For more information, see +// Cloud Identity and Access Management (at https://cloud.google.com/iam). +func (c *dashboardsRESTClient) DeleteDashboard(ctx context.Context, req *dashboardpb.DeleteDashboardRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// UpdateDashboard replaces an existing custom dashboard with a new definition. +// +// This method requires the monitoring.dashboards.update permission +// on the specified dashboard. For more information, see +// Cloud Identity and Access Management (at https://cloud.google.com/iam). +func (c *dashboardsRESTClient) UpdateDashboard(ctx context.Context, req *dashboardpb.UpdateDashboardRequest, opts ...gax.CallOption) (*dashboardpb.Dashboard, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetDashboard() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetDashboard().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "dashboard.name", url.QueryEscape(req.GetDashboard().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateDashboard[0:len((*c.CallOptions).UpdateDashboard):len((*c.CallOptions).UpdateDashboard)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &dashboardpb.Dashboard{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + // DashboardIterator manages a stream of *dashboardpb.Dashboard. type DashboardIterator struct { items []*dashboardpb.Dashboard diff --git a/monitoring/dashboard/apiv1/dashboards_client_example_test.go b/monitoring/dashboard/apiv1/dashboards_client_example_test.go index fd21379b0622..9f9c60a0007c 100644 --- a/monitoring/dashboard/apiv1/dashboards_client_example_test.go +++ b/monitoring/dashboard/apiv1/dashboards_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewDashboardsClient() { _ = c } +func ExampleNewDashboardsRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := dashboard.NewDashboardsRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleDashboardsClient_CreateDashboard() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/monitoring/dashboard/apiv1/doc.go b/monitoring/dashboard/apiv1/doc.go index 8b8f577d9383..ff2a42054cc4 100644 --- a/monitoring/dashboard/apiv1/doc.go +++ b/monitoring/dashboard/apiv1/doc.go @@ -80,6 +80,8 @@ package dashboard // import "cloud.google.com/go/monitoring/dashboard/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -171,3 +173,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/monitoring/dashboard/apiv1/gapic_metadata.json b/monitoring/dashboard/apiv1/gapic_metadata.json index 28ca5eb4c1ce..8e22576143bc 100644 --- a/monitoring/dashboard/apiv1/gapic_metadata.json +++ b/monitoring/dashboard/apiv1/gapic_metadata.json @@ -36,6 +36,36 @@ ] } } + }, + "rest": { + "libraryClient": "DashboardsClient", + "rpcs": { + "CreateDashboard": { + "methods": [ + "CreateDashboard" + ] + }, + "DeleteDashboard": { + "methods": [ + "DeleteDashboard" + ] + }, + "GetDashboard": { + "methods": [ + "GetDashboard" + ] + }, + "ListDashboards": { + "methods": [ + "ListDashboards" + ] + }, + "UpdateDashboard": { + "methods": [ + "UpdateDashboard" + ] + } + } } } } diff --git a/monitoring/metricsscope/apiv1/doc.go b/monitoring/metricsscope/apiv1/doc.go index ae0a7d803a6a..01d13883340f 100644 --- a/monitoring/metricsscope/apiv1/doc.go +++ b/monitoring/metricsscope/apiv1/doc.go @@ -85,6 +85,8 @@ package metricsscope // import "cloud.google.com/go/monitoring/metricsscope/apiv import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -176,3 +178,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/monitoring/metricsscope/apiv1/gapic_metadata.json b/monitoring/metricsscope/apiv1/gapic_metadata.json index c89418b8a205..a7851eb8e190 100644 --- a/monitoring/metricsscope/apiv1/gapic_metadata.json +++ b/monitoring/metricsscope/apiv1/gapic_metadata.json @@ -31,6 +31,31 @@ ] } } + }, + "rest": { + "libraryClient": "MetricsScopesClient", + "rpcs": { + "CreateMonitoredProject": { + "methods": [ + "CreateMonitoredProject" + ] + }, + "DeleteMonitoredProject": { + "methods": [ + "DeleteMonitoredProject" + ] + }, + "GetMetricsScope": { + "methods": [ + "GetMetricsScope" + ] + }, + "ListMetricsScopesByMonitoredProject": { + "methods": [ + "ListMetricsScopesByMonitoredProject" + ] + } + } } } } diff --git a/monitoring/metricsscope/apiv1/metrics_scopes_client.go b/monitoring/metricsscope/apiv1/metrics_scopes_client.go index 73a5b0702ac7..8bbd7b520832 100644 --- a/monitoring/metricsscope/apiv1/metrics_scopes_client.go +++ b/monitoring/metricsscope/apiv1/metrics_scopes_client.go @@ -17,9 +17,12 @@ package metricsscope import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,12 +30,15 @@ import ( lroauto "cloud.google.com/go/longrunning/autogen" metricsscopepb "cloud.google.com/go/monitoring/metricsscope/apiv1/metricsscopepb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" ) var newMetricsScopesClientHook clientHook @@ -66,6 +72,15 @@ func defaultMetricsScopesCallOptions() *MetricsScopesCallOptions { } } +func defaultMetricsScopesRESTCallOptions() *MetricsScopesCallOptions { + return &MetricsScopesCallOptions{ + GetMetricsScope: []gax.CallOption{}, + ListMetricsScopesByMonitoredProject: []gax.CallOption{}, + CreateMonitoredProject: []gax.CallOption{}, + DeleteMonitoredProject: []gax.CallOption{}, + } +} + // internalMetricsScopesClient is an interface that defines the methods available from Cloud Monitoring API. type internalMetricsScopesClient interface { Close() error @@ -253,6 +268,90 @@ func (c *metricsScopesGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type metricsScopesRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing MetricsScopesClient + CallOptions **MetricsScopesCallOptions +} + +// NewMetricsScopesRESTClient creates a new metrics scopes rest client. +// +// Manages Cloud Monitoring Metrics Scopes, and the monitoring of Google Cloud +// projects and AWS accounts. +func NewMetricsScopesRESTClient(ctx context.Context, opts ...option.ClientOption) (*MetricsScopesClient, error) { + clientOpts := append(defaultMetricsScopesRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultMetricsScopesRESTCallOptions() + c := &metricsScopesRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &MetricsScopesClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultMetricsScopesRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://monitoring.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://monitoring.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://monitoring.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *metricsScopesRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *metricsScopesRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *metricsScopesRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *metricsScopesGRPCClient) GetMetricsScope(ctx context.Context, req *metricsscopepb.GetMetricsScopeRequest, opts ...gax.CallOption) (*metricsscopepb.MetricsScope, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -323,9 +422,259 @@ func (c *metricsScopesGRPCClient) DeleteMonitoredProject(ctx context.Context, re }, nil } +// GetMetricsScope returns a specific Metrics Scope. +func (c *metricsScopesRESTClient) GetMetricsScope(ctx context.Context, req *metricsscopepb.GetMetricsScopeRequest, opts ...gax.CallOption) (*metricsscopepb.MetricsScope, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetMetricsScope[0:len((*c.CallOptions).GetMetricsScope):len((*c.CallOptions).GetMetricsScope)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &metricsscopepb.MetricsScope{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListMetricsScopesByMonitoredProject returns a list of every Metrics Scope that a specific MonitoredProject +// has been added to. The metrics scope representing the specified monitored +// project will always be the first entry in the response. +func (c *metricsScopesRESTClient) ListMetricsScopesByMonitoredProject(ctx context.Context, req *metricsscopepb.ListMetricsScopesByMonitoredProjectRequest, opts ...gax.CallOption) (*metricsscopepb.ListMetricsScopesByMonitoredProjectResponse, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/locations/global/metricsScopes:listMetricsScopesByMonitoredProject") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("monitoredResourceContainer", fmt.Sprintf("%v", req.GetMonitoredResourceContainer())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).ListMetricsScopesByMonitoredProject[0:len((*c.CallOptions).ListMetricsScopesByMonitoredProject):len((*c.CallOptions).ListMetricsScopesByMonitoredProject)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &metricsscopepb.ListMetricsScopesByMonitoredProjectResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateMonitoredProject adds a MonitoredProject with the given project ID +// to the specified Metrics Scope. +func (c *metricsScopesRESTClient) CreateMonitoredProject(ctx context.Context, req *metricsscopepb.CreateMonitoredProjectRequest, opts ...gax.CallOption) (*CreateMonitoredProjectOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetMonitoredProject() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/projects", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateMonitoredProjectOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteMonitoredProject deletes a MonitoredProject from the specified Metrics Scope. +func (c *metricsScopesRESTClient) DeleteMonitoredProject(ctx context.Context, req *metricsscopepb.DeleteMonitoredProjectRequest, opts ...gax.CallOption) (*DeleteMonitoredProjectOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteMonitoredProjectOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + // CreateMonitoredProjectOperation manages a long-running operation from CreateMonitoredProject. type CreateMonitoredProjectOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateMonitoredProjectOperation returns a new CreateMonitoredProjectOperation from a given name. @@ -336,10 +685,21 @@ func (c *metricsScopesGRPCClient) CreateMonitoredProjectOperation(name string) * } } +// CreateMonitoredProjectOperation returns a new CreateMonitoredProjectOperation from a given name. +// The name must be that of a previously created CreateMonitoredProjectOperation, possibly from a different process. +func (c *metricsScopesRESTClient) CreateMonitoredProjectOperation(name string) *CreateMonitoredProjectOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateMonitoredProjectOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateMonitoredProjectOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*metricsscopepb.MonitoredProject, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp metricsscopepb.MonitoredProject if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -357,6 +717,7 @@ func (op *CreateMonitoredProjectOperation) Wait(ctx context.Context, opts ...gax // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateMonitoredProjectOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*metricsscopepb.MonitoredProject, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp metricsscopepb.MonitoredProject if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -394,7 +755,8 @@ func (op *CreateMonitoredProjectOperation) Name() string { // DeleteMonitoredProjectOperation manages a long-running operation from DeleteMonitoredProject. type DeleteMonitoredProjectOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteMonitoredProjectOperation returns a new DeleteMonitoredProjectOperation from a given name. @@ -405,10 +767,21 @@ func (c *metricsScopesGRPCClient) DeleteMonitoredProjectOperation(name string) * } } +// DeleteMonitoredProjectOperation returns a new DeleteMonitoredProjectOperation from a given name. +// The name must be that of a previously created DeleteMonitoredProjectOperation, possibly from a different process. +func (c *metricsScopesRESTClient) DeleteMonitoredProjectOperation(name string) *DeleteMonitoredProjectOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteMonitoredProjectOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteMonitoredProjectOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -422,6 +795,7 @@ func (op *DeleteMonitoredProjectOperation) Wait(ctx context.Context, opts ...gax // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteMonitoredProjectOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } diff --git a/monitoring/metricsscope/apiv1/metrics_scopes_client_example_test.go b/monitoring/metricsscope/apiv1/metrics_scopes_client_example_test.go index cc86312973a9..36c5716cb4cf 100644 --- a/monitoring/metricsscope/apiv1/metrics_scopes_client_example_test.go +++ b/monitoring/metricsscope/apiv1/metrics_scopes_client_example_test.go @@ -40,6 +40,23 @@ func ExampleNewMetricsScopesClient() { _ = c } +func ExampleNewMetricsScopesRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := metricsscope.NewMetricsScopesRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleMetricsScopesClient_GetMetricsScope() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/monitoring/metricsscope/apiv1/metricsscopepb/metrics_scope.pb.go b/monitoring/metricsscope/apiv1/metricsscopepb/metrics_scope.pb.go index a7c69b93b282..7941cff52f3b 100644 --- a/monitoring/metricsscope/apiv1/metricsscopepb/metrics_scope.pb.go +++ b/monitoring/metricsscope/apiv1/metricsscopepb/metrics_scope.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/monitoring/metricsscope/v1/metrics_scope.proto package metricsscopepb diff --git a/monitoring/metricsscope/apiv1/metricsscopepb/metrics_scopes.pb.go b/monitoring/metricsscope/apiv1/metricsscopepb/metrics_scopes.pb.go index 1b272e30e9f6..b027b96ae570 100644 --- a/monitoring/metricsscope/apiv1/metricsscopepb/metrics_scopes.pb.go +++ b/monitoring/metricsscope/apiv1/metricsscopepb/metrics_scopes.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/monitoring/metricsscope/v1/metrics_scopes.proto package metricsscopepb diff --git a/networkconnectivity/apiv1/doc.go b/networkconnectivity/apiv1/doc.go index 393e07f9d038..da8067611a92 100644 --- a/networkconnectivity/apiv1/doc.go +++ b/networkconnectivity/apiv1/doc.go @@ -86,6 +86,8 @@ package networkconnectivity // import "cloud.google.com/go/networkconnectivity/a import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -174,3 +176,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/networkconnectivity/apiv1/gapic_metadata.json b/networkconnectivity/apiv1/gapic_metadata.json index 2d2135a1cac7..dfbc5270b392 100644 --- a/networkconnectivity/apiv1/gapic_metadata.json +++ b/networkconnectivity/apiv1/gapic_metadata.json @@ -106,6 +106,106 @@ ] } } + }, + "rest": { + "libraryClient": "HubClient", + "rpcs": { + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "CreateHub": { + "methods": [ + "CreateHub" + ] + }, + "CreateSpoke": { + "methods": [ + "CreateSpoke" + ] + }, + "DeleteHub": { + "methods": [ + "DeleteHub" + ] + }, + "DeleteOperation": { + "methods": [ + "DeleteOperation" + ] + }, + "DeleteSpoke": { + "methods": [ + "DeleteSpoke" + ] + }, + "GetHub": { + "methods": [ + "GetHub" + ] + }, + "GetIamPolicy": { + "methods": [ + "GetIamPolicy" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "GetSpoke": { + "methods": [ + "GetSpoke" + ] + }, + "ListHubs": { + "methods": [ + "ListHubs" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "ListSpokes": { + "methods": [ + "ListSpokes" + ] + }, + "SetIamPolicy": { + "methods": [ + "SetIamPolicy" + ] + }, + "TestIamPermissions": { + "methods": [ + "TestIamPermissions" + ] + }, + "UpdateHub": { + "methods": [ + "UpdateHub" + ] + }, + "UpdateSpoke": { + "methods": [ + "UpdateSpoke" + ] + } + } } } }, @@ -180,6 +280,76 @@ ] } } + }, + "rest": { + "libraryClient": "PolicyBasedRoutingClient", + "rpcs": { + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "CreatePolicyBasedRoute": { + "methods": [ + "CreatePolicyBasedRoute" + ] + }, + "DeleteOperation": { + "methods": [ + "DeleteOperation" + ] + }, + "DeletePolicyBasedRoute": { + "methods": [ + "DeletePolicyBasedRoute" + ] + }, + "GetIamPolicy": { + "methods": [ + "GetIamPolicy" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "GetPolicyBasedRoute": { + "methods": [ + "GetPolicyBasedRoute" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "ListPolicyBasedRoutes": { + "methods": [ + "ListPolicyBasedRoutes" + ] + }, + "SetIamPolicy": { + "methods": [ + "SetIamPolicy" + ] + }, + "TestIamPermissions": { + "methods": [ + "TestIamPermissions" + ] + } + } } } } diff --git a/networkconnectivity/apiv1/hub_client.go b/networkconnectivity/apiv1/hub_client.go index 7fa3f0edde45..bac4da7a9f41 100644 --- a/networkconnectivity/apiv1/hub_client.go +++ b/networkconnectivity/apiv1/hub_client.go @@ -17,9 +17,12 @@ package networkconnectivity import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,16 +30,19 @@ import ( lroauto "cloud.google.com/go/longrunning/autogen" networkconnectivitypb "cloud.google.com/go/networkconnectivity/apiv1/networkconnectivitypb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" iampb "google.golang.org/genproto/googleapis/iam/v1" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -141,6 +147,66 @@ func defaultHubCallOptions() *HubCallOptions { } } +func defaultHubRESTCallOptions() *HubCallOptions { + return &HubCallOptions{ + ListHubs: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetHub: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateHub: []gax.CallOption{}, + UpdateHub: []gax.CallOption{}, + DeleteHub: []gax.CallOption{}, + ListSpokes: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetSpoke: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateSpoke: []gax.CallOption{}, + UpdateSpoke: []gax.CallOption{}, + DeleteSpoke: []gax.CallOption{}, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + GetIamPolicy: []gax.CallOption{}, + SetIamPolicy: []gax.CallOption{}, + TestIamPermissions: []gax.CallOption{}, + CancelOperation: []gax.CallOption{}, + DeleteOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalHubClient is an interface that defines the methods available from Network Connectivity API. type internalHubClient interface { Close() error @@ -467,6 +533,91 @@ func (c *hubGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type hubRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing HubClient + CallOptions **HubCallOptions +} + +// NewHubRESTClient creates a new hub service rest client. +// +// Network Connectivity Center is a hub-and-spoke abstraction for network +// connectivity management in Google Cloud. It reduces operational complexity +// through a simple, centralized connectivity management model. +func NewHubRESTClient(ctx context.Context, opts ...option.ClientOption) (*HubClient, error) { + clientOpts := append(defaultHubRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultHubRESTCallOptions() + c := &hubRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &HubClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultHubRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://networkconnectivity.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://networkconnectivity.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://networkconnectivity.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *hubRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *hubRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *hubRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *hubGRPCClient) ListHubs(ctx context.Context, req *networkconnectivitypb.ListHubsRequest, opts ...gax.CallOption) *HubIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -946,122 +1097,1472 @@ func (c *hubGRPCClient) ListOperations(ctx context.Context, req *longrunningpb.L return it } -// CreateHubOperation manages a long-running operation from CreateHub. -type CreateHubOperation struct { - lro *longrunning.Operation -} +// ListHubs lists the Network Connectivity Center hubs associated with a given project. +func (c *hubRESTClient) ListHubs(ctx context.Context, req *networkconnectivitypb.ListHubsRequest, opts ...gax.CallOption) *HubIterator { + it := &HubIterator{} + req = proto.Clone(req).(*networkconnectivitypb.ListHubsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*networkconnectivitypb.Hub, string, error) { + resp := &networkconnectivitypb.ListHubsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/hubs", req.GetParent()) -// CreateHubOperation returns a new CreateHubOperation from a given name. -// The name must be that of a previously created CreateHubOperation, possibly from a different process. -func (c *hubGRPCClient) CreateHubOperation(name string) *CreateHubOperation { - return &CreateHubOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *CreateHubOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*networkconnectivitypb.Hub, error) { - var resp networkconnectivitypb.Hub - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { - return nil, err + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetHubs(), resp.GetNextPageToken(), nil } - return &resp, nil -} -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *CreateHubOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*networkconnectivitypb.Hub, error) { - var resp networkconnectivitypb.Hub - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { - return nil, err - } - if !op.Done() { - return nil, 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 } - return &resp, nil + + it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it } -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *CreateHubOperation) Metadata() (*networkconnectivitypb.OperationMetadata, error) { - var meta networkconnectivitypb.OperationMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { +// GetHub gets details about a Network Connectivity Center hub. +func (c *hubRESTClient) GetHub(ctx context.Context, req *networkconnectivitypb.GetHubRequest, opts ...gax.CallOption) (*networkconnectivitypb.Hub, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - return &meta, nil -} + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) -// Done reports whether the long-running operation has completed. -func (op *CreateHubOperation) Done() bool { - return op.lro.Done() -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") -// 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 *CreateHubOperation) Name() string { - return op.lro.Name() -} + baseUrl.RawQuery = params.Encode() -// CreateSpokeOperation manages a long-running operation from CreateSpoke. -type CreateSpokeOperation struct { - lro *longrunning.Operation -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) -// CreateSpokeOperation returns a new CreateSpokeOperation from a given name. -// The name must be that of a previously created CreateSpokeOperation, possibly from a different process. -func (c *hubGRPCClient) CreateSpokeOperation(name string) *CreateSpokeOperation { - return &CreateSpokeOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetHub[0:len((*c.CallOptions).GetHub):len((*c.CallOptions).GetHub)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &networkconnectivitypb.Hub{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e } + return resp, nil } -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *CreateSpokeOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*networkconnectivitypb.Spoke, error) { - var resp networkconnectivitypb.Spoke - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { +// CreateHub creates a new Network Connectivity Center hub in the specified project. +func (c *hubRESTClient) CreateHub(ctx context.Context, req *networkconnectivitypb.CreateHubRequest, opts ...gax.CallOption) (*CreateHubOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetHub() + jsonReq, err := m.Marshal(body) + if err != nil { return nil, err } - return &resp, nil -} -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *CreateSpokeOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*networkconnectivitypb.Spoke, error) { - var resp networkconnectivitypb.Spoke - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - if !op.Done() { - return nil, nil + baseUrl.Path += fmt.Sprintf("/v1/%v/hubs", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("hubId", fmt.Sprintf("%v", req.GetHubId())) + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } - return &resp, nil -} -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateHubOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateHub updates the description and/or labels of a Network Connectivity Center +// hub. +func (c *hubRESTClient) UpdateHub(ctx context.Context, req *networkconnectivitypb.UpdateHubRequest, opts ...gax.CallOption) (*UpdateHubOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetHub() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetHub().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "hub.name", url.QueryEscape(req.GetHub().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateHubOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteHub deletes a Network Connectivity Center hub. +func (c *hubRESTClient) DeleteHub(ctx context.Context, req *networkconnectivitypb.DeleteHubRequest, opts ...gax.CallOption) (*DeleteHubOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteHubOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListSpokes lists the Network Connectivity Center spokes in a specified project and +// location. +func (c *hubRESTClient) ListSpokes(ctx context.Context, req *networkconnectivitypb.ListSpokesRequest, opts ...gax.CallOption) *SpokeIterator { + it := &SpokeIterator{} + req = proto.Clone(req).(*networkconnectivitypb.ListSpokesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*networkconnectivitypb.Spoke, string, error) { + resp := &networkconnectivitypb.ListSpokesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/spokes", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetSpokes(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetSpoke gets details about a Network Connectivity Center spoke. +func (c *hubRESTClient) GetSpoke(ctx context.Context, req *networkconnectivitypb.GetSpokeRequest, opts ...gax.CallOption) (*networkconnectivitypb.Spoke, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetSpoke[0:len((*c.CallOptions).GetSpoke):len((*c.CallOptions).GetSpoke)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &networkconnectivitypb.Spoke{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateSpoke creates a Network Connectivity Center spoke. +func (c *hubRESTClient) CreateSpoke(ctx context.Context, req *networkconnectivitypb.CreateSpokeRequest, opts ...gax.CallOption) (*CreateSpokeOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetSpoke() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/spokes", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + params.Add("spokeId", fmt.Sprintf("%v", req.GetSpokeId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateSpokeOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateSpoke updates the parameters of a Network Connectivity Center spoke. +func (c *hubRESTClient) UpdateSpoke(ctx context.Context, req *networkconnectivitypb.UpdateSpokeRequest, opts ...gax.CallOption) (*UpdateSpokeOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetSpoke() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetSpoke().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "spoke.name", url.QueryEscape(req.GetSpoke().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateSpokeOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteSpoke deletes a Network Connectivity Center spoke. +func (c *hubRESTClient) DeleteSpoke(ctx context.Context, req *networkconnectivitypb.DeleteSpokeRequest, opts ...gax.CallOption) (*DeleteSpokeOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteSpokeOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetLocation gets information about a location. +func (c *hubRESTClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *hubRESTClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetIamPolicy gets the access control policy for a resource. Returns an empty policy +// if the resource exists and does not have a policy set. +func (c *hubRESTClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:getIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetOptions().GetRequestedPolicyVersion() != 0 { + params.Add("options.requestedPolicyVersion", fmt.Sprintf("%v", req.GetOptions().GetRequestedPolicyVersion())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SetIamPolicy sets the access control policy on the specified resource. Replaces +// any existing policy. +// +// Can return NOT_FOUND, INVALID_ARGUMENT, and PERMISSION_DENIED +// errors. +func (c *hubRESTClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:setIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// TestIamPermissions returns permissions that a caller has on the specified resource. If the +// resource does not exist, this will return an empty set of +// permissions, not a NOT_FOUND error. +// +// Note: This operation is designed to be used for building +// permission-aware UIs and command-line tools, not for authorization +// checking. This operation may “fail open” without warning. +func (c *hubRESTClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:testIamPermissions", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.TestIamPermissionsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *hubRESTClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// DeleteOperation is a utility method from google.longrunning.Operations. +func (c *hubRESTClient) DeleteOperation(ctx context.Context, req *longrunningpb.DeleteOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *hubRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *hubRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CreateHubOperation manages a long-running operation from CreateHub. +type CreateHubOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateHubOperation returns a new CreateHubOperation from a given name. +// The name must be that of a previously created CreateHubOperation, possibly from a different process. +func (c *hubGRPCClient) CreateHubOperation(name string) *CreateHubOperation { + return &CreateHubOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateHubOperation returns a new CreateHubOperation from a given name. +// The name must be that of a previously created CreateHubOperation, possibly from a different process. +func (c *hubRESTClient) CreateHubOperation(name string) *CreateHubOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateHubOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CreateHubOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*networkconnectivitypb.Hub, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp networkconnectivitypb.Hub + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *CreateHubOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*networkconnectivitypb.Hub, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp networkconnectivitypb.Hub + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *CreateHubOperation) Metadata() (*networkconnectivitypb.OperationMetadata, error) { + var meta networkconnectivitypb.OperationMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *CreateHubOperation) Done() bool { + return op.lro.Done() +} + +// 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 *CreateHubOperation) Name() string { + return op.lro.Name() +} + +// CreateSpokeOperation manages a long-running operation from CreateSpoke. +type CreateSpokeOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateSpokeOperation returns a new CreateSpokeOperation from a given name. +// The name must be that of a previously created CreateSpokeOperation, possibly from a different process. +func (c *hubGRPCClient) CreateSpokeOperation(name string) *CreateSpokeOperation { + return &CreateSpokeOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateSpokeOperation returns a new CreateSpokeOperation from a given name. +// The name must be that of a previously created CreateSpokeOperation, possibly from a different process. +func (c *hubRESTClient) CreateSpokeOperation(name string) *CreateSpokeOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateSpokeOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CreateSpokeOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*networkconnectivitypb.Spoke, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp networkconnectivitypb.Spoke + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *CreateSpokeOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*networkconnectivitypb.Spoke, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp networkconnectivitypb.Spoke + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. // If the metadata is not available, the returned metadata and error are both nil. func (op *CreateSpokeOperation) Metadata() (*networkconnectivitypb.OperationMetadata, error) { var meta networkconnectivitypb.OperationMetadata @@ -1086,7 +2587,8 @@ func (op *CreateSpokeOperation) Name() string { // DeleteHubOperation manages a long-running operation from DeleteHub. type DeleteHubOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteHubOperation returns a new DeleteHubOperation from a given name. @@ -1097,10 +2599,21 @@ func (c *hubGRPCClient) DeleteHubOperation(name string) *DeleteHubOperation { } } +// DeleteHubOperation returns a new DeleteHubOperation from a given name. +// The name must be that of a previously created DeleteHubOperation, possibly from a different process. +func (c *hubRESTClient) DeleteHubOperation(name string) *DeleteHubOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteHubOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteHubOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -1114,6 +2627,7 @@ func (op *DeleteHubOperation) Wait(ctx context.Context, opts ...gax.CallOption) // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteHubOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -1144,7 +2658,8 @@ func (op *DeleteHubOperation) Name() string { // DeleteSpokeOperation manages a long-running operation from DeleteSpoke. type DeleteSpokeOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteSpokeOperation returns a new DeleteSpokeOperation from a given name. @@ -1155,10 +2670,21 @@ func (c *hubGRPCClient) DeleteSpokeOperation(name string) *DeleteSpokeOperation } } +// DeleteSpokeOperation returns a new DeleteSpokeOperation from a given name. +// The name must be that of a previously created DeleteSpokeOperation, possibly from a different process. +func (c *hubRESTClient) DeleteSpokeOperation(name string) *DeleteSpokeOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteSpokeOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteSpokeOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -1172,6 +2698,7 @@ func (op *DeleteSpokeOperation) Wait(ctx context.Context, opts ...gax.CallOption // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteSpokeOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -1202,7 +2729,8 @@ func (op *DeleteSpokeOperation) Name() string { // UpdateHubOperation manages a long-running operation from UpdateHub. type UpdateHubOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateHubOperation returns a new UpdateHubOperation from a given name. @@ -1213,10 +2741,21 @@ func (c *hubGRPCClient) UpdateHubOperation(name string) *UpdateHubOperation { } } +// UpdateHubOperation returns a new UpdateHubOperation from a given name. +// The name must be that of a previously created UpdateHubOperation, possibly from a different process. +func (c *hubRESTClient) UpdateHubOperation(name string) *UpdateHubOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateHubOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateHubOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*networkconnectivitypb.Hub, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp networkconnectivitypb.Hub if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1234,6 +2773,7 @@ func (op *UpdateHubOperation) Wait(ctx context.Context, opts ...gax.CallOption) // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateHubOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*networkconnectivitypb.Hub, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp networkconnectivitypb.Hub if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1271,7 +2811,8 @@ func (op *UpdateHubOperation) Name() string { // UpdateSpokeOperation manages a long-running operation from UpdateSpoke. type UpdateSpokeOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateSpokeOperation returns a new UpdateSpokeOperation from a given name. @@ -1282,10 +2823,21 @@ func (c *hubGRPCClient) UpdateSpokeOperation(name string) *UpdateSpokeOperation } } +// UpdateSpokeOperation returns a new UpdateSpokeOperation from a given name. +// The name must be that of a previously created UpdateSpokeOperation, possibly from a different process. +func (c *hubRESTClient) UpdateSpokeOperation(name string) *UpdateSpokeOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateSpokeOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateSpokeOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*networkconnectivitypb.Spoke, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp networkconnectivitypb.Spoke if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1303,6 +2855,7 @@ func (op *UpdateSpokeOperation) Wait(ctx context.Context, opts ...gax.CallOption // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateSpokeOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*networkconnectivitypb.Spoke, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp networkconnectivitypb.Spoke if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/networkconnectivity/apiv1/hub_client_example_test.go b/networkconnectivity/apiv1/hub_client_example_test.go index 928a5b5fbeb6..afc933564bad 100644 --- a/networkconnectivity/apiv1/hub_client_example_test.go +++ b/networkconnectivity/apiv1/hub_client_example_test.go @@ -44,6 +44,23 @@ func ExampleNewHubClient() { _ = c } +func ExampleNewHubRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := networkconnectivity.NewHubRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleHubClient_ListHubs() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/networkconnectivity/apiv1/networkconnectivitypb/common.pb.go b/networkconnectivity/apiv1/networkconnectivitypb/common.pb.go index 62a754af8484..f77941517fb7 100644 --- a/networkconnectivity/apiv1/networkconnectivitypb/common.pb.go +++ b/networkconnectivity/apiv1/networkconnectivitypb/common.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/networkconnectivity/v1/common.proto package networkconnectivitypb diff --git a/networkconnectivity/apiv1/networkconnectivitypb/hub.pb.go b/networkconnectivity/apiv1/networkconnectivitypb/hub.pb.go index 7f5747ff6afb..eb76f76331f9 100644 --- a/networkconnectivity/apiv1/networkconnectivitypb/hub.pb.go +++ b/networkconnectivity/apiv1/networkconnectivitypb/hub.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/networkconnectivity/v1/hub.proto package networkconnectivitypb @@ -170,8 +170,7 @@ type Hub struct { // Immutable. The name of the hub. Hub names must be unique. They use the // following form: - // - // `projects/{project_number}/locations/global/hubs/{hub_id}` + // `projects/{project_number}/locations/global/hubs/{hub_id}` Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Output only. The time the hub was created. CreateTime *timestamppb.Timestamp `protobuf:"bytes,2,opt,name=create_time,json=createTime,proto3" json:"create_time,omitempty"` @@ -363,8 +362,7 @@ type Spoke struct { // Immutable. The name of the spoke. Spoke names must be unique. They use the // following form: - // - // `projects/{project_number}/locations/{region}/spokes/{spoke_id}` + // `projects/{project_number}/locations/{region}/spokes/{spoke_id}` Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Output only. The time the spoke was created. CreateTime *timestamppb.Timestamp `protobuf:"bytes,2,opt,name=create_time,json=createTime,proto3" json:"create_time,omitempty"` diff --git a/networkconnectivity/apiv1/networkconnectivitypb/policy_based_routing.pb.go b/networkconnectivity/apiv1/networkconnectivitypb/policy_based_routing.pb.go index 66a84e85a779..671724b5af2b 100644 --- a/networkconnectivity/apiv1/networkconnectivitypb/policy_based_routing.pb.go +++ b/networkconnectivity/apiv1/networkconnectivitypb/policy_based_routing.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/networkconnectivity/v1/policy_based_routing.proto package networkconnectivitypb @@ -163,12 +163,10 @@ type PolicyBasedRoute struct { // network endpoints (e.g. VMs, VPNs, and Interconnects) in the VPC. // // Types that are assignable to Target: - // // *PolicyBasedRoute_VirtualMachine_ // *PolicyBasedRoute_InterconnectAttachment_ Target isPolicyBasedRoute_Target `protobuf_oneof:"target"` // Types that are assignable to NextHop: - // // *PolicyBasedRoute_NextHopIlbIp NextHop isPolicyBasedRoute_NextHop `protobuf_oneof:"next_hop"` // Immutable. A unique name of the resource in the form of diff --git a/networkconnectivity/apiv1/policy_based_routing_client.go b/networkconnectivity/apiv1/policy_based_routing_client.go index d1d02c1e0840..905b7e115790 100644 --- a/networkconnectivity/apiv1/policy_based_routing_client.go +++ b/networkconnectivity/apiv1/policy_based_routing_client.go @@ -17,9 +17,12 @@ package networkconnectivity import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,16 +30,19 @@ import ( lroauto "cloud.google.com/go/longrunning/autogen" networkconnectivitypb "cloud.google.com/go/networkconnectivity/apiv1/networkconnectivitypb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" iampb "google.golang.org/genproto/googleapis/iam/v1" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -109,6 +115,42 @@ func defaultPolicyBasedRoutingCallOptions() *PolicyBasedRoutingCallOptions { } } +func defaultPolicyBasedRoutingRESTCallOptions() *PolicyBasedRoutingCallOptions { + return &PolicyBasedRoutingCallOptions{ + ListPolicyBasedRoutes: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetPolicyBasedRoute: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreatePolicyBasedRoute: []gax.CallOption{}, + DeletePolicyBasedRoute: []gax.CallOption{}, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + GetIamPolicy: []gax.CallOption{}, + SetIamPolicy: []gax.CallOption{}, + TestIamPermissions: []gax.CallOption{}, + CancelOperation: []gax.CallOption{}, + DeleteOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalPolicyBasedRoutingClient is an interface that defines the methods available from Network Connectivity API. type internalPolicyBasedRoutingClient interface { Close() error @@ -367,6 +409,90 @@ func (c *policyBasedRoutingGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type policyBasedRoutingRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing PolicyBasedRoutingClient + CallOptions **PolicyBasedRoutingCallOptions +} + +// NewPolicyBasedRoutingRESTClient creates a new policy based routing service rest client. +// +// Policy-Based Routing allows GCP customers to specify flexibile routing +// policies for Layer 4 traffic traversing through the connected service. +func NewPolicyBasedRoutingRESTClient(ctx context.Context, opts ...option.ClientOption) (*PolicyBasedRoutingClient, error) { + clientOpts := append(defaultPolicyBasedRoutingRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultPolicyBasedRoutingRESTCallOptions() + c := &policyBasedRoutingRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &PolicyBasedRoutingClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultPolicyBasedRoutingRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://networkconnectivity.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://networkconnectivity.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://networkconnectivity.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *policyBasedRoutingRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *policyBasedRoutingRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *policyBasedRoutingRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *policyBasedRoutingGRPCClient) ListPolicyBasedRoutes(ctx context.Context, req *networkconnectivitypb.ListPolicyBasedRoutesRequest, opts ...gax.CallOption) *PolicyBasedRouteIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -683,85 +809,985 @@ func (c *policyBasedRoutingGRPCClient) ListOperations(ctx context.Context, req * return it } -// CreatePolicyBasedRouteOperation manages a long-running operation from CreatePolicyBasedRoute. -type CreatePolicyBasedRouteOperation struct { - lro *longrunning.Operation -} +// ListPolicyBasedRoutes lists PolicyBasedRoutes in a given project and location. +func (c *policyBasedRoutingRESTClient) ListPolicyBasedRoutes(ctx context.Context, req *networkconnectivitypb.ListPolicyBasedRoutesRequest, opts ...gax.CallOption) *PolicyBasedRouteIterator { + it := &PolicyBasedRouteIterator{} + req = proto.Clone(req).(*networkconnectivitypb.ListPolicyBasedRoutesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*networkconnectivitypb.PolicyBasedRoute, string, error) { + resp := &networkconnectivitypb.ListPolicyBasedRoutesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/policyBasedRoutes", req.GetParent()) -// CreatePolicyBasedRouteOperation returns a new CreatePolicyBasedRouteOperation from a given name. -// The name must be that of a previously created CreatePolicyBasedRouteOperation, possibly from a different process. -func (c *policyBasedRoutingGRPCClient) CreatePolicyBasedRouteOperation(name string) *CreatePolicyBasedRouteOperation { - return &CreatePolicyBasedRouteOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetPolicyBasedRoutes(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it } -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *CreatePolicyBasedRouteOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*networkconnectivitypb.PolicyBasedRoute, error) { - var resp networkconnectivitypb.PolicyBasedRoute - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { +// GetPolicyBasedRoute gets details of a single PolicyBasedRoute. +func (c *policyBasedRoutingRESTClient) GetPolicyBasedRoute(ctx context.Context, req *networkconnectivitypb.GetPolicyBasedRouteRequest, opts ...gax.CallOption) (*networkconnectivitypb.PolicyBasedRoute, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - return &resp, nil + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetPolicyBasedRoute[0:len((*c.CallOptions).GetPolicyBasedRoute):len((*c.CallOptions).GetPolicyBasedRoute)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &networkconnectivitypb.PolicyBasedRoute{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil } -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *CreatePolicyBasedRouteOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*networkconnectivitypb.PolicyBasedRoute, error) { - var resp networkconnectivitypb.PolicyBasedRoute - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { +// CreatePolicyBasedRoute creates a new PolicyBasedRoute in a given project and location. +func (c *policyBasedRoutingRESTClient) CreatePolicyBasedRoute(ctx context.Context, req *networkconnectivitypb.CreatePolicyBasedRouteRequest, opts ...gax.CallOption) (*CreatePolicyBasedRouteOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetPolicyBasedRoute() + jsonReq, err := m.Marshal(body) + if err != nil { return nil, err } - if !op.Done() { - return nil, nil + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err } - return &resp, nil + baseUrl.Path += fmt.Sprintf("/v1/%v/policyBasedRoutes", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPolicyBasedRouteId() != "" { + params.Add("policyBasedRouteId", fmt.Sprintf("%v", req.GetPolicyBasedRouteId())) + } + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreatePolicyBasedRouteOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil } -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *CreatePolicyBasedRouteOperation) Metadata() (*networkconnectivitypb.OperationMetadata, error) { - var meta networkconnectivitypb.OperationMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { +// DeletePolicyBasedRoute deletes a single PolicyBasedRoute. +func (c *policyBasedRoutingRESTClient) DeletePolicyBasedRoute(ctx context.Context, req *networkconnectivitypb.DeletePolicyBasedRouteRequest, opts ...gax.CallOption) (*DeletePolicyBasedRouteOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - return &meta, nil -} + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) -// Done reports whether the long-running operation has completed. -func (op *CreatePolicyBasedRouteOperation) Done() bool { - return op.lro.Done() -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } -// 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 *CreatePolicyBasedRouteOperation) Name() string { - return op.lro.Name() -} + baseUrl.RawQuery = params.Encode() -// DeletePolicyBasedRouteOperation manages a long-running operation from DeletePolicyBasedRoute. -type DeletePolicyBasedRouteOperation struct { - lro *longrunning.Operation -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) -// DeletePolicyBasedRouteOperation returns a new DeletePolicyBasedRouteOperation from a given name. -// The name must be that of a previously created DeletePolicyBasedRouteOperation, possibly from a different process. -func (c *policyBasedRoutingGRPCClient) DeletePolicyBasedRouteOperation(name string) *DeletePolicyBasedRouteOperation { - return &DeletePolicyBasedRouteOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeletePolicyBasedRouteOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetLocation gets information about a location. +func (c *policyBasedRoutingRESTClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *policyBasedRoutingRESTClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetIamPolicy gets the access control policy for a resource. Returns an empty policy +// if the resource exists and does not have a policy set. +func (c *policyBasedRoutingRESTClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:getIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetOptions().GetRequestedPolicyVersion() != 0 { + params.Add("options.requestedPolicyVersion", fmt.Sprintf("%v", req.GetOptions().GetRequestedPolicyVersion())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SetIamPolicy sets the access control policy on the specified resource. Replaces +// any existing policy. +// +// Can return NOT_FOUND, INVALID_ARGUMENT, and PERMISSION_DENIED +// errors. +func (c *policyBasedRoutingRESTClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:setIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// TestIamPermissions returns permissions that a caller has on the specified resource. If the +// resource does not exist, this will return an empty set of +// permissions, not a NOT_FOUND error. +// +// Note: This operation is designed to be used for building +// permission-aware UIs and command-line tools, not for authorization +// checking. This operation may “fail open” without warning. +func (c *policyBasedRoutingRESTClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:testIamPermissions", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.TestIamPermissionsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *policyBasedRoutingRESTClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// DeleteOperation is a utility method from google.longrunning.Operations. +func (c *policyBasedRoutingRESTClient) DeleteOperation(ctx context.Context, req *longrunningpb.DeleteOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *policyBasedRoutingRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *policyBasedRoutingRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CreatePolicyBasedRouteOperation manages a long-running operation from CreatePolicyBasedRoute. +type CreatePolicyBasedRouteOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreatePolicyBasedRouteOperation returns a new CreatePolicyBasedRouteOperation from a given name. +// The name must be that of a previously created CreatePolicyBasedRouteOperation, possibly from a different process. +func (c *policyBasedRoutingGRPCClient) CreatePolicyBasedRouteOperation(name string) *CreatePolicyBasedRouteOperation { + return &CreatePolicyBasedRouteOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreatePolicyBasedRouteOperation returns a new CreatePolicyBasedRouteOperation from a given name. +// The name must be that of a previously created CreatePolicyBasedRouteOperation, possibly from a different process. +func (c *policyBasedRoutingRESTClient) CreatePolicyBasedRouteOperation(name string) *CreatePolicyBasedRouteOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreatePolicyBasedRouteOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CreatePolicyBasedRouteOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*networkconnectivitypb.PolicyBasedRoute, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp networkconnectivitypb.PolicyBasedRoute + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *CreatePolicyBasedRouteOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*networkconnectivitypb.PolicyBasedRoute, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp networkconnectivitypb.PolicyBasedRoute + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *CreatePolicyBasedRouteOperation) Metadata() (*networkconnectivitypb.OperationMetadata, error) { + var meta networkconnectivitypb.OperationMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *CreatePolicyBasedRouteOperation) Done() bool { + return op.lro.Done() +} + +// 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 *CreatePolicyBasedRouteOperation) Name() string { + return op.lro.Name() +} + +// DeletePolicyBasedRouteOperation manages a long-running operation from DeletePolicyBasedRoute. +type DeletePolicyBasedRouteOperation struct { + lro *longrunning.Operation + pollPath string +} + +// DeletePolicyBasedRouteOperation returns a new DeletePolicyBasedRouteOperation from a given name. +// The name must be that of a previously created DeletePolicyBasedRouteOperation, possibly from a different process. +func (c *policyBasedRoutingGRPCClient) DeletePolicyBasedRouteOperation(name string) *DeletePolicyBasedRouteOperation { + return &DeletePolicyBasedRouteOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// DeletePolicyBasedRouteOperation returns a new DeletePolicyBasedRouteOperation from a given name. +// The name must be that of a previously created DeletePolicyBasedRouteOperation, possibly from a different process. +func (c *policyBasedRoutingRESTClient) DeletePolicyBasedRouteOperation(name string) *DeletePolicyBasedRouteOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeletePolicyBasedRouteOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, } } @@ -769,6 +1795,7 @@ func (c *policyBasedRoutingGRPCClient) DeletePolicyBasedRouteOperation(name stri // // See documentation of Poll for error-handling information. func (op *DeletePolicyBasedRouteOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -782,6 +1809,7 @@ func (op *DeletePolicyBasedRouteOperation) Wait(ctx context.Context, opts ...gax // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeletePolicyBasedRouteOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } diff --git a/networkconnectivity/apiv1/policy_based_routing_client_example_test.go b/networkconnectivity/apiv1/policy_based_routing_client_example_test.go index d313998c702d..8da22d3e5b4a 100644 --- a/networkconnectivity/apiv1/policy_based_routing_client_example_test.go +++ b/networkconnectivity/apiv1/policy_based_routing_client_example_test.go @@ -44,6 +44,23 @@ func ExampleNewPolicyBasedRoutingClient() { _ = c } +func ExampleNewPolicyBasedRoutingRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := networkconnectivity.NewPolicyBasedRoutingRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExamplePolicyBasedRoutingClient_ListPolicyBasedRoutes() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/networkconnectivity/apiv1alpha1/hub_client.go b/networkconnectivity/apiv1alpha1/hub_client.go index 55fde8712127..3072bcd9c76b 100644 --- a/networkconnectivity/apiv1alpha1/hub_client.go +++ b/networkconnectivity/apiv1alpha1/hub_client.go @@ -816,6 +816,7 @@ func (c *hubRESTClient) ListHubs(ctx context.Context, req *networkconnectivitypb baseUrl.Path += fmt.Sprintf("/v1alpha1/%v/hubs", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -895,6 +896,11 @@ func (c *hubRESTClient) GetHub(ctx context.Context, req *networkconnectivitypb.G } baseUrl.Path += fmt.Sprintf("/v1alpha1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -956,6 +962,7 @@ func (c *hubRESTClient) CreateHub(ctx context.Context, req *networkconnectivityp baseUrl.Path += fmt.Sprintf("/v1alpha1/%v/hubs", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetHubId() != "" { params.Add("hubId", fmt.Sprintf("%v", req.GetHubId())) } @@ -1030,6 +1037,7 @@ func (c *hubRESTClient) UpdateHub(ctx context.Context, req *networkconnectivityp baseUrl.Path += fmt.Sprintf("/v1alpha1/%v", req.GetHub().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetRequestId() != "" { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -1101,6 +1109,7 @@ func (c *hubRESTClient) DeleteHub(ctx context.Context, req *networkconnectivityp baseUrl.Path += fmt.Sprintf("/v1alpha1/%v", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetRequestId() != "" { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -1178,6 +1187,7 @@ func (c *hubRESTClient) ListSpokes(ctx context.Context, req *networkconnectivity baseUrl.Path += fmt.Sprintf("/v1alpha1/%v/spokes", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1257,6 +1267,11 @@ func (c *hubRESTClient) GetSpoke(ctx context.Context, req *networkconnectivitypb } baseUrl.Path += fmt.Sprintf("/v1alpha1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1318,6 +1333,7 @@ func (c *hubRESTClient) CreateSpoke(ctx context.Context, req *networkconnectivit baseUrl.Path += fmt.Sprintf("/v1alpha1/%v/spokes", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetRequestId() != "" { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -1392,6 +1408,7 @@ func (c *hubRESTClient) UpdateSpoke(ctx context.Context, req *networkconnectivit baseUrl.Path += fmt.Sprintf("/v1alpha1/%v", req.GetSpoke().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetRequestId() != "" { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -1463,6 +1480,7 @@ func (c *hubRESTClient) DeleteSpoke(ctx context.Context, req *networkconnectivit baseUrl.Path += fmt.Sprintf("/v1alpha1/%v", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetRequestId() != "" { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } diff --git a/networkconnectivity/apiv1alpha1/networkconnectivitypb/common.pb.go b/networkconnectivity/apiv1alpha1/networkconnectivitypb/common.pb.go index 84403fde92b3..a2b9f20874ce 100644 --- a/networkconnectivity/apiv1alpha1/networkconnectivitypb/common.pb.go +++ b/networkconnectivity/apiv1alpha1/networkconnectivitypb/common.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/networkconnectivity/v1alpha1/common.proto package networkconnectivitypb diff --git a/networkconnectivity/apiv1alpha1/networkconnectivitypb/hub.pb.go b/networkconnectivity/apiv1alpha1/networkconnectivitypb/hub.pb.go index 3b9bc5b776c0..ae1da2913573 100644 --- a/networkconnectivity/apiv1alpha1/networkconnectivitypb/hub.pb.go +++ b/networkconnectivity/apiv1alpha1/networkconnectivitypb/hub.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/networkconnectivity/v1alpha1/hub.proto package networkconnectivitypb diff --git a/networkmanagement/apiv1/doc.go b/networkmanagement/apiv1/doc.go index 0fe4692a1a36..5e3307bc3663 100644 --- a/networkmanagement/apiv1/doc.go +++ b/networkmanagement/apiv1/doc.go @@ -87,6 +87,8 @@ package networkmanagement // import "cloud.google.com/go/networkmanagement/apiv1 import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -175,3 +177,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/networkmanagement/apiv1/gapic_metadata.json b/networkmanagement/apiv1/gapic_metadata.json index f0493deeab7d..a5463a35dc6e 100644 --- a/networkmanagement/apiv1/gapic_metadata.json +++ b/networkmanagement/apiv1/gapic_metadata.json @@ -41,6 +41,41 @@ ] } } + }, + "rest": { + "libraryClient": "ReachabilityClient", + "rpcs": { + "CreateConnectivityTest": { + "methods": [ + "CreateConnectivityTest" + ] + }, + "DeleteConnectivityTest": { + "methods": [ + "DeleteConnectivityTest" + ] + }, + "GetConnectivityTest": { + "methods": [ + "GetConnectivityTest" + ] + }, + "ListConnectivityTests": { + "methods": [ + "ListConnectivityTests" + ] + }, + "RerunConnectivityTest": { + "methods": [ + "RerunConnectivityTest" + ] + }, + "UpdateConnectivityTest": { + "methods": [ + "UpdateConnectivityTest" + ] + } + } } } } diff --git a/networkmanagement/apiv1/networkmanagementpb/connectivity_test.pb.go b/networkmanagement/apiv1/networkmanagementpb/connectivity_test.pb.go index 16a2589f919a..39f68dc10fbc 100644 --- a/networkmanagement/apiv1/networkmanagementpb/connectivity_test.pb.go +++ b/networkmanagement/apiv1/networkmanagementpb/connectivity_test.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/networkmanagement/v1/connectivity_test.proto package networkmanagementpb @@ -104,11 +104,11 @@ const ( ReachabilityDetails_RESULT_UNSPECIFIED ReachabilityDetails_Result = 0 // Possible scenarios are: // - // - The configuration analysis determined that a packet originating from - // the source is expected to reach the destination. - // - The analysis didn't complete because the user lacks permission for - // some of the resources in the trace. However, at the time the user's - // permission became insufficient, the trace had been successful so far. + // * The configuration analysis determined that a packet originating from + // the source is expected to reach the destination. + // * The analysis didn't complete because the user lacks permission for + // some of the resources in the trace. However, at the time the user's + // permission became insufficient, the trace had been successful so far. ReachabilityDetails_REACHABLE ReachabilityDetails_Result = 1 // A packet originating from the source is expected to be dropped before // reaching the destination. @@ -120,11 +120,11 @@ const ( ReachabilityDetails_AMBIGUOUS ReachabilityDetails_Result = 4 // The configuration analysis did not complete. Possible reasons are: // - // - A permissions error occurred--for example, the user might not have - // read permission for all of the resources named in the test. - // - An internal error occurred. - // - The analyzer received an invalid or unsupported argument or was unable - // to identify a known endpoint. + // * A permissions error occurred--for example, the user might not have + // read permission for all of the resources named in the test. + // * An internal error occurred. + // * The analyzer received an invalid or unsupported argument or was unable + // to identify a known endpoint. ReachabilityDetails_UNDETERMINED ReachabilityDetails_Result = 5 ) @@ -180,8 +180,7 @@ type ConnectivityTest struct { unknownFields protoimpl.UnknownFields // Required. Unique name of the resource using the form: - // - // `projects/{project_id}/locations/global/connectivityTests/{test_id}` + // `projects/{project_id}/locations/global/connectivityTests/{test_id}` Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // The user-supplied description of the Connectivity Test. // Maximum of 512 characters. diff --git a/networkmanagement/apiv1/networkmanagementpb/reachability.pb.go b/networkmanagement/apiv1/networkmanagementpb/reachability.pb.go index 3122f849fcae..ecf18fc9d10e 100644 --- a/networkmanagement/apiv1/networkmanagementpb/reachability.pb.go +++ b/networkmanagement/apiv1/networkmanagementpb/reachability.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/networkmanagement/v1/reachability.proto package networkmanagementpb @@ -50,8 +50,7 @@ type ListConnectivityTestsRequest struct { unknownFields protoimpl.UnknownFields // Required. The parent resource of the Connectivity Tests: - // - // `projects/{project_id}/locations/global` + // `projects/{project_id}/locations/global` Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // Number of `ConnectivityTests` to return. PageSize int32 `protobuf:"varint,2,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"` @@ -67,8 +66,8 @@ type ListConnectivityTestsRequest struct { // field, or a synthetic field. Field names can be camelCase or snake_case. // // Examples: - // - Filter by name: - // name = "projects/proj-1/locations/global/connectivityTests/test-1 + // - Filter by name: + // name = "projects/proj-1/locations/global/connectivityTests/test-1 // // - Filter by labels: // - Resources that have a key called `foo` @@ -221,8 +220,7 @@ type GetConnectivityTestRequest struct { unknownFields protoimpl.UnknownFields // Required. `ConnectivityTest` resource name using the form: - // - // `projects/{project_id}/locations/global/connectivityTests/{test_id}` + // `projects/{project_id}/locations/global/connectivityTests/{test_id}` Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` } @@ -272,8 +270,7 @@ type CreateConnectivityTestRequest struct { unknownFields protoimpl.UnknownFields // Required. The parent resource of the Connectivity Test to create: - // - // `projects/{project_id}/locations/global` + // `projects/{project_id}/locations/global` Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // Required. The logical name of the Connectivity Test in your project // with the following restrictions: @@ -407,8 +404,7 @@ type DeleteConnectivityTestRequest struct { unknownFields protoimpl.UnknownFields // Required. Connectivity Test resource name using the form: - // - // `projects/{project_id}/locations/global/connectivityTests/{test_id}` + // `projects/{project_id}/locations/global/connectivityTests/{test_id}` Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` } @@ -458,8 +454,7 @@ type RerunConnectivityTestRequest struct { unknownFields protoimpl.UnknownFields // Required. Connectivity Test resource name using the form: - // - // `projects/{project_id}/locations/global/connectivityTests/{test_id}` + // `projects/{project_id}/locations/global/connectivityTests/{test_id}` Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` } diff --git a/networkmanagement/apiv1/networkmanagementpb/trace.pb.go b/networkmanagement/apiv1/networkmanagementpb/trace.pb.go index 7b7a05d41ccd..d8dafb93dcf8 100644 --- a/networkmanagement/apiv1/networkmanagementpb/trace.pb.go +++ b/networkmanagement/apiv1/networkmanagementpb/trace.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/networkmanagement/v1/trace.proto package networkmanagementpb @@ -1153,7 +1153,6 @@ type Step struct { // final state the configuration is cleared. // // Types that are assignable to StepInfo: - // // *Step_Instance // *Step_Firewall // *Step_Route diff --git a/networkmanagement/apiv1/reachability_client.go b/networkmanagement/apiv1/reachability_client.go index d9cb6f88fa02..c0847e7cb492 100644 --- a/networkmanagement/apiv1/reachability_client.go +++ b/networkmanagement/apiv1/reachability_client.go @@ -17,9 +17,12 @@ package networkmanagement import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,13 +30,16 @@ import ( lroauto "cloud.google.com/go/longrunning/autogen" networkmanagementpb "cloud.google.com/go/networkmanagement/apiv1/networkmanagementpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -72,6 +78,17 @@ func defaultReachabilityCallOptions() *ReachabilityCallOptions { } } +func defaultReachabilityRESTCallOptions() *ReachabilityCallOptions { + return &ReachabilityCallOptions{ + ListConnectivityTests: []gax.CallOption{}, + GetConnectivityTest: []gax.CallOption{}, + CreateConnectivityTest: []gax.CallOption{}, + UpdateConnectivityTest: []gax.CallOption{}, + RerunConnectivityTest: []gax.CallOption{}, + DeleteConnectivityTest: []gax.CallOption{}, + } +} + // internalReachabilityClient is an interface that defines the methods available from Network Management API. type internalReachabilityClient interface { Close() error @@ -330,6 +347,96 @@ func (c *reachabilityGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type reachabilityRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing ReachabilityClient + CallOptions **ReachabilityCallOptions +} + +// NewReachabilityRESTClient creates a new reachability service rest client. +// +// The Reachability service in the Google Cloud Network Management API provides +// services that analyze the reachability within a single Google Virtual Private +// Cloud (VPC) network, between peered VPC networks, between VPC and on-premises +// networks, or between VPC networks and internet hosts. A reachability analysis +// is based on Google Cloud network configurations. +// +// You can use the analysis results to verify these configurations and +// to troubleshoot connectivity issues. +func NewReachabilityRESTClient(ctx context.Context, opts ...option.ClientOption) (*ReachabilityClient, error) { + clientOpts := append(defaultReachabilityRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultReachabilityRESTCallOptions() + c := &reachabilityRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &ReachabilityClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultReachabilityRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://networkmanagement.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://networkmanagement.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://networkmanagement.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *reachabilityRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *reachabilityRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *reachabilityRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *reachabilityGRPCClient) ListConnectivityTests(ctx context.Context, req *networkmanagementpb.ListConnectivityTestsRequest, opts ...gax.CallOption) *ConnectivityTestIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -493,9 +600,474 @@ func (c *reachabilityGRPCClient) DeleteConnectivityTest(ctx context.Context, req }, nil } +// ListConnectivityTests lists all Connectivity Tests owned by a project. +func (c *reachabilityRESTClient) ListConnectivityTests(ctx context.Context, req *networkmanagementpb.ListConnectivityTestsRequest, opts ...gax.CallOption) *ConnectivityTestIterator { + it := &ConnectivityTestIterator{} + req = proto.Clone(req).(*networkmanagementpb.ListConnectivityTestsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*networkmanagementpb.ConnectivityTest, string, error) { + resp := &networkmanagementpb.ListConnectivityTestsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/connectivityTests", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetResources(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetConnectivityTest gets the details of a specific Connectivity Test. +func (c *reachabilityRESTClient) GetConnectivityTest(ctx context.Context, req *networkmanagementpb.GetConnectivityTestRequest, opts ...gax.CallOption) (*networkmanagementpb.ConnectivityTest, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetConnectivityTest[0:len((*c.CallOptions).GetConnectivityTest):len((*c.CallOptions).GetConnectivityTest)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &networkmanagementpb.ConnectivityTest{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateConnectivityTest creates a new Connectivity Test. +// After you create a test, the reachability analysis is performed as part +// of the long running operation, which completes when the analysis completes. +// +// If the endpoint specifications in ConnectivityTest are invalid +// (for example, containing non-existent resources in the network, or you +// don’t have read permissions to the network configurations of listed +// projects), then the reachability result returns a value of UNKNOWN. +// +// If the endpoint specifications in ConnectivityTest are +// incomplete, the reachability result returns a value of +// AMBIGUOUS. For more information, +// see the Connectivity Test documentation. +func (c *reachabilityRESTClient) CreateConnectivityTest(ctx context.Context, req *networkmanagementpb.CreateConnectivityTestRequest, opts ...gax.CallOption) (*CreateConnectivityTestOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetResource() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/connectivityTests", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("testId", fmt.Sprintf("%v", req.GetTestId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateConnectivityTestOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateConnectivityTest updates the configuration of an existing ConnectivityTest. +// After you update a test, the reachability analysis is performed as part +// of the long running operation, which completes when the analysis completes. +// The Reachability state in the test resource is updated with the new result. +// +// If the endpoint specifications in ConnectivityTest are invalid +// (for example, they contain non-existent resources in the network, or the +// user does not have read permissions to the network configurations of +// listed projects), then the reachability result returns a value of +// UNKNOWN. +// +// If the endpoint specifications in ConnectivityTest are incomplete, the +// reachability result returns a value of AMBIGUOUS. See the documentation +// in ConnectivityTest for for more details. +func (c *reachabilityRESTClient) UpdateConnectivityTest(ctx context.Context, req *networkmanagementpb.UpdateConnectivityTestRequest, opts ...gax.CallOption) (*UpdateConnectivityTestOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetResource() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetResource().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource.name", url.QueryEscape(req.GetResource().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateConnectivityTestOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// RerunConnectivityTest rerun an existing ConnectivityTest. +// After the user triggers the rerun, the reachability analysis is performed +// as part of the long running operation, which completes when the analysis +// completes. +// +// Even though the test configuration remains the same, the reachability +// result may change due to underlying network configuration changes. +// +// If the endpoint specifications in ConnectivityTest become invalid (for +// example, specified resources are deleted in the network, or you lost +// read permissions to the network configurations of listed projects), then +// the reachability result returns a value of UNKNOWN. +func (c *reachabilityRESTClient) RerunConnectivityTest(ctx context.Context, req *networkmanagementpb.RerunConnectivityTestRequest, opts ...gax.CallOption) (*RerunConnectivityTestOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:rerun", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &RerunConnectivityTestOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteConnectivityTest deletes a specific ConnectivityTest. +func (c *reachabilityRESTClient) DeleteConnectivityTest(ctx context.Context, req *networkmanagementpb.DeleteConnectivityTestRequest, opts ...gax.CallOption) (*DeleteConnectivityTestOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteConnectivityTestOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + // CreateConnectivityTestOperation manages a long-running operation from CreateConnectivityTest. type CreateConnectivityTestOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateConnectivityTestOperation returns a new CreateConnectivityTestOperation from a given name. @@ -506,10 +1078,21 @@ func (c *reachabilityGRPCClient) CreateConnectivityTestOperation(name string) *C } } +// CreateConnectivityTestOperation returns a new CreateConnectivityTestOperation from a given name. +// The name must be that of a previously created CreateConnectivityTestOperation, possibly from a different process. +func (c *reachabilityRESTClient) CreateConnectivityTestOperation(name string) *CreateConnectivityTestOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateConnectivityTestOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateConnectivityTestOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*networkmanagementpb.ConnectivityTest, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp networkmanagementpb.ConnectivityTest if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -527,6 +1110,7 @@ func (op *CreateConnectivityTestOperation) Wait(ctx context.Context, opts ...gax // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateConnectivityTestOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*networkmanagementpb.ConnectivityTest, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp networkmanagementpb.ConnectivityTest if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -564,7 +1148,8 @@ func (op *CreateConnectivityTestOperation) Name() string { // DeleteConnectivityTestOperation manages a long-running operation from DeleteConnectivityTest. type DeleteConnectivityTestOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteConnectivityTestOperation returns a new DeleteConnectivityTestOperation from a given name. @@ -575,10 +1160,21 @@ func (c *reachabilityGRPCClient) DeleteConnectivityTestOperation(name string) *D } } +// DeleteConnectivityTestOperation returns a new DeleteConnectivityTestOperation from a given name. +// The name must be that of a previously created DeleteConnectivityTestOperation, possibly from a different process. +func (c *reachabilityRESTClient) DeleteConnectivityTestOperation(name string) *DeleteConnectivityTestOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteConnectivityTestOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteConnectivityTestOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -592,6 +1188,7 @@ func (op *DeleteConnectivityTestOperation) Wait(ctx context.Context, opts ...gax // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteConnectivityTestOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -622,7 +1219,8 @@ func (op *DeleteConnectivityTestOperation) Name() string { // RerunConnectivityTestOperation manages a long-running operation from RerunConnectivityTest. type RerunConnectivityTestOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // RerunConnectivityTestOperation returns a new RerunConnectivityTestOperation from a given name. @@ -633,10 +1231,21 @@ func (c *reachabilityGRPCClient) RerunConnectivityTestOperation(name string) *Re } } +// RerunConnectivityTestOperation returns a new RerunConnectivityTestOperation from a given name. +// The name must be that of a previously created RerunConnectivityTestOperation, possibly from a different process. +func (c *reachabilityRESTClient) RerunConnectivityTestOperation(name string) *RerunConnectivityTestOperation { + override := fmt.Sprintf("/v1/%s", name) + return &RerunConnectivityTestOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *RerunConnectivityTestOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*networkmanagementpb.ConnectivityTest, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp networkmanagementpb.ConnectivityTest if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -654,6 +1263,7 @@ func (op *RerunConnectivityTestOperation) Wait(ctx context.Context, opts ...gax. // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *RerunConnectivityTestOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*networkmanagementpb.ConnectivityTest, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp networkmanagementpb.ConnectivityTest if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -691,7 +1301,8 @@ func (op *RerunConnectivityTestOperation) Name() string { // UpdateConnectivityTestOperation manages a long-running operation from UpdateConnectivityTest. type UpdateConnectivityTestOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateConnectivityTestOperation returns a new UpdateConnectivityTestOperation from a given name. @@ -702,10 +1313,21 @@ func (c *reachabilityGRPCClient) UpdateConnectivityTestOperation(name string) *U } } +// UpdateConnectivityTestOperation returns a new UpdateConnectivityTestOperation from a given name. +// The name must be that of a previously created UpdateConnectivityTestOperation, possibly from a different process. +func (c *reachabilityRESTClient) UpdateConnectivityTestOperation(name string) *UpdateConnectivityTestOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateConnectivityTestOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateConnectivityTestOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*networkmanagementpb.ConnectivityTest, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp networkmanagementpb.ConnectivityTest if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -723,6 +1345,7 @@ func (op *UpdateConnectivityTestOperation) Wait(ctx context.Context, opts ...gax // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateConnectivityTestOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*networkmanagementpb.ConnectivityTest, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp networkmanagementpb.ConnectivityTest if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/networkmanagement/apiv1/reachability_client_example_test.go b/networkmanagement/apiv1/reachability_client_example_test.go index 296dc2b9925a..82b098bc1c01 100644 --- a/networkmanagement/apiv1/reachability_client_example_test.go +++ b/networkmanagement/apiv1/reachability_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewReachabilityClient() { _ = c } +func ExampleNewReachabilityRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := networkmanagement.NewReachabilityRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleReachabilityClient_ListConnectivityTests() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/networksecurity/apiv1beta1/network_security_client.go b/networksecurity/apiv1beta1/network_security_client.go index 1ead9af68931..e64ebfe436b1 100644 --- a/networksecurity/apiv1beta1/network_security_client.go +++ b/networksecurity/apiv1beta1/network_security_client.go @@ -1245,6 +1245,7 @@ func (c *restClient) ListAuthorizationPolicies(ctx context.Context, req *network baseUrl.Path += fmt.Sprintf("/v1beta1/%v/authorizationPolicies", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -1318,6 +1319,11 @@ func (c *restClient) GetAuthorizationPolicy(ctx context.Context, req *networksec } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1379,6 +1385,7 @@ func (c *restClient) CreateAuthorizationPolicy(ctx context.Context, req *network baseUrl.Path += fmt.Sprintf("/v1beta1/%v/authorizationPolicies", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("authorizationPolicyId", fmt.Sprintf("%v", req.GetAuthorizationPolicyId())) baseUrl.RawQuery = params.Encode() @@ -1448,6 +1455,7 @@ func (c *restClient) UpdateAuthorizationPolicy(ctx context.Context, req *network baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetAuthorizationPolicy().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -1515,6 +1523,11 @@ func (c *restClient) DeleteAuthorizationPolicy(ctx context.Context, req *network } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1586,6 +1599,7 @@ func (c *restClient) ListServerTlsPolicies(ctx context.Context, req *networksecu baseUrl.Path += fmt.Sprintf("/v1beta1/%v/serverTlsPolicies", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -1659,6 +1673,11 @@ func (c *restClient) GetServerTlsPolicy(ctx context.Context, req *networksecurit } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1720,6 +1739,7 @@ func (c *restClient) CreateServerTlsPolicy(ctx context.Context, req *networksecu baseUrl.Path += fmt.Sprintf("/v1beta1/%v/serverTlsPolicies", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("serverTlsPolicyId", fmt.Sprintf("%v", req.GetServerTlsPolicyId())) baseUrl.RawQuery = params.Encode() @@ -1789,6 +1809,7 @@ func (c *restClient) UpdateServerTlsPolicy(ctx context.Context, req *networksecu baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetServerTlsPolicy().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -1856,6 +1877,11 @@ func (c *restClient) DeleteServerTlsPolicy(ctx context.Context, req *networksecu } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1927,6 +1953,7 @@ func (c *restClient) ListClientTlsPolicies(ctx context.Context, req *networksecu baseUrl.Path += fmt.Sprintf("/v1beta1/%v/clientTlsPolicies", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -2000,6 +2027,11 @@ func (c *restClient) GetClientTlsPolicy(ctx context.Context, req *networksecurit } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2061,6 +2093,7 @@ func (c *restClient) CreateClientTlsPolicy(ctx context.Context, req *networksecu baseUrl.Path += fmt.Sprintf("/v1beta1/%v/clientTlsPolicies", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("clientTlsPolicyId", fmt.Sprintf("%v", req.GetClientTlsPolicyId())) baseUrl.RawQuery = params.Encode() @@ -2130,6 +2163,7 @@ func (c *restClient) UpdateClientTlsPolicy(ctx context.Context, req *networksecu baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetClientTlsPolicy().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -2197,6 +2231,11 @@ func (c *restClient) DeleteClientTlsPolicy(ctx context.Context, req *networksecu } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2254,6 +2293,11 @@ func (c *restClient) GetLocation(ctx context.Context, req *locationpb.GetLocatio } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2321,6 +2365,7 @@ func (c *restClient) ListLocations(ctx context.Context, req *locationpb.ListLoca baseUrl.Path += fmt.Sprintf("/v1beta1/%v/locations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -2399,6 +2444,7 @@ func (c *restClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRe baseUrl.Path += fmt.Sprintf("/v1beta1/%v:getIamPolicy", req.GetResource()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetOptions().GetRequestedPolicyVersion() != 0 { params.Add("options.requestedPolicyVersion", fmt.Sprintf("%v", req.GetOptions().GetRequestedPolicyVersion())) } @@ -2468,6 +2514,11 @@ func (c *restClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRe } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:setIamPolicy", req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) @@ -2533,6 +2584,11 @@ func (c *restClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamP } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:testIamPermissions", req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) @@ -2592,6 +2648,11 @@ func (c *restClient) CancelOperation(ctx context.Context, req *longrunningpb.Can } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:cancel", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2627,6 +2688,11 @@ func (c *restClient) DeleteOperation(ctx context.Context, req *longrunningpb.Del } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2662,6 +2728,11 @@ func (c *restClient) GetOperation(ctx context.Context, req *longrunningpb.GetOpe } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2729,6 +2800,7 @@ func (c *restClient) ListOperations(ctx context.Context, req *longrunningpb.List baseUrl.Path += fmt.Sprintf("/v1beta1/%v/operations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/networksecurity/apiv1beta1/networksecuritypb/authorization_policy.pb.go b/networksecurity/apiv1beta1/networksecuritypb/authorization_policy.pb.go index d11b227c3fcc..888dfa6d4449 100644 --- a/networksecurity/apiv1beta1/networksecuritypb/authorization_policy.pb.go +++ b/networksecurity/apiv1beta1/networksecuritypb/authorization_policy.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/networksecurity/v1beta1/authorization_policy.proto package networksecuritypb @@ -795,7 +795,6 @@ type AuthorizationPolicy_Rule_Destination_HttpHeaderMatch struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Type: - // // *AuthorizationPolicy_Rule_Destination_HttpHeaderMatch_RegexMatch Type isAuthorizationPolicy_Rule_Destination_HttpHeaderMatch_Type `protobuf_oneof:"type"` // Required. The name of the HTTP header to match. For matching diff --git a/networksecurity/apiv1beta1/networksecuritypb/client_tls_policy.pb.go b/networksecurity/apiv1beta1/networksecuritypb/client_tls_policy.pb.go index 4cf9dcbd8f48..17276a752b80 100644 --- a/networksecurity/apiv1beta1/networksecuritypb/client_tls_policy.pb.go +++ b/networksecurity/apiv1beta1/networksecuritypb/client_tls_policy.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/networksecurity/v1beta1/client_tls_policy.proto package networksecuritypb diff --git a/networksecurity/apiv1beta1/networksecuritypb/common.pb.go b/networksecurity/apiv1beta1/networksecuritypb/common.pb.go index 7a9028e66d19..3e3c2e7ec9f1 100644 --- a/networksecurity/apiv1beta1/networksecuritypb/common.pb.go +++ b/networksecurity/apiv1beta1/networksecuritypb/common.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/networksecurity/v1beta1/common.proto package networksecuritypb diff --git a/networksecurity/apiv1beta1/networksecuritypb/network_security.pb.go b/networksecurity/apiv1beta1/networksecuritypb/network_security.pb.go index 20490fe34aa2..feb03413c37a 100644 --- a/networksecurity/apiv1beta1/networksecuritypb/network_security.pb.go +++ b/networksecurity/apiv1beta1/networksecuritypb/network_security.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/networksecurity/v1beta1/network_security.proto package networksecuritypb diff --git a/networksecurity/apiv1beta1/networksecuritypb/server_tls_policy.pb.go b/networksecurity/apiv1beta1/networksecuritypb/server_tls_policy.pb.go index 7ffb41f61e18..388ef45e1fa5 100644 --- a/networksecurity/apiv1beta1/networksecuritypb/server_tls_policy.pb.go +++ b/networksecurity/apiv1beta1/networksecuritypb/server_tls_policy.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/networksecurity/v1beta1/server_tls_policy.proto package networksecuritypb @@ -57,6 +57,7 @@ type ServerTlsPolicy struct { UpdateTime *timestamppb.Timestamp `protobuf:"bytes,4,opt,name=update_time,json=updateTime,proto3" json:"update_time,omitempty"` // Set of label tags associated with the resource. Labels map[string]string `protobuf:"bytes,5,rep,name=labels,proto3" json:"labels,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` + // // Determines if server allows plaintext connections. If set to true, server // allows plain text connections. By default, it is set to false. This setting // is not exclusive of other encryption modes. For example, if `allow_open` @@ -67,10 +68,12 @@ type ServerTlsPolicy struct { // Consider using it if you wish to upgrade in place your deployment to TLS // while having mixed TLS and non-TLS traffic reaching port :80. AllowOpen bool `protobuf:"varint,6,opt,name=allow_open,json=allowOpen,proto3" json:"allow_open,omitempty"` + // // Defines a mechanism to provision server identity (public and private keys). // Cannot be combined with `allow_open` as a permissive mode that allows both // plain text and TLS is not supported. ServerCertificate *CertificateProvider `protobuf:"bytes,7,opt,name=server_certificate,json=serverCertificate,proto3" json:"server_certificate,omitempty"` + // // Defines a mechanism to provision peer validation certificates for peer to // peer authentication (Mutual TLS - mTLS). If not specified, client // certificate will not be requested. The connection is treated as TLS and not @@ -538,6 +541,7 @@ type ServerTlsPolicy_MTLSPolicy struct { sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields + // // Defines the mechanism to obtain the Certificate Authority certificate to // validate the client certificate. ClientValidationCa []*ValidationCA `protobuf:"bytes,1,rep,name=client_validation_ca,json=clientValidationCa,proto3" json:"client_validation_ca,omitempty"` diff --git a/networksecurity/apiv1beta1/networksecuritypb/tls.pb.go b/networksecurity/apiv1beta1/networksecuritypb/tls.pb.go index 8488aaa38b91..c6a318982b61 100644 --- a/networksecurity/apiv1beta1/networksecuritypb/tls.pb.go +++ b/networksecurity/apiv1beta1/networksecuritypb/tls.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/networksecurity/v1beta1/tls.proto package networksecuritypb @@ -96,7 +96,6 @@ type ValidationCA struct { // The type of certificate provider which provides the CA certificate. // // Types that are assignable to Type: - // // *ValidationCA_GrpcEndpoint // *ValidationCA_CertificateProviderInstance Type isValidationCA_Type `protobuf_oneof:"type"` @@ -241,7 +240,6 @@ type CertificateProvider struct { // private keys. // // Types that are assignable to Type: - // // *CertificateProvider_GrpcEndpoint // *CertificateProvider_CertificateProviderInstance Type isCertificateProvider_Type `protobuf_oneof:"type"` diff --git a/notebooks/apiv1/doc.go b/notebooks/apiv1/doc.go index b124573e64fa..b6f0d1113680 100644 --- a/notebooks/apiv1/doc.go +++ b/notebooks/apiv1/doc.go @@ -86,6 +86,8 @@ package notebooks // import "cloud.google.com/go/notebooks/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -174,3 +176,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/notebooks/apiv1/gapic_metadata.json b/notebooks/apiv1/gapic_metadata.json index be14c8110f1f..8ecdcd4c9878 100644 --- a/notebooks/apiv1/gapic_metadata.json +++ b/notebooks/apiv1/gapic_metadata.json @@ -121,6 +121,121 @@ ] } } + }, + "rest": { + "libraryClient": "ManagedNotebookClient", + "rpcs": { + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "CreateRuntime": { + "methods": [ + "CreateRuntime" + ] + }, + "DeleteOperation": { + "methods": [ + "DeleteOperation" + ] + }, + "DeleteRuntime": { + "methods": [ + "DeleteRuntime" + ] + }, + "DiagnoseRuntime": { + "methods": [ + "DiagnoseRuntime" + ] + }, + "GetIamPolicy": { + "methods": [ + "GetIamPolicy" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "GetRuntime": { + "methods": [ + "GetRuntime" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "ListRuntimes": { + "methods": [ + "ListRuntimes" + ] + }, + "RefreshRuntimeTokenInternal": { + "methods": [ + "RefreshRuntimeTokenInternal" + ] + }, + "ReportRuntimeEvent": { + "methods": [ + "ReportRuntimeEvent" + ] + }, + "ResetRuntime": { + "methods": [ + "ResetRuntime" + ] + }, + "SetIamPolicy": { + "methods": [ + "SetIamPolicy" + ] + }, + "StartRuntime": { + "methods": [ + "StartRuntime" + ] + }, + "StopRuntime": { + "methods": [ + "StopRuntime" + ] + }, + "SwitchRuntime": { + "methods": [ + "SwitchRuntime" + ] + }, + "TestIamPermissions": { + "methods": [ + "TestIamPermissions" + ] + }, + "UpdateRuntime": { + "methods": [ + "UpdateRuntime" + ] + }, + "UpgradeRuntime": { + "methods": [ + "UpgradeRuntime" + ] + } + } } } }, @@ -345,6 +460,226 @@ ] } } + }, + "rest": { + "libraryClient": "NotebookClient", + "rpcs": { + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "CreateEnvironment": { + "methods": [ + "CreateEnvironment" + ] + }, + "CreateExecution": { + "methods": [ + "CreateExecution" + ] + }, + "CreateInstance": { + "methods": [ + "CreateInstance" + ] + }, + "CreateSchedule": { + "methods": [ + "CreateSchedule" + ] + }, + "DeleteEnvironment": { + "methods": [ + "DeleteEnvironment" + ] + }, + "DeleteExecution": { + "methods": [ + "DeleteExecution" + ] + }, + "DeleteInstance": { + "methods": [ + "DeleteInstance" + ] + }, + "DeleteOperation": { + "methods": [ + "DeleteOperation" + ] + }, + "DeleteSchedule": { + "methods": [ + "DeleteSchedule" + ] + }, + "DiagnoseInstance": { + "methods": [ + "DiagnoseInstance" + ] + }, + "GetEnvironment": { + "methods": [ + "GetEnvironment" + ] + }, + "GetExecution": { + "methods": [ + "GetExecution" + ] + }, + "GetIamPolicy": { + "methods": [ + "GetIamPolicy" + ] + }, + "GetInstance": { + "methods": [ + "GetInstance" + ] + }, + "GetInstanceHealth": { + "methods": [ + "GetInstanceHealth" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "GetSchedule": { + "methods": [ + "GetSchedule" + ] + }, + "IsInstanceUpgradeable": { + "methods": [ + "IsInstanceUpgradeable" + ] + }, + "ListEnvironments": { + "methods": [ + "ListEnvironments" + ] + }, + "ListExecutions": { + "methods": [ + "ListExecutions" + ] + }, + "ListInstances": { + "methods": [ + "ListInstances" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "ListSchedules": { + "methods": [ + "ListSchedules" + ] + }, + "RegisterInstance": { + "methods": [ + "RegisterInstance" + ] + }, + "ReportInstanceInfo": { + "methods": [ + "ReportInstanceInfo" + ] + }, + "ResetInstance": { + "methods": [ + "ResetInstance" + ] + }, + "RollbackInstance": { + "methods": [ + "RollbackInstance" + ] + }, + "SetIamPolicy": { + "methods": [ + "SetIamPolicy" + ] + }, + "SetInstanceAccelerator": { + "methods": [ + "SetInstanceAccelerator" + ] + }, + "SetInstanceLabels": { + "methods": [ + "SetInstanceLabels" + ] + }, + "SetInstanceMachineType": { + "methods": [ + "SetInstanceMachineType" + ] + }, + "StartInstance": { + "methods": [ + "StartInstance" + ] + }, + "StopInstance": { + "methods": [ + "StopInstance" + ] + }, + "TestIamPermissions": { + "methods": [ + "TestIamPermissions" + ] + }, + "TriggerSchedule": { + "methods": [ + "TriggerSchedule" + ] + }, + "UpdateInstanceConfig": { + "methods": [ + "UpdateInstanceConfig" + ] + }, + "UpdateInstanceMetadataItems": { + "methods": [ + "UpdateInstanceMetadataItems" + ] + }, + "UpdateShieldedInstanceConfig": { + "methods": [ + "UpdateShieldedInstanceConfig" + ] + }, + "UpgradeInstance": { + "methods": [ + "UpgradeInstance" + ] + }, + "UpgradeInstanceInternal": { + "methods": [ + "UpgradeInstanceInternal" + ] + } + } } } } diff --git a/notebooks/apiv1/managed_notebook_client.go b/notebooks/apiv1/managed_notebook_client.go index e052c8fbf45f..4d4252fa42d7 100644 --- a/notebooks/apiv1/managed_notebook_client.go +++ b/notebooks/apiv1/managed_notebook_client.go @@ -17,9 +17,12 @@ package notebooks import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,16 +30,19 @@ import ( lroauto "cloud.google.com/go/longrunning/autogen" notebookspb "cloud.google.com/go/notebooks/apiv1/notebookspb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" iampb "google.golang.org/genproto/googleapis/iam/v1" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -148,6 +154,70 @@ func defaultManagedNotebookCallOptions() *ManagedNotebookCallOptions { } } +func defaultManagedNotebookRESTCallOptions() *ManagedNotebookCallOptions { + return &ManagedNotebookCallOptions{ + ListRuntimes: []gax.CallOption{}, + GetRuntime: []gax.CallOption{}, + CreateRuntime: []gax.CallOption{}, + UpdateRuntime: []gax.CallOption{}, + DeleteRuntime: []gax.CallOption{}, + StartRuntime: []gax.CallOption{}, + StopRuntime: []gax.CallOption{}, + SwitchRuntime: []gax.CallOption{}, + ResetRuntime: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UpgradeRuntime: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ReportRuntimeEvent: []gax.CallOption{}, + RefreshRuntimeTokenInternal: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DiagnoseRuntime: []gax.CallOption{}, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + GetIamPolicy: []gax.CallOption{}, + SetIamPolicy: []gax.CallOption{}, + TestIamPermissions: []gax.CallOption{}, + CancelOperation: []gax.CallOption{}, + DeleteOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 300000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + } +} + // internalManagedNotebookClient is an interface that defines the methods available from Notebooks API. type internalManagedNotebookClient interface { Close() error @@ -524,6 +594,89 @@ func (c *managedNotebookGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type managedNotebookRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing ManagedNotebookClient + CallOptions **ManagedNotebookCallOptions +} + +// NewManagedNotebookRESTClient creates a new managed notebook service rest client. +// +// API v1 service for Managed Notebooks. +func NewManagedNotebookRESTClient(ctx context.Context, opts ...option.ClientOption) (*ManagedNotebookClient, error) { + clientOpts := append(defaultManagedNotebookRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultManagedNotebookRESTCallOptions() + c := &managedNotebookRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &ManagedNotebookClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultManagedNotebookRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://notebooks.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://notebooks.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://notebooks.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *managedNotebookRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *managedNotebookRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *managedNotebookRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *managedNotebookGRPCClient) ListRuntimes(ctx context.Context, req *notebookspb.ListRuntimesRequest, opts ...gax.CallOption) *RuntimeIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1054,121 +1207,1644 @@ func (c *managedNotebookGRPCClient) ListOperations(ctx context.Context, req *lon return it } -// CreateRuntimeOperation manages a long-running operation from CreateRuntime. -type CreateRuntimeOperation struct { - lro *longrunning.Operation -} +// ListRuntimes lists Runtimes in a given project and location. +func (c *managedNotebookRESTClient) ListRuntimes(ctx context.Context, req *notebookspb.ListRuntimesRequest, opts ...gax.CallOption) *RuntimeIterator { + it := &RuntimeIterator{} + req = proto.Clone(req).(*notebookspb.ListRuntimesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*notebookspb.Runtime, string, error) { + resp := ¬ebookspb.ListRuntimesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/runtimes", req.GetParent()) -// CreateRuntimeOperation returns a new CreateRuntimeOperation from a given name. -// The name must be that of a previously created CreateRuntimeOperation, possibly from a different process. -func (c *managedNotebookGRPCClient) CreateRuntimeOperation(name string) *CreateRuntimeOperation { - return &CreateRuntimeOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *CreateRuntimeOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Runtime, error) { - var resp notebookspb.Runtime - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { - return nil, err + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetRuntimes(), resp.GetNextPageToken(), nil } - return &resp, nil -} -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *CreateRuntimeOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Runtime, error) { - var resp notebookspb.Runtime - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { - return nil, err - } - if !op.Done() { - return nil, 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 } - return &resp, nil + + it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it } -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *CreateRuntimeOperation) Metadata() (*notebookspb.OperationMetadata, error) { - var meta notebookspb.OperationMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { +// GetRuntime gets details of a single Runtime. The location must be a regional endpoint +// rather than zonal. +func (c *managedNotebookRESTClient) GetRuntime(ctx context.Context, req *notebookspb.GetRuntimeRequest, opts ...gax.CallOption) (*notebookspb.Runtime, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - return &meta, nil -} + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) -// Done reports whether the long-running operation has completed. -func (op *CreateRuntimeOperation) Done() bool { - return op.lro.Done() -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") -// 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 *CreateRuntimeOperation) Name() string { - return op.lro.Name() -} + baseUrl.RawQuery = params.Encode() -// DeleteRuntimeOperation manages a long-running operation from DeleteRuntime. -type DeleteRuntimeOperation struct { - lro *longrunning.Operation -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) -// DeleteRuntimeOperation returns a new DeleteRuntimeOperation from a given name. -// The name must be that of a previously created DeleteRuntimeOperation, possibly from a different process. -func (c *managedNotebookGRPCClient) DeleteRuntimeOperation(name string) *DeleteRuntimeOperation { - return &DeleteRuntimeOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetRuntime[0:len((*c.CallOptions).GetRuntime):len((*c.CallOptions).GetRuntime)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := ¬ebookspb.Runtime{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *DeleteRuntimeOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { - return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) -} + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *DeleteRuntimeOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { - return op.lro.Poll(ctx, nil, opts...) + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil } -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *DeleteRuntimeOperation) Metadata() (*notebookspb.OperationMetadata, error) { - var meta notebookspb.OperationMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { +// CreateRuntime creates a new Runtime in a given project and location. +func (c *managedNotebookRESTClient) CreateRuntime(ctx context.Context, req *notebookspb.CreateRuntimeRequest, opts ...gax.CallOption) (*CreateRuntimeOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetRuntime() + jsonReq, err := m.Marshal(body) + if err != nil { return nil, err } - return &meta, nil -} + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/runtimes", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + params.Add("runtimeId", fmt.Sprintf("%v", req.GetRuntimeId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateRuntimeOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateRuntime update Notebook Runtime configuration. +func (c *managedNotebookRESTClient) UpdateRuntime(ctx context.Context, req *notebookspb.UpdateRuntimeRequest, opts ...gax.CallOption) (*UpdateRuntimeOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetRuntime() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetRuntime().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "runtime.name", url.QueryEscape(req.GetRuntime().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateRuntimeOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteRuntime deletes a single Runtime. +func (c *managedNotebookRESTClient) DeleteRuntime(ctx context.Context, req *notebookspb.DeleteRuntimeRequest, opts ...gax.CallOption) (*DeleteRuntimeOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteRuntimeOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// StartRuntime starts a Managed Notebook Runtime. +// Perform “Start” on GPU instances; “Resume” on CPU instances +// See: +// https://cloud.google.com/compute/docs/instances/stop-start-instance (at https://cloud.google.com/compute/docs/instances/stop-start-instance) +// https://cloud.google.com/compute/docs/instances/suspend-resume-instance (at https://cloud.google.com/compute/docs/instances/suspend-resume-instance) +func (c *managedNotebookRESTClient) StartRuntime(ctx context.Context, req *notebookspb.StartRuntimeRequest, opts ...gax.CallOption) (*StartRuntimeOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:start", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &StartRuntimeOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// StopRuntime stops a Managed Notebook Runtime. +// Perform “Stop” on GPU instances; “Suspend” on CPU instances +// See: +// https://cloud.google.com/compute/docs/instances/stop-start-instance (at https://cloud.google.com/compute/docs/instances/stop-start-instance) +// https://cloud.google.com/compute/docs/instances/suspend-resume-instance (at https://cloud.google.com/compute/docs/instances/suspend-resume-instance) +func (c *managedNotebookRESTClient) StopRuntime(ctx context.Context, req *notebookspb.StopRuntimeRequest, opts ...gax.CallOption) (*StopRuntimeOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:stop", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &StopRuntimeOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// SwitchRuntime switch a Managed Notebook Runtime. +func (c *managedNotebookRESTClient) SwitchRuntime(ctx context.Context, req *notebookspb.SwitchRuntimeRequest, opts ...gax.CallOption) (*SwitchRuntimeOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:switch", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &SwitchRuntimeOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ResetRuntime resets a Managed Notebook Runtime. +func (c *managedNotebookRESTClient) ResetRuntime(ctx context.Context, req *notebookspb.ResetRuntimeRequest, opts ...gax.CallOption) (*ResetRuntimeOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:reset", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &ResetRuntimeOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpgradeRuntime upgrades a Managed Notebook Runtime to the latest version. +func (c *managedNotebookRESTClient) UpgradeRuntime(ctx context.Context, req *notebookspb.UpgradeRuntimeRequest, opts ...gax.CallOption) (*UpgradeRuntimeOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:upgrade", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpgradeRuntimeOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ReportRuntimeEvent report and process a runtime event. +func (c *managedNotebookRESTClient) ReportRuntimeEvent(ctx context.Context, req *notebookspb.ReportRuntimeEventRequest, opts ...gax.CallOption) (*ReportRuntimeEventOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:reportEvent", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &ReportRuntimeEventOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// RefreshRuntimeTokenInternal gets an access token for the consumer service account that the customer +// attached to the runtime. Only accessible from the tenant instance. +func (c *managedNotebookRESTClient) RefreshRuntimeTokenInternal(ctx context.Context, req *notebookspb.RefreshRuntimeTokenInternalRequest, opts ...gax.CallOption) (*notebookspb.RefreshRuntimeTokenInternalResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:refreshRuntimeTokenInternal", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).RefreshRuntimeTokenInternal[0:len((*c.CallOptions).RefreshRuntimeTokenInternal):len((*c.CallOptions).RefreshRuntimeTokenInternal)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := ¬ebookspb.RefreshRuntimeTokenInternalResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DiagnoseRuntime creates a Diagnostic File and runs Diagnostic Tool given a Runtime. +func (c *managedNotebookRESTClient) DiagnoseRuntime(ctx context.Context, req *notebookspb.DiagnoseRuntimeRequest, opts ...gax.CallOption) (*DiagnoseRuntimeOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:diagnose", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DiagnoseRuntimeOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetLocation gets information about a location. +func (c *managedNotebookRESTClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *managedNotebookRESTClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetIamPolicy gets the access control policy for a resource. Returns an empty policy +// if the resource exists and does not have a policy set. +func (c *managedNotebookRESTClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:getIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetOptions().GetRequestedPolicyVersion() != 0 { + params.Add("options.requestedPolicyVersion", fmt.Sprintf("%v", req.GetOptions().GetRequestedPolicyVersion())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SetIamPolicy sets the access control policy on the specified resource. Replaces +// any existing policy. +// +// Can return NOT_FOUND, INVALID_ARGUMENT, and PERMISSION_DENIED +// errors. +func (c *managedNotebookRESTClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:setIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// TestIamPermissions returns permissions that a caller has on the specified resource. If the +// resource does not exist, this will return an empty set of +// permissions, not a NOT_FOUND error. +// +// Note: This operation is designed to be used for building +// permission-aware UIs and command-line tools, not for authorization +// checking. This operation may “fail open” without warning. +func (c *managedNotebookRESTClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:testIamPermissions", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.TestIamPermissionsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *managedNotebookRESTClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// DeleteOperation is a utility method from google.longrunning.Operations. +func (c *managedNotebookRESTClient) DeleteOperation(ctx context.Context, req *longrunningpb.DeleteOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *managedNotebookRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *managedNotebookRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CreateRuntimeOperation manages a long-running operation from CreateRuntime. +type CreateRuntimeOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateRuntimeOperation returns a new CreateRuntimeOperation from a given name. +// The name must be that of a previously created CreateRuntimeOperation, possibly from a different process. +func (c *managedNotebookGRPCClient) CreateRuntimeOperation(name string) *CreateRuntimeOperation { + return &CreateRuntimeOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateRuntimeOperation returns a new CreateRuntimeOperation from a given name. +// The name must be that of a previously created CreateRuntimeOperation, possibly from a different process. +func (c *managedNotebookRESTClient) CreateRuntimeOperation(name string) *CreateRuntimeOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateRuntimeOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CreateRuntimeOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Runtime, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp notebookspb.Runtime + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *CreateRuntimeOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Runtime, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp notebookspb.Runtime + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *CreateRuntimeOperation) Metadata() (*notebookspb.OperationMetadata, error) { + var meta notebookspb.OperationMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *CreateRuntimeOperation) Done() bool { + return op.lro.Done() +} + +// 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 *CreateRuntimeOperation) Name() string { + return op.lro.Name() +} + +// DeleteRuntimeOperation manages a long-running operation from DeleteRuntime. +type DeleteRuntimeOperation struct { + lro *longrunning.Operation + pollPath string +} + +// DeleteRuntimeOperation returns a new DeleteRuntimeOperation from a given name. +// The name must be that of a previously created DeleteRuntimeOperation, possibly from a different process. +func (c *managedNotebookGRPCClient) DeleteRuntimeOperation(name string) *DeleteRuntimeOperation { + return &DeleteRuntimeOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// DeleteRuntimeOperation returns a new DeleteRuntimeOperation from a given name. +// The name must be that of a previously created DeleteRuntimeOperation, possibly from a different process. +func (c *managedNotebookRESTClient) DeleteRuntimeOperation(name string) *DeleteRuntimeOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteRuntimeOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *DeleteRuntimeOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *DeleteRuntimeOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + return op.lro.Poll(ctx, nil, opts...) +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *DeleteRuntimeOperation) Metadata() (*notebookspb.OperationMetadata, error) { + var meta notebookspb.OperationMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} // Done reports whether the long-running operation has completed. func (op *DeleteRuntimeOperation) Done() bool { @@ -1183,7 +2859,8 @@ func (op *DeleteRuntimeOperation) Name() string { // DiagnoseRuntimeOperation manages a long-running operation from DiagnoseRuntime. type DiagnoseRuntimeOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DiagnoseRuntimeOperation returns a new DiagnoseRuntimeOperation from a given name. @@ -1194,10 +2871,21 @@ func (c *managedNotebookGRPCClient) DiagnoseRuntimeOperation(name string) *Diagn } } +// DiagnoseRuntimeOperation returns a new DiagnoseRuntimeOperation from a given name. +// The name must be that of a previously created DiagnoseRuntimeOperation, possibly from a different process. +func (c *managedNotebookRESTClient) DiagnoseRuntimeOperation(name string) *DiagnoseRuntimeOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DiagnoseRuntimeOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DiagnoseRuntimeOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Runtime, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp notebookspb.Runtime if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1215,6 +2903,7 @@ func (op *DiagnoseRuntimeOperation) Wait(ctx context.Context, opts ...gax.CallOp // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DiagnoseRuntimeOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Runtime, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp notebookspb.Runtime if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1252,7 +2941,8 @@ func (op *DiagnoseRuntimeOperation) Name() string { // ReportRuntimeEventOperation manages a long-running operation from ReportRuntimeEvent. type ReportRuntimeEventOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // ReportRuntimeEventOperation returns a new ReportRuntimeEventOperation from a given name. @@ -1263,10 +2953,21 @@ func (c *managedNotebookGRPCClient) ReportRuntimeEventOperation(name string) *Re } } +// ReportRuntimeEventOperation returns a new ReportRuntimeEventOperation from a given name. +// The name must be that of a previously created ReportRuntimeEventOperation, possibly from a different process. +func (c *managedNotebookRESTClient) ReportRuntimeEventOperation(name string) *ReportRuntimeEventOperation { + override := fmt.Sprintf("/v1/%s", name) + return &ReportRuntimeEventOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *ReportRuntimeEventOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Runtime, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp notebookspb.Runtime if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1284,6 +2985,7 @@ func (op *ReportRuntimeEventOperation) Wait(ctx context.Context, opts ...gax.Cal // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *ReportRuntimeEventOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Runtime, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp notebookspb.Runtime if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1321,7 +3023,8 @@ func (op *ReportRuntimeEventOperation) Name() string { // ResetRuntimeOperation manages a long-running operation from ResetRuntime. type ResetRuntimeOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // ResetRuntimeOperation returns a new ResetRuntimeOperation from a given name. @@ -1332,10 +3035,21 @@ func (c *managedNotebookGRPCClient) ResetRuntimeOperation(name string) *ResetRun } } +// ResetRuntimeOperation returns a new ResetRuntimeOperation from a given name. +// The name must be that of a previously created ResetRuntimeOperation, possibly from a different process. +func (c *managedNotebookRESTClient) ResetRuntimeOperation(name string) *ResetRuntimeOperation { + override := fmt.Sprintf("/v1/%s", name) + return &ResetRuntimeOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *ResetRuntimeOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Runtime, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp notebookspb.Runtime if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1353,6 +3067,7 @@ func (op *ResetRuntimeOperation) Wait(ctx context.Context, opts ...gax.CallOptio // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *ResetRuntimeOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Runtime, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp notebookspb.Runtime if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1390,7 +3105,8 @@ func (op *ResetRuntimeOperation) Name() string { // StartRuntimeOperation manages a long-running operation from StartRuntime. type StartRuntimeOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // StartRuntimeOperation returns a new StartRuntimeOperation from a given name. @@ -1401,10 +3117,21 @@ func (c *managedNotebookGRPCClient) StartRuntimeOperation(name string) *StartRun } } +// StartRuntimeOperation returns a new StartRuntimeOperation from a given name. +// The name must be that of a previously created StartRuntimeOperation, possibly from a different process. +func (c *managedNotebookRESTClient) StartRuntimeOperation(name string) *StartRuntimeOperation { + override := fmt.Sprintf("/v1/%s", name) + return &StartRuntimeOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *StartRuntimeOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Runtime, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp notebookspb.Runtime if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1422,6 +3149,7 @@ func (op *StartRuntimeOperation) Wait(ctx context.Context, opts ...gax.CallOptio // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *StartRuntimeOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Runtime, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp notebookspb.Runtime if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1459,7 +3187,8 @@ func (op *StartRuntimeOperation) Name() string { // StopRuntimeOperation manages a long-running operation from StopRuntime. type StopRuntimeOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // StopRuntimeOperation returns a new StopRuntimeOperation from a given name. @@ -1470,10 +3199,21 @@ func (c *managedNotebookGRPCClient) StopRuntimeOperation(name string) *StopRunti } } +// StopRuntimeOperation returns a new StopRuntimeOperation from a given name. +// The name must be that of a previously created StopRuntimeOperation, possibly from a different process. +func (c *managedNotebookRESTClient) StopRuntimeOperation(name string) *StopRuntimeOperation { + override := fmt.Sprintf("/v1/%s", name) + return &StopRuntimeOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *StopRuntimeOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Runtime, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp notebookspb.Runtime if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1491,6 +3231,7 @@ func (op *StopRuntimeOperation) Wait(ctx context.Context, opts ...gax.CallOption // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *StopRuntimeOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Runtime, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp notebookspb.Runtime if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1528,7 +3269,8 @@ func (op *StopRuntimeOperation) Name() string { // SwitchRuntimeOperation manages a long-running operation from SwitchRuntime. type SwitchRuntimeOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // SwitchRuntimeOperation returns a new SwitchRuntimeOperation from a given name. @@ -1539,10 +3281,21 @@ func (c *managedNotebookGRPCClient) SwitchRuntimeOperation(name string) *SwitchR } } +// SwitchRuntimeOperation returns a new SwitchRuntimeOperation from a given name. +// The name must be that of a previously created SwitchRuntimeOperation, possibly from a different process. +func (c *managedNotebookRESTClient) SwitchRuntimeOperation(name string) *SwitchRuntimeOperation { + override := fmt.Sprintf("/v1/%s", name) + return &SwitchRuntimeOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *SwitchRuntimeOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Runtime, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp notebookspb.Runtime if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1560,6 +3313,7 @@ func (op *SwitchRuntimeOperation) Wait(ctx context.Context, opts ...gax.CallOpti // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *SwitchRuntimeOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Runtime, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp notebookspb.Runtime if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1597,7 +3351,8 @@ func (op *SwitchRuntimeOperation) Name() string { // UpdateRuntimeOperation manages a long-running operation from UpdateRuntime. type UpdateRuntimeOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateRuntimeOperation returns a new UpdateRuntimeOperation from a given name. @@ -1608,10 +3363,21 @@ func (c *managedNotebookGRPCClient) UpdateRuntimeOperation(name string) *UpdateR } } +// UpdateRuntimeOperation returns a new UpdateRuntimeOperation from a given name. +// The name must be that of a previously created UpdateRuntimeOperation, possibly from a different process. +func (c *managedNotebookRESTClient) UpdateRuntimeOperation(name string) *UpdateRuntimeOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateRuntimeOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateRuntimeOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Runtime, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp notebookspb.Runtime if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1629,6 +3395,7 @@ func (op *UpdateRuntimeOperation) Wait(ctx context.Context, opts ...gax.CallOpti // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateRuntimeOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Runtime, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp notebookspb.Runtime if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1666,7 +3433,8 @@ func (op *UpdateRuntimeOperation) Name() string { // UpgradeRuntimeOperation manages a long-running operation from UpgradeRuntime. type UpgradeRuntimeOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpgradeRuntimeOperation returns a new UpgradeRuntimeOperation from a given name. @@ -1677,10 +3445,21 @@ func (c *managedNotebookGRPCClient) UpgradeRuntimeOperation(name string) *Upgrad } } +// UpgradeRuntimeOperation returns a new UpgradeRuntimeOperation from a given name. +// The name must be that of a previously created UpgradeRuntimeOperation, possibly from a different process. +func (c *managedNotebookRESTClient) UpgradeRuntimeOperation(name string) *UpgradeRuntimeOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpgradeRuntimeOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpgradeRuntimeOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Runtime, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp notebookspb.Runtime if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1698,6 +3477,7 @@ func (op *UpgradeRuntimeOperation) Wait(ctx context.Context, opts ...gax.CallOpt // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpgradeRuntimeOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Runtime, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp notebookspb.Runtime if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/notebooks/apiv1/managed_notebook_client_example_test.go b/notebooks/apiv1/managed_notebook_client_example_test.go index 7357e6413cf9..c453696bad9e 100644 --- a/notebooks/apiv1/managed_notebook_client_example_test.go +++ b/notebooks/apiv1/managed_notebook_client_example_test.go @@ -44,6 +44,23 @@ func ExampleNewManagedNotebookClient() { _ = c } +func ExampleNewManagedNotebookRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := notebooks.NewManagedNotebookRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleManagedNotebookClient_ListRuntimes() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/notebooks/apiv1/notebook_client.go b/notebooks/apiv1/notebook_client.go index 7a973144eee9..34e1e96bde8c 100644 --- a/notebooks/apiv1/notebook_client.go +++ b/notebooks/apiv1/notebook_client.go @@ -17,9 +17,12 @@ package notebooks import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,16 +30,19 @@ import ( lroauto "cloud.google.com/go/longrunning/autogen" notebookspb "cloud.google.com/go/notebooks/apiv1/notebookspb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" iampb "google.golang.org/genproto/googleapis/iam/v1" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -180,6 +186,82 @@ func defaultNotebookCallOptions() *NotebookCallOptions { } } +func defaultNotebookRESTCallOptions() *NotebookCallOptions { + return &NotebookCallOptions{ + ListInstances: []gax.CallOption{}, + GetInstance: []gax.CallOption{}, + CreateInstance: []gax.CallOption{}, + RegisterInstance: []gax.CallOption{}, + SetInstanceAccelerator: []gax.CallOption{}, + SetInstanceMachineType: []gax.CallOption{}, + UpdateInstanceConfig: []gax.CallOption{}, + UpdateShieldedInstanceConfig: []gax.CallOption{}, + SetInstanceLabels: []gax.CallOption{}, + UpdateInstanceMetadataItems: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeleteInstance: []gax.CallOption{}, + StartInstance: []gax.CallOption{}, + StopInstance: []gax.CallOption{}, + ResetInstance: []gax.CallOption{}, + ReportInstanceInfo: []gax.CallOption{}, + IsInstanceUpgradeable: []gax.CallOption{}, + GetInstanceHealth: []gax.CallOption{}, + UpgradeInstance: []gax.CallOption{}, + RollbackInstance: []gax.CallOption{}, + DiagnoseInstance: []gax.CallOption{}, + UpgradeInstanceInternal: []gax.CallOption{}, + ListEnvironments: []gax.CallOption{}, + GetEnvironment: []gax.CallOption{}, + CreateEnvironment: []gax.CallOption{}, + DeleteEnvironment: []gax.CallOption{}, + ListSchedules: []gax.CallOption{}, + GetSchedule: []gax.CallOption{}, + DeleteSchedule: []gax.CallOption{}, + CreateSchedule: []gax.CallOption{}, + TriggerSchedule: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListExecutions: []gax.CallOption{}, + GetExecution: []gax.CallOption{}, + DeleteExecution: []gax.CallOption{}, + CreateExecution: []gax.CallOption{}, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + GetIamPolicy: []gax.CallOption{}, + SetIamPolicy: []gax.CallOption{}, + TestIamPermissions: []gax.CallOption{}, + CancelOperation: []gax.CallOption{}, + DeleteOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 300000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + } +} + // internalNotebookClient is an interface that defines the methods available from Notebooks API. type internalNotebookClient interface { Close() error @@ -770,6 +852,89 @@ func (c *notebookGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type notebookRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing NotebookClient + CallOptions **NotebookCallOptions +} + +// NewNotebookRESTClient creates a new notebook service rest client. +// +// API v1 service for Cloud AI Platform Notebooks. +func NewNotebookRESTClient(ctx context.Context, opts ...option.ClientOption) (*NotebookClient, error) { + clientOpts := append(defaultNotebookRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultNotebookRESTCallOptions() + c := ¬ebookRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &NotebookClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultNotebookRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://notebooks.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://notebooks.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://notebooks.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *notebookRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *notebookRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *notebookRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *notebookGRPCClient) ListInstances(ctx context.Context, req *notebookspb.ListInstancesRequest, opts ...gax.CallOption) *InstanceIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1857,109 +2022,3053 @@ func (c *notebookGRPCClient) ListOperations(ctx context.Context, req *longrunnin return it } -// CreateEnvironmentOperation manages a long-running operation from CreateEnvironment. -type CreateEnvironmentOperation struct { - lro *longrunning.Operation -} +// ListInstances lists instances in a given project and location. +func (c *notebookRESTClient) ListInstances(ctx context.Context, req *notebookspb.ListInstancesRequest, opts ...gax.CallOption) *InstanceIterator { + it := &InstanceIterator{} + req = proto.Clone(req).(*notebookspb.ListInstancesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*notebookspb.Instance, string, error) { + resp := ¬ebookspb.ListInstancesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/instances", req.GetParent()) -// CreateEnvironmentOperation returns a new CreateEnvironmentOperation from a given name. -// The name must be that of a previously created CreateEnvironmentOperation, possibly from a different process. -func (c *notebookGRPCClient) CreateEnvironmentOperation(name string) *CreateEnvironmentOperation { - return &CreateEnvironmentOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *CreateEnvironmentOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Environment, error) { - var resp notebookspb.Environment - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { - return nil, err + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetInstances(), resp.GetNextPageToken(), nil } - return &resp, nil -} -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *CreateEnvironmentOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Environment, error) { - var resp notebookspb.Environment - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { - return nil, err - } - if !op.Done() { - return nil, 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 } - return &resp, nil + + it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it } -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *CreateEnvironmentOperation) Metadata() (*notebookspb.OperationMetadata, error) { - var meta notebookspb.OperationMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { +// GetInstance gets details of a single Instance. +func (c *notebookRESTClient) GetInstance(ctx context.Context, req *notebookspb.GetInstanceRequest, opts ...gax.CallOption) (*notebookspb.Instance, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - return &meta, nil -} + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) -// Done reports whether the long-running operation has completed. -func (op *CreateEnvironmentOperation) Done() bool { - return op.lro.Done() -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") -// 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 *CreateEnvironmentOperation) Name() string { - return op.lro.Name() -} + baseUrl.RawQuery = params.Encode() -// CreateExecutionOperation manages a long-running operation from CreateExecution. -type CreateExecutionOperation struct { - lro *longrunning.Operation -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) -// CreateExecutionOperation returns a new CreateExecutionOperation from a given name. -// The name must be that of a previously created CreateExecutionOperation, possibly from a different process. -func (c *notebookGRPCClient) CreateExecutionOperation(name string) *CreateExecutionOperation { - return &CreateExecutionOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetInstance[0:len((*c.CallOptions).GetInstance):len((*c.CallOptions).GetInstance)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := ¬ebookspb.Instance{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e } + return resp, nil } -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *CreateExecutionOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Execution, error) { - var resp notebookspb.Execution - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { +// CreateInstance creates a new Instance in a given project and location. +func (c *notebookRESTClient) CreateInstance(ctx context.Context, req *notebookspb.CreateInstanceRequest, opts ...gax.CallOption) (*CreateInstanceOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetInstance() + jsonReq, err := m.Marshal(body) + if err != nil { return nil, err } - return &resp, nil -} -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/instances", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("instanceId", fmt.Sprintf("%v", req.GetInstanceId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// RegisterInstance registers an existing legacy notebook instance to the Notebooks API server. +// Legacy instances are instances created with the legacy Compute Engine +// calls. They are not manageable by the Notebooks API out of the box. This +// call makes these instances manageable by the Notebooks API. +func (c *notebookRESTClient) RegisterInstance(ctx context.Context, req *notebookspb.RegisterInstanceRequest, opts ...gax.CallOption) (*RegisterInstanceOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/instances:register", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &RegisterInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// SetInstanceAccelerator updates the guest accelerators of a single Instance. +func (c *notebookRESTClient) SetInstanceAccelerator(ctx context.Context, req *notebookspb.SetInstanceAcceleratorRequest, opts ...gax.CallOption) (*SetInstanceAcceleratorOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:setAccelerator", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &SetInstanceAcceleratorOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// SetInstanceMachineType updates the machine type of a single Instance. +func (c *notebookRESTClient) SetInstanceMachineType(ctx context.Context, req *notebookspb.SetInstanceMachineTypeRequest, opts ...gax.CallOption) (*SetInstanceMachineTypeOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:setMachineType", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &SetInstanceMachineTypeOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateInstanceConfig update Notebook Instance configurations. +func (c *notebookRESTClient) UpdateInstanceConfig(ctx context.Context, req *notebookspb.UpdateInstanceConfigRequest, opts ...gax.CallOption) (*UpdateInstanceConfigOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:updateConfig", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateInstanceConfigOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateShieldedInstanceConfig updates the Shielded instance configuration of a single Instance. +func (c *notebookRESTClient) UpdateShieldedInstanceConfig(ctx context.Context, req *notebookspb.UpdateShieldedInstanceConfigRequest, opts ...gax.CallOption) (*UpdateShieldedInstanceConfigOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:updateShieldedInstanceConfig", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateShieldedInstanceConfigOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// SetInstanceLabels replaces all the labels of an Instance. +func (c *notebookRESTClient) SetInstanceLabels(ctx context.Context, req *notebookspb.SetInstanceLabelsRequest, opts ...gax.CallOption) (*SetInstanceLabelsOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:setLabels", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &SetInstanceLabelsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateInstanceMetadataItems add/update metadata items for an instance. +func (c *notebookRESTClient) UpdateInstanceMetadataItems(ctx context.Context, req *notebookspb.UpdateInstanceMetadataItemsRequest, opts ...gax.CallOption) (*notebookspb.UpdateInstanceMetadataItemsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:updateMetadataItems", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateInstanceMetadataItems[0:len((*c.CallOptions).UpdateInstanceMetadataItems):len((*c.CallOptions).UpdateInstanceMetadataItems)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := ¬ebookspb.UpdateInstanceMetadataItemsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteInstance deletes a single Instance. +func (c *notebookRESTClient) DeleteInstance(ctx context.Context, req *notebookspb.DeleteInstanceRequest, opts ...gax.CallOption) (*DeleteInstanceOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// StartInstance starts a notebook instance. +func (c *notebookRESTClient) StartInstance(ctx context.Context, req *notebookspb.StartInstanceRequest, opts ...gax.CallOption) (*StartInstanceOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:start", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &StartInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// StopInstance stops a notebook instance. +func (c *notebookRESTClient) StopInstance(ctx context.Context, req *notebookspb.StopInstanceRequest, opts ...gax.CallOption) (*StopInstanceOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:stop", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &StopInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ResetInstance resets a notebook instance. +func (c *notebookRESTClient) ResetInstance(ctx context.Context, req *notebookspb.ResetInstanceRequest, opts ...gax.CallOption) (*ResetInstanceOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:reset", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &ResetInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ReportInstanceInfo allows notebook instances to +// report their latest instance information to the Notebooks +// API server. The server will merge the reported information to +// the instance metadata store. Do not use this method directly. +func (c *notebookRESTClient) ReportInstanceInfo(ctx context.Context, req *notebookspb.ReportInstanceInfoRequest, opts ...gax.CallOption) (*ReportInstanceInfoOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:report", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &ReportInstanceInfoOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// IsInstanceUpgradeable check if a notebook instance is upgradable. +func (c *notebookRESTClient) IsInstanceUpgradeable(ctx context.Context, req *notebookspb.IsInstanceUpgradeableRequest, opts ...gax.CallOption) (*notebookspb.IsInstanceUpgradeableResponse, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:isUpgradeable", req.GetNotebookInstance()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetType() != 0 { + params.Add("type", fmt.Sprintf("%v", req.GetType())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "notebook_instance", url.QueryEscape(req.GetNotebookInstance()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).IsInstanceUpgradeable[0:len((*c.CallOptions).IsInstanceUpgradeable):len((*c.CallOptions).IsInstanceUpgradeable)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := ¬ebookspb.IsInstanceUpgradeableResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetInstanceHealth check if a notebook instance is healthy. +func (c *notebookRESTClient) GetInstanceHealth(ctx context.Context, req *notebookspb.GetInstanceHealthRequest, opts ...gax.CallOption) (*notebookspb.GetInstanceHealthResponse, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:getInstanceHealth", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetInstanceHealth[0:len((*c.CallOptions).GetInstanceHealth):len((*c.CallOptions).GetInstanceHealth)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := ¬ebookspb.GetInstanceHealthResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpgradeInstance upgrades a notebook instance to the latest version. +func (c *notebookRESTClient) UpgradeInstance(ctx context.Context, req *notebookspb.UpgradeInstanceRequest, opts ...gax.CallOption) (*UpgradeInstanceOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:upgrade", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpgradeInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// RollbackInstance rollbacks a notebook instance to the previous version. +func (c *notebookRESTClient) RollbackInstance(ctx context.Context, req *notebookspb.RollbackInstanceRequest, opts ...gax.CallOption) (*RollbackInstanceOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:rollback", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &RollbackInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DiagnoseInstance creates a Diagnostic File and runs Diagnostic Tool given an Instance. +func (c *notebookRESTClient) DiagnoseInstance(ctx context.Context, req *notebookspb.DiagnoseInstanceRequest, opts ...gax.CallOption) (*DiagnoseInstanceOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:diagnose", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DiagnoseInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpgradeInstanceInternal allows notebook instances to +// call this endpoint to upgrade themselves. Do not use this method directly. +func (c *notebookRESTClient) UpgradeInstanceInternal(ctx context.Context, req *notebookspb.UpgradeInstanceInternalRequest, opts ...gax.CallOption) (*UpgradeInstanceInternalOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:upgradeInternal", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpgradeInstanceInternalOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListEnvironments lists environments in a project. +func (c *notebookRESTClient) ListEnvironments(ctx context.Context, req *notebookspb.ListEnvironmentsRequest, opts ...gax.CallOption) *EnvironmentIterator { + it := &EnvironmentIterator{} + req = proto.Clone(req).(*notebookspb.ListEnvironmentsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*notebookspb.Environment, string, error) { + resp := ¬ebookspb.ListEnvironmentsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/environments", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetEnvironments(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetEnvironment gets details of a single Environment. +func (c *notebookRESTClient) GetEnvironment(ctx context.Context, req *notebookspb.GetEnvironmentRequest, opts ...gax.CallOption) (*notebookspb.Environment, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetEnvironment[0:len((*c.CallOptions).GetEnvironment):len((*c.CallOptions).GetEnvironment)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := ¬ebookspb.Environment{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateEnvironment creates a new Environment. +func (c *notebookRESTClient) CreateEnvironment(ctx context.Context, req *notebookspb.CreateEnvironmentRequest, opts ...gax.CallOption) (*CreateEnvironmentOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetEnvironment() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/environments", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("environmentId", fmt.Sprintf("%v", req.GetEnvironmentId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateEnvironmentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteEnvironment deletes a single Environment. +func (c *notebookRESTClient) DeleteEnvironment(ctx context.Context, req *notebookspb.DeleteEnvironmentRequest, opts ...gax.CallOption) (*DeleteEnvironmentOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteEnvironmentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListSchedules lists schedules in a given project and location. +func (c *notebookRESTClient) ListSchedules(ctx context.Context, req *notebookspb.ListSchedulesRequest, opts ...gax.CallOption) *ScheduleIterator { + it := &ScheduleIterator{} + req = proto.Clone(req).(*notebookspb.ListSchedulesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*notebookspb.Schedule, string, error) { + resp := ¬ebookspb.ListSchedulesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/schedules", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetSchedules(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetSchedule gets details of schedule +func (c *notebookRESTClient) GetSchedule(ctx context.Context, req *notebookspb.GetScheduleRequest, opts ...gax.CallOption) (*notebookspb.Schedule, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetSchedule[0:len((*c.CallOptions).GetSchedule):len((*c.CallOptions).GetSchedule)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := ¬ebookspb.Schedule{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteSchedule deletes schedule and all underlying jobs +func (c *notebookRESTClient) DeleteSchedule(ctx context.Context, req *notebookspb.DeleteScheduleRequest, opts ...gax.CallOption) (*DeleteScheduleOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteScheduleOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// CreateSchedule creates a new Scheduled Notebook in a given project and location. +func (c *notebookRESTClient) CreateSchedule(ctx context.Context, req *notebookspb.CreateScheduleRequest, opts ...gax.CallOption) (*CreateScheduleOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetSchedule() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/schedules", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("scheduleId", fmt.Sprintf("%v", req.GetScheduleId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateScheduleOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// TriggerSchedule triggers execution of an existing schedule. +func (c *notebookRESTClient) TriggerSchedule(ctx context.Context, req *notebookspb.TriggerScheduleRequest, opts ...gax.CallOption) (*TriggerScheduleOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:trigger", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &TriggerScheduleOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListExecutions lists executions in a given project and location +func (c *notebookRESTClient) ListExecutions(ctx context.Context, req *notebookspb.ListExecutionsRequest, opts ...gax.CallOption) *ExecutionIterator { + it := &ExecutionIterator{} + req = proto.Clone(req).(*notebookspb.ListExecutionsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*notebookspb.Execution, string, error) { + resp := ¬ebookspb.ListExecutionsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/executions", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetExecutions(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetExecution gets details of executions +func (c *notebookRESTClient) GetExecution(ctx context.Context, req *notebookspb.GetExecutionRequest, opts ...gax.CallOption) (*notebookspb.Execution, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetExecution[0:len((*c.CallOptions).GetExecution):len((*c.CallOptions).GetExecution)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := ¬ebookspb.Execution{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteExecution deletes execution +func (c *notebookRESTClient) DeleteExecution(ctx context.Context, req *notebookspb.DeleteExecutionRequest, opts ...gax.CallOption) (*DeleteExecutionOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteExecutionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// CreateExecution creates a new Execution in a given project and location. +func (c *notebookRESTClient) CreateExecution(ctx context.Context, req *notebookspb.CreateExecutionRequest, opts ...gax.CallOption) (*CreateExecutionOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetExecution() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/executions", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("executionId", fmt.Sprintf("%v", req.GetExecutionId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateExecutionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetLocation gets information about a location. +func (c *notebookRESTClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *notebookRESTClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetIamPolicy gets the access control policy for a resource. Returns an empty policy +// if the resource exists and does not have a policy set. +func (c *notebookRESTClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:getIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetOptions().GetRequestedPolicyVersion() != 0 { + params.Add("options.requestedPolicyVersion", fmt.Sprintf("%v", req.GetOptions().GetRequestedPolicyVersion())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SetIamPolicy sets the access control policy on the specified resource. Replaces +// any existing policy. +// +// Can return NOT_FOUND, INVALID_ARGUMENT, and PERMISSION_DENIED +// errors. +func (c *notebookRESTClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:setIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// TestIamPermissions returns permissions that a caller has on the specified resource. If the +// resource does not exist, this will return an empty set of +// permissions, not a NOT_FOUND error. +// +// Note: This operation is designed to be used for building +// permission-aware UIs and command-line tools, not for authorization +// checking. This operation may “fail open” without warning. +func (c *notebookRESTClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:testIamPermissions", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.TestIamPermissionsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *notebookRESTClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// DeleteOperation is a utility method from google.longrunning.Operations. +func (c *notebookRESTClient) DeleteOperation(ctx context.Context, req *longrunningpb.DeleteOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *notebookRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *notebookRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CreateEnvironmentOperation manages a long-running operation from CreateEnvironment. +type CreateEnvironmentOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateEnvironmentOperation returns a new CreateEnvironmentOperation from a given name. +// The name must be that of a previously created CreateEnvironmentOperation, possibly from a different process. +func (c *notebookGRPCClient) CreateEnvironmentOperation(name string) *CreateEnvironmentOperation { + return &CreateEnvironmentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateEnvironmentOperation returns a new CreateEnvironmentOperation from a given name. +// The name must be that of a previously created CreateEnvironmentOperation, possibly from a different process. +func (c *notebookRESTClient) CreateEnvironmentOperation(name string) *CreateEnvironmentOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateEnvironmentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CreateEnvironmentOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Environment, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp notebookspb.Environment + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *CreateEnvironmentOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Environment, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp notebookspb.Environment + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *CreateEnvironmentOperation) Metadata() (*notebookspb.OperationMetadata, error) { + var meta notebookspb.OperationMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *CreateEnvironmentOperation) Done() bool { + return op.lro.Done() +} + +// 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 *CreateEnvironmentOperation) Name() string { + return op.lro.Name() +} + +// CreateExecutionOperation manages a long-running operation from CreateExecution. +type CreateExecutionOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateExecutionOperation returns a new CreateExecutionOperation from a given name. +// The name must be that of a previously created CreateExecutionOperation, possibly from a different process. +func (c *notebookGRPCClient) CreateExecutionOperation(name string) *CreateExecutionOperation { + return &CreateExecutionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateExecutionOperation returns a new CreateExecutionOperation from a given name. +// The name must be that of a previously created CreateExecutionOperation, possibly from a different process. +func (c *notebookRESTClient) CreateExecutionOperation(name string) *CreateExecutionOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateExecutionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CreateExecutionOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Execution, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp notebookspb.Execution + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateExecutionOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Execution, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp notebookspb.Execution if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1997,7 +5106,8 @@ func (op *CreateExecutionOperation) Name() string { // CreateInstanceOperation manages a long-running operation from CreateInstance. type CreateInstanceOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateInstanceOperation returns a new CreateInstanceOperation from a given name. @@ -2008,10 +5118,21 @@ func (c *notebookGRPCClient) CreateInstanceOperation(name string) *CreateInstanc } } +// CreateInstanceOperation returns a new CreateInstanceOperation from a given name. +// The name must be that of a previously created CreateInstanceOperation, possibly from a different process. +func (c *notebookRESTClient) CreateInstanceOperation(name string) *CreateInstanceOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp notebookspb.Instance if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2029,6 +5150,7 @@ func (op *CreateInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOpt // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateInstanceOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp notebookspb.Instance if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2066,7 +5188,8 @@ func (op *CreateInstanceOperation) Name() string { // CreateScheduleOperation manages a long-running operation from CreateSchedule. type CreateScheduleOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateScheduleOperation returns a new CreateScheduleOperation from a given name. @@ -2077,10 +5200,21 @@ func (c *notebookGRPCClient) CreateScheduleOperation(name string) *CreateSchedul } } +// CreateScheduleOperation returns a new CreateScheduleOperation from a given name. +// The name must be that of a previously created CreateScheduleOperation, possibly from a different process. +func (c *notebookRESTClient) CreateScheduleOperation(name string) *CreateScheduleOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateScheduleOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateScheduleOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Schedule, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp notebookspb.Schedule if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2098,6 +5232,7 @@ func (op *CreateScheduleOperation) Wait(ctx context.Context, opts ...gax.CallOpt // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateScheduleOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Schedule, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp notebookspb.Schedule if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2135,7 +5270,8 @@ func (op *CreateScheduleOperation) Name() string { // DeleteEnvironmentOperation manages a long-running operation from DeleteEnvironment. type DeleteEnvironmentOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteEnvironmentOperation returns a new DeleteEnvironmentOperation from a given name. @@ -2146,10 +5282,21 @@ func (c *notebookGRPCClient) DeleteEnvironmentOperation(name string) *DeleteEnvi } } +// DeleteEnvironmentOperation returns a new DeleteEnvironmentOperation from a given name. +// The name must be that of a previously created DeleteEnvironmentOperation, possibly from a different process. +func (c *notebookRESTClient) DeleteEnvironmentOperation(name string) *DeleteEnvironmentOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteEnvironmentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteEnvironmentOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -2163,6 +5310,7 @@ func (op *DeleteEnvironmentOperation) Wait(ctx context.Context, opts ...gax.Call // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteEnvironmentOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -2193,7 +5341,8 @@ func (op *DeleteEnvironmentOperation) Name() string { // DeleteExecutionOperation manages a long-running operation from DeleteExecution. type DeleteExecutionOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteExecutionOperation returns a new DeleteExecutionOperation from a given name. @@ -2204,10 +5353,21 @@ func (c *notebookGRPCClient) DeleteExecutionOperation(name string) *DeleteExecut } } +// DeleteExecutionOperation returns a new DeleteExecutionOperation from a given name. +// The name must be that of a previously created DeleteExecutionOperation, possibly from a different process. +func (c *notebookRESTClient) DeleteExecutionOperation(name string) *DeleteExecutionOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteExecutionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteExecutionOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -2221,6 +5381,7 @@ func (op *DeleteExecutionOperation) Wait(ctx context.Context, opts ...gax.CallOp // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteExecutionOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -2251,7 +5412,8 @@ func (op *DeleteExecutionOperation) Name() string { // DeleteInstanceOperation manages a long-running operation from DeleteInstance. type DeleteInstanceOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteInstanceOperation returns a new DeleteInstanceOperation from a given name. @@ -2262,10 +5424,21 @@ func (c *notebookGRPCClient) DeleteInstanceOperation(name string) *DeleteInstanc } } +// DeleteInstanceOperation returns a new DeleteInstanceOperation from a given name. +// The name must be that of a previously created DeleteInstanceOperation, possibly from a different process. +func (c *notebookRESTClient) DeleteInstanceOperation(name string) *DeleteInstanceOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -2279,6 +5452,7 @@ func (op *DeleteInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOpt // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteInstanceOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -2309,7 +5483,8 @@ func (op *DeleteInstanceOperation) Name() string { // DeleteScheduleOperation manages a long-running operation from DeleteSchedule. type DeleteScheduleOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteScheduleOperation returns a new DeleteScheduleOperation from a given name. @@ -2320,10 +5495,21 @@ func (c *notebookGRPCClient) DeleteScheduleOperation(name string) *DeleteSchedul } } +// DeleteScheduleOperation returns a new DeleteScheduleOperation from a given name. +// The name must be that of a previously created DeleteScheduleOperation, possibly from a different process. +func (c *notebookRESTClient) DeleteScheduleOperation(name string) *DeleteScheduleOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteScheduleOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteScheduleOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -2337,6 +5523,7 @@ func (op *DeleteScheduleOperation) Wait(ctx context.Context, opts ...gax.CallOpt // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteScheduleOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -2367,7 +5554,8 @@ func (op *DeleteScheduleOperation) Name() string { // DiagnoseInstanceOperation manages a long-running operation from DiagnoseInstance. type DiagnoseInstanceOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DiagnoseInstanceOperation returns a new DiagnoseInstanceOperation from a given name. @@ -2378,10 +5566,21 @@ func (c *notebookGRPCClient) DiagnoseInstanceOperation(name string) *DiagnoseIns } } +// DiagnoseInstanceOperation returns a new DiagnoseInstanceOperation from a given name. +// The name must be that of a previously created DiagnoseInstanceOperation, possibly from a different process. +func (c *notebookRESTClient) DiagnoseInstanceOperation(name string) *DiagnoseInstanceOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DiagnoseInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DiagnoseInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp notebookspb.Instance if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2399,6 +5598,7 @@ func (op *DiagnoseInstanceOperation) Wait(ctx context.Context, opts ...gax.CallO // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DiagnoseInstanceOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp notebookspb.Instance if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2436,7 +5636,8 @@ func (op *DiagnoseInstanceOperation) Name() string { // RegisterInstanceOperation manages a long-running operation from RegisterInstance. type RegisterInstanceOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // RegisterInstanceOperation returns a new RegisterInstanceOperation from a given name. @@ -2447,10 +5648,21 @@ func (c *notebookGRPCClient) RegisterInstanceOperation(name string) *RegisterIns } } +// RegisterInstanceOperation returns a new RegisterInstanceOperation from a given name. +// The name must be that of a previously created RegisterInstanceOperation, possibly from a different process. +func (c *notebookRESTClient) RegisterInstanceOperation(name string) *RegisterInstanceOperation { + override := fmt.Sprintf("/v1/%s", name) + return &RegisterInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *RegisterInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp notebookspb.Instance if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2468,6 +5680,7 @@ func (op *RegisterInstanceOperation) Wait(ctx context.Context, opts ...gax.CallO // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *RegisterInstanceOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp notebookspb.Instance if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2505,7 +5718,8 @@ func (op *RegisterInstanceOperation) Name() string { // ReportInstanceInfoOperation manages a long-running operation from ReportInstanceInfo. type ReportInstanceInfoOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // ReportInstanceInfoOperation returns a new ReportInstanceInfoOperation from a given name. @@ -2516,10 +5730,21 @@ func (c *notebookGRPCClient) ReportInstanceInfoOperation(name string) *ReportIns } } +// ReportInstanceInfoOperation returns a new ReportInstanceInfoOperation from a given name. +// The name must be that of a previously created ReportInstanceInfoOperation, possibly from a different process. +func (c *notebookRESTClient) ReportInstanceInfoOperation(name string) *ReportInstanceInfoOperation { + override := fmt.Sprintf("/v1/%s", name) + return &ReportInstanceInfoOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *ReportInstanceInfoOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp notebookspb.Instance if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2537,6 +5762,7 @@ func (op *ReportInstanceInfoOperation) Wait(ctx context.Context, opts ...gax.Cal // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *ReportInstanceInfoOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp notebookspb.Instance if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2574,7 +5800,8 @@ func (op *ReportInstanceInfoOperation) Name() string { // ResetInstanceOperation manages a long-running operation from ResetInstance. type ResetInstanceOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // ResetInstanceOperation returns a new ResetInstanceOperation from a given name. @@ -2585,10 +5812,21 @@ func (c *notebookGRPCClient) ResetInstanceOperation(name string) *ResetInstanceO } } +// ResetInstanceOperation returns a new ResetInstanceOperation from a given name. +// The name must be that of a previously created ResetInstanceOperation, possibly from a different process. +func (c *notebookRESTClient) ResetInstanceOperation(name string) *ResetInstanceOperation { + override := fmt.Sprintf("/v1/%s", name) + return &ResetInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *ResetInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp notebookspb.Instance if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2606,6 +5844,7 @@ func (op *ResetInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOpti // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *ResetInstanceOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp notebookspb.Instance if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2643,7 +5882,8 @@ func (op *ResetInstanceOperation) Name() string { // RollbackInstanceOperation manages a long-running operation from RollbackInstance. type RollbackInstanceOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // RollbackInstanceOperation returns a new RollbackInstanceOperation from a given name. @@ -2654,10 +5894,21 @@ func (c *notebookGRPCClient) RollbackInstanceOperation(name string) *RollbackIns } } +// RollbackInstanceOperation returns a new RollbackInstanceOperation from a given name. +// The name must be that of a previously created RollbackInstanceOperation, possibly from a different process. +func (c *notebookRESTClient) RollbackInstanceOperation(name string) *RollbackInstanceOperation { + override := fmt.Sprintf("/v1/%s", name) + return &RollbackInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *RollbackInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp notebookspb.Instance if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2675,6 +5926,7 @@ func (op *RollbackInstanceOperation) Wait(ctx context.Context, opts ...gax.CallO // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *RollbackInstanceOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp notebookspb.Instance if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2712,7 +5964,8 @@ func (op *RollbackInstanceOperation) Name() string { // SetInstanceAcceleratorOperation manages a long-running operation from SetInstanceAccelerator. type SetInstanceAcceleratorOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // SetInstanceAcceleratorOperation returns a new SetInstanceAcceleratorOperation from a given name. @@ -2723,10 +5976,21 @@ func (c *notebookGRPCClient) SetInstanceAcceleratorOperation(name string) *SetIn } } +// SetInstanceAcceleratorOperation returns a new SetInstanceAcceleratorOperation from a given name. +// The name must be that of a previously created SetInstanceAcceleratorOperation, possibly from a different process. +func (c *notebookRESTClient) SetInstanceAcceleratorOperation(name string) *SetInstanceAcceleratorOperation { + override := fmt.Sprintf("/v1/%s", name) + return &SetInstanceAcceleratorOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *SetInstanceAcceleratorOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp notebookspb.Instance if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2744,6 +6008,7 @@ func (op *SetInstanceAcceleratorOperation) Wait(ctx context.Context, opts ...gax // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *SetInstanceAcceleratorOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp notebookspb.Instance if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2781,7 +6046,8 @@ func (op *SetInstanceAcceleratorOperation) Name() string { // SetInstanceLabelsOperation manages a long-running operation from SetInstanceLabels. type SetInstanceLabelsOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // SetInstanceLabelsOperation returns a new SetInstanceLabelsOperation from a given name. @@ -2792,10 +6058,21 @@ func (c *notebookGRPCClient) SetInstanceLabelsOperation(name string) *SetInstanc } } +// SetInstanceLabelsOperation returns a new SetInstanceLabelsOperation from a given name. +// The name must be that of a previously created SetInstanceLabelsOperation, possibly from a different process. +func (c *notebookRESTClient) SetInstanceLabelsOperation(name string) *SetInstanceLabelsOperation { + override := fmt.Sprintf("/v1/%s", name) + return &SetInstanceLabelsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *SetInstanceLabelsOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp notebookspb.Instance if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2813,6 +6090,7 @@ func (op *SetInstanceLabelsOperation) Wait(ctx context.Context, opts ...gax.Call // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *SetInstanceLabelsOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp notebookspb.Instance if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2850,7 +6128,8 @@ func (op *SetInstanceLabelsOperation) Name() string { // SetInstanceMachineTypeOperation manages a long-running operation from SetInstanceMachineType. type SetInstanceMachineTypeOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // SetInstanceMachineTypeOperation returns a new SetInstanceMachineTypeOperation from a given name. @@ -2861,10 +6140,21 @@ func (c *notebookGRPCClient) SetInstanceMachineTypeOperation(name string) *SetIn } } +// SetInstanceMachineTypeOperation returns a new SetInstanceMachineTypeOperation from a given name. +// The name must be that of a previously created SetInstanceMachineTypeOperation, possibly from a different process. +func (c *notebookRESTClient) SetInstanceMachineTypeOperation(name string) *SetInstanceMachineTypeOperation { + override := fmt.Sprintf("/v1/%s", name) + return &SetInstanceMachineTypeOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *SetInstanceMachineTypeOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp notebookspb.Instance if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2882,6 +6172,7 @@ func (op *SetInstanceMachineTypeOperation) Wait(ctx context.Context, opts ...gax // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *SetInstanceMachineTypeOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp notebookspb.Instance if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2919,7 +6210,8 @@ func (op *SetInstanceMachineTypeOperation) Name() string { // StartInstanceOperation manages a long-running operation from StartInstance. type StartInstanceOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // StartInstanceOperation returns a new StartInstanceOperation from a given name. @@ -2930,10 +6222,21 @@ func (c *notebookGRPCClient) StartInstanceOperation(name string) *StartInstanceO } } +// StartInstanceOperation returns a new StartInstanceOperation from a given name. +// The name must be that of a previously created StartInstanceOperation, possibly from a different process. +func (c *notebookRESTClient) StartInstanceOperation(name string) *StartInstanceOperation { + override := fmt.Sprintf("/v1/%s", name) + return &StartInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *StartInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp notebookspb.Instance if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2951,6 +6254,7 @@ func (op *StartInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOpti // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *StartInstanceOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp notebookspb.Instance if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2988,7 +6292,8 @@ func (op *StartInstanceOperation) Name() string { // StopInstanceOperation manages a long-running operation from StopInstance. type StopInstanceOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // StopInstanceOperation returns a new StopInstanceOperation from a given name. @@ -2999,10 +6304,21 @@ func (c *notebookGRPCClient) StopInstanceOperation(name string) *StopInstanceOpe } } +// StopInstanceOperation returns a new StopInstanceOperation from a given name. +// The name must be that of a previously created StopInstanceOperation, possibly from a different process. +func (c *notebookRESTClient) StopInstanceOperation(name string) *StopInstanceOperation { + override := fmt.Sprintf("/v1/%s", name) + return &StopInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *StopInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp notebookspb.Instance if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -3020,6 +6336,7 @@ func (op *StopInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOptio // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *StopInstanceOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp notebookspb.Instance if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -3057,7 +6374,8 @@ func (op *StopInstanceOperation) Name() string { // TriggerScheduleOperation manages a long-running operation from TriggerSchedule. type TriggerScheduleOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // TriggerScheduleOperation returns a new TriggerScheduleOperation from a given name. @@ -3068,10 +6386,21 @@ func (c *notebookGRPCClient) TriggerScheduleOperation(name string) *TriggerSched } } +// TriggerScheduleOperation returns a new TriggerScheduleOperation from a given name. +// The name must be that of a previously created TriggerScheduleOperation, possibly from a different process. +func (c *notebookRESTClient) TriggerScheduleOperation(name string) *TriggerScheduleOperation { + override := fmt.Sprintf("/v1/%s", name) + return &TriggerScheduleOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *TriggerScheduleOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Schedule, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp notebookspb.Schedule if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -3089,6 +6418,7 @@ func (op *TriggerScheduleOperation) Wait(ctx context.Context, opts ...gax.CallOp // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *TriggerScheduleOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Schedule, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp notebookspb.Schedule if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -3126,7 +6456,8 @@ func (op *TriggerScheduleOperation) Name() string { // UpdateInstanceConfigOperation manages a long-running operation from UpdateInstanceConfig. type UpdateInstanceConfigOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateInstanceConfigOperation returns a new UpdateInstanceConfigOperation from a given name. @@ -3137,10 +6468,21 @@ func (c *notebookGRPCClient) UpdateInstanceConfigOperation(name string) *UpdateI } } +// UpdateInstanceConfigOperation returns a new UpdateInstanceConfigOperation from a given name. +// The name must be that of a previously created UpdateInstanceConfigOperation, possibly from a different process. +func (c *notebookRESTClient) UpdateInstanceConfigOperation(name string) *UpdateInstanceConfigOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateInstanceConfigOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateInstanceConfigOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp notebookspb.Instance if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -3158,6 +6500,7 @@ func (op *UpdateInstanceConfigOperation) Wait(ctx context.Context, opts ...gax.C // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateInstanceConfigOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp notebookspb.Instance if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -3195,7 +6538,8 @@ func (op *UpdateInstanceConfigOperation) Name() string { // UpdateShieldedInstanceConfigOperation manages a long-running operation from UpdateShieldedInstanceConfig. type UpdateShieldedInstanceConfigOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateShieldedInstanceConfigOperation returns a new UpdateShieldedInstanceConfigOperation from a given name. @@ -3206,10 +6550,21 @@ func (c *notebookGRPCClient) UpdateShieldedInstanceConfigOperation(name string) } } +// UpdateShieldedInstanceConfigOperation returns a new UpdateShieldedInstanceConfigOperation from a given name. +// The name must be that of a previously created UpdateShieldedInstanceConfigOperation, possibly from a different process. +func (c *notebookRESTClient) UpdateShieldedInstanceConfigOperation(name string) *UpdateShieldedInstanceConfigOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateShieldedInstanceConfigOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateShieldedInstanceConfigOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp notebookspb.Instance if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -3227,6 +6582,7 @@ func (op *UpdateShieldedInstanceConfigOperation) Wait(ctx context.Context, opts // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateShieldedInstanceConfigOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp notebookspb.Instance if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -3264,7 +6620,8 @@ func (op *UpdateShieldedInstanceConfigOperation) Name() string { // UpgradeInstanceOperation manages a long-running operation from UpgradeInstance. type UpgradeInstanceOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpgradeInstanceOperation returns a new UpgradeInstanceOperation from a given name. @@ -3275,10 +6632,21 @@ func (c *notebookGRPCClient) UpgradeInstanceOperation(name string) *UpgradeInsta } } +// UpgradeInstanceOperation returns a new UpgradeInstanceOperation from a given name. +// The name must be that of a previously created UpgradeInstanceOperation, possibly from a different process. +func (c *notebookRESTClient) UpgradeInstanceOperation(name string) *UpgradeInstanceOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpgradeInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpgradeInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp notebookspb.Instance if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -3296,6 +6664,7 @@ func (op *UpgradeInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOp // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpgradeInstanceOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp notebookspb.Instance if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -3333,7 +6702,8 @@ func (op *UpgradeInstanceOperation) Name() string { // UpgradeInstanceInternalOperation manages a long-running operation from UpgradeInstanceInternal. type UpgradeInstanceInternalOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpgradeInstanceInternalOperation returns a new UpgradeInstanceInternalOperation from a given name. @@ -3344,10 +6714,21 @@ func (c *notebookGRPCClient) UpgradeInstanceInternalOperation(name string) *Upgr } } +// UpgradeInstanceInternalOperation returns a new UpgradeInstanceInternalOperation from a given name. +// The name must be that of a previously created UpgradeInstanceInternalOperation, possibly from a different process. +func (c *notebookRESTClient) UpgradeInstanceInternalOperation(name string) *UpgradeInstanceInternalOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpgradeInstanceInternalOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpgradeInstanceInternalOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp notebookspb.Instance if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -3365,6 +6746,7 @@ func (op *UpgradeInstanceInternalOperation) Wait(ctx context.Context, opts ...ga // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpgradeInstanceInternalOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*notebookspb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp notebookspb.Instance if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/notebooks/apiv1/notebook_client_example_test.go b/notebooks/apiv1/notebook_client_example_test.go index e3b3679a2e65..20e74629fce5 100644 --- a/notebooks/apiv1/notebook_client_example_test.go +++ b/notebooks/apiv1/notebook_client_example_test.go @@ -44,6 +44,23 @@ func ExampleNewNotebookClient() { _ = c } +func ExampleNewNotebookRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := notebooks.NewNotebookRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleNotebookClient_ListInstances() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/notebooks/apiv1/notebookspb/diagnostic_config.pb.go b/notebooks/apiv1/notebookspb/diagnostic_config.pb.go index 673f37e11fef..57d9a13a7ee6 100644 --- a/notebooks/apiv1/notebookspb/diagnostic_config.pb.go +++ b/notebooks/apiv1/notebookspb/diagnostic_config.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/notebooks/v1/diagnostic_config.proto package notebookspb @@ -47,12 +47,11 @@ type DiagnosticConfig struct { // // Permissions: // User Managed Notebooks: - // - storage.buckets.writer: Must be given to the project's service account - // attached to VM. - // + // - storage.buckets.writer: Must be given to the project's service account + // attached to VM. // Google Managed Notebooks: - // - storage.buckets.writer: Must be given to the project's service account or - // user credentials attached to VM depending on authentication mode. + // - storage.buckets.writer: Must be given to the project's service account or + // user credentials attached to VM depending on authentication mode. // // Cloud Storage bucket Log file will be written to // `gs://$GCS_BUCKET/$RELATIVE_PATH/$VM_DATE_$TIME.tar.gz` diff --git a/notebooks/apiv1/notebookspb/environment.pb.go b/notebooks/apiv1/notebookspb/environment.pb.go index 801148e11261..0f19fb18759f 100644 --- a/notebooks/apiv1/notebookspb/environment.pb.go +++ b/notebooks/apiv1/notebookspb/environment.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/notebooks/v1/environment.proto package notebookspb @@ -55,7 +55,6 @@ type Environment struct { // Type of the environment; can be one of VM image, or container image. // // Types that are assignable to ImageType: - // // *Environment_VmImage // *Environment_ContainerImage ImageType isEnvironment_ImageType `protobuf_oneof:"image_type"` @@ -186,7 +185,6 @@ type VmImage struct { // The reference to an external Compute Engine VM image. // // Types that are assignable to Image: - // // *VmImage_ImageName // *VmImage_ImageFamily Image isVmImage_Image `protobuf_oneof:"image"` diff --git a/notebooks/apiv1/notebookspb/event.pb.go b/notebooks/apiv1/notebookspb/event.pb.go index 1d75e8e47060..6afa4a89437e 100644 --- a/notebooks/apiv1/notebookspb/event.pb.go +++ b/notebooks/apiv1/notebookspb/event.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/notebooks/v1/event.proto package notebookspb diff --git a/notebooks/apiv1/notebookspb/execution.pb.go b/notebooks/apiv1/notebookspb/execution.pb.go index 83829e131bf7..c1f8b692bbcc 100644 --- a/notebooks/apiv1/notebookspb/execution.pb.go +++ b/notebooks/apiv1/notebookspb/execution.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/notebooks/v1/execution.proto package notebookspb @@ -59,7 +59,7 @@ const ( // own cluster specification. When you use this tier, set values to // configure your processing cluster according to these guidelines: // - // - You _must_ set `ExecutionTemplate.masterType` to specify the type + // * You _must_ set `ExecutionTemplate.masterType` to specify the type // of machine to use for your master node. This is the only required // setting. ExecutionTemplate_CUSTOM ExecutionTemplate_ScaleTier = 6 @@ -367,6 +367,7 @@ type ExecutionTemplate struct { // - `n1-highcpu-64` // - `n1-highcpu-96` // + // // Alternatively, you can use the following legacy machine types: // // - `standard` @@ -384,6 +385,7 @@ type ExecutionTemplate struct { // - `complex_model_m_v100` // - `complex_model_l_v100` // + // // Finally, if you want to use a TPU for training, specify `cloud_tpu` in this // field. Learn more about the [special configuration options for training // with @@ -431,7 +433,6 @@ type ExecutionTemplate struct { // NOTE: There are currently no extra parameters for VertexAI jobs. // // Types that are assignable to JobParameters: - // // *ExecutionTemplate_DataprocParameters_ // *ExecutionTemplate_VertexAiParameters JobParameters isExecutionTemplate_JobParameters `protobuf_oneof:"job_parameters"` @@ -861,9 +862,7 @@ type ExecutionTemplate_VertexAIParameters struct { // left unspecified, the job is not peered with any network. Network string `protobuf:"bytes,1,opt,name=network,proto3" json:"network,omitempty"` // Environment variables. - // - // At most 100 environment variables can be specified and unique. - // + // At most 100 environment variables can be specified and unique. // Example: GCP_BUCKET=gs://my-bucket/samples/ Env map[string]string `protobuf:"bytes,2,rep,name=env,proto3" json:"env,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` } diff --git a/notebooks/apiv1/notebookspb/instance.pb.go b/notebooks/apiv1/notebookspb/instance.pb.go index 25a5c72be357..8afaea448268 100644 --- a/notebooks/apiv1/notebookspb/instance.pb.go +++ b/notebooks/apiv1/notebookspb/instance.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/notebooks/v1/instance.proto package notebookspb @@ -632,7 +632,6 @@ type Instance struct { // Type of the environment; can be one of VM image, or container image. // // Types that are assignable to Environment: - // // *Instance_VmImage // *Instance_ContainerImage Environment isInstance_Environment `protobuf_oneof:"environment"` @@ -663,12 +662,10 @@ type Instance struct { // If not specified, the following // [scopes](https://cloud.google.com/compute/docs/access/service-accounts#accesscopesiam) // are defined: - // - https://www.googleapis.com/auth/cloud-platform - // - https://www.googleapis.com/auth/userinfo.email - // + // - https://www.googleapis.com/auth/cloud-platform + // - https://www.googleapis.com/auth/userinfo.email // If not using default scopes, you need at least: - // - // https://www.googleapis.com/auth/compute + // https://www.googleapis.com/auth/compute ServiceAccountScopes []string `protobuf:"bytes,31,rep,name=service_account_scopes,json=serviceAccountScopes,proto3" json:"service_account_scopes,omitempty"` // Required. The [Compute Engine machine type](/compute/docs/machine-types) of this // instance. diff --git a/notebooks/apiv1/notebookspb/instance_config.pb.go b/notebooks/apiv1/notebookspb/instance_config.pb.go index 3368fb19ac18..830ddb2aaf17 100644 --- a/notebooks/apiv1/notebookspb/instance_config.pb.go +++ b/notebooks/apiv1/notebookspb/instance_config.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/notebooks/v1/instance_config.proto package notebookspb diff --git a/notebooks/apiv1/notebookspb/managed_service.pb.go b/notebooks/apiv1/notebookspb/managed_service.pb.go index 45180b99ffcb..ffd660cd6ee1 100644 --- a/notebooks/apiv1/notebookspb/managed_service.pb.go +++ b/notebooks/apiv1/notebookspb/managed_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/notebooks/v1/managed_service.proto package notebookspb @@ -767,14 +767,15 @@ type UpdateRuntimeRequest struct { // specified as `software_config.kernels`, // and the `PATCH` request body would specify the new value, as follows: // - // { - // "software_config":{ - // "kernels": [{ - // 'repository': - // 'gcr.io/deeplearning-platform-release/pytorch-gpu', 'tag': - // 'latest' }], - // } - // } + // { + // "software_config":{ + // "kernels": [{ + // 'repository': + // 'gcr.io/deeplearning-platform-release/pytorch-gpu', 'tag': + // 'latest' }], + // } + // } + // // // Currently, only the following fields can be updated: // - software_config.kernels diff --git a/notebooks/apiv1/notebookspb/runtime.pb.go b/notebooks/apiv1/notebookspb/runtime.pb.go index f8b88cd5e167..9fe50f347f1f 100644 --- a/notebooks/apiv1/notebookspb/runtime.pb.go +++ b/notebooks/apiv1/notebookspb/runtime.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/notebooks/v1/runtime.proto package notebookspb @@ -511,7 +511,6 @@ type Runtime struct { // Type of the runtime; currently only supports Compute Engine VM. // // Types that are assignable to RuntimeType: - // // *Runtime_VirtualMachine RuntimeType isRuntime_RuntimeType `protobuf_oneof:"runtime_type"` // Output only. Runtime state. @@ -1561,14 +1560,13 @@ type VirtualMachineConfig struct { // // Example: managed-notebooks-range-c // PEERING_RANGE_NAME_3=managed-notebooks-range-c - // - // gcloud compute addresses create $PEERING_RANGE_NAME_3 \ - // --global \ - // --prefix-length=24 \ - // --description="Google Cloud Managed Notebooks Range 24 c" \ - // --network=$NETWORK \ - // --addresses=192.168.0.0 \ - // --purpose=VPC_PEERING + // gcloud compute addresses create $PEERING_RANGE_NAME_3 \ + // --global \ + // --prefix-length=24 \ + // --description="Google Cloud Managed Notebooks Range 24 c" \ + // --network=$NETWORK \ + // --addresses=192.168.0.0 \ + // --purpose=VPC_PEERING // // Field value will be: `managed-notebooks-range-c` ReservedIpRange string `protobuf:"bytes,18,opt,name=reserved_ip_range,json=reservedIpRange,proto3" json:"reserved_ip_range,omitempty"` diff --git a/notebooks/apiv1/notebookspb/schedule.pb.go b/notebooks/apiv1/notebookspb/schedule.pb.go index 0757b2775d6f..58ea95040be2 100644 --- a/notebooks/apiv1/notebookspb/schedule.pb.go +++ b/notebooks/apiv1/notebookspb/schedule.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/notebooks/v1/schedule.proto package notebookspb diff --git a/notebooks/apiv1/notebookspb/service.pb.go b/notebooks/apiv1/notebookspb/service.pb.go index b2ca7e79bacb..76846de1c5a9 100644 --- a/notebooks/apiv1/notebookspb/service.pb.go +++ b/notebooks/apiv1/notebookspb/service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/notebooks/v1/service.proto package notebookspb @@ -1492,14 +1492,13 @@ type GetInstanceHealthResponse struct { HealthState GetInstanceHealthResponse_HealthState `protobuf:"varint,1,opt,name=health_state,json=healthState,proto3,enum=google.cloud.notebooks.v1.GetInstanceHealthResponse_HealthState" json:"health_state,omitempty"` // Output only. Additional information about instance health. // Example: - // - // healthInfo": { - // "docker_proxy_agent_status": "1", - // "docker_status": "1", - // "jupyterlab_api_status": "-1", - // "jupyterlab_status": "-1", - // "updated": "2020-10-18 09:40:03.573409" - // } + // healthInfo": { + // "docker_proxy_agent_status": "1", + // "docker_status": "1", + // "jupyterlab_api_status": "-1", + // "jupyterlab_status": "-1", + // "updated": "2020-10-18 09:40:03.573409" + // } HealthInfo map[string]string `protobuf:"bytes,2,rep,name=health_info,json=healthInfo,proto3" json:"health_info,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` } @@ -2204,8 +2203,8 @@ type ListSchedulesResponse struct { NextPageToken string `protobuf:"bytes,2,opt,name=next_page_token,json=nextPageToken,proto3" json:"next_page_token,omitempty"` // Schedules that could not be reached. For example: // - // ['projects/{project_id}/location/{location}/schedules/monthly_digest', - // 'projects/{project_id}/location/{location}/schedules/weekly_sentiment'] + // ['projects/{project_id}/location/{location}/schedules/monthly_digest', + // 'projects/{project_id}/location/{location}/schedules/weekly_sentiment'] Unreachable []string `protobuf:"bytes,3,rep,name=unreachable,proto3" json:"unreachable,omitempty"` } @@ -2582,8 +2581,8 @@ type ListExecutionsResponse struct { NextPageToken string `protobuf:"bytes,2,opt,name=next_page_token,json=nextPageToken,proto3" json:"next_page_token,omitempty"` // Executions IDs that could not be reached. For example: // - // ['projects/{project_id}/location/{location}/executions/imagenet_test1', - // 'projects/{project_id}/location/{location}/executions/classifier_train1'] + // ['projects/{project_id}/location/{location}/executions/imagenet_test1', + // 'projects/{project_id}/location/{location}/executions/classifier_train1'] Unreachable []string `protobuf:"bytes,3,rep,name=unreachable,proto3" json:"unreachable,omitempty"` } diff --git a/notebooks/apiv1beta1/notebook_client.go b/notebooks/apiv1beta1/notebook_client.go index c3957dbb1355..79019c9a3a0c 100644 --- a/notebooks/apiv1beta1/notebook_client.go +++ b/notebooks/apiv1beta1/notebook_client.go @@ -1401,6 +1401,7 @@ func (c *notebookRESTClient) ListInstances(ctx context.Context, req *notebookspb baseUrl.Path += fmt.Sprintf("/v1beta1/%v/instances", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -1474,6 +1475,11 @@ func (c *notebookRESTClient) GetInstance(ctx context.Context, req *notebookspb.G } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1535,6 +1541,7 @@ func (c *notebookRESTClient) CreateInstance(ctx context.Context, req *notebooksp baseUrl.Path += fmt.Sprintf("/v1beta1/%v/instances", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("instanceId", fmt.Sprintf("%v", req.GetInstanceId())) baseUrl.RawQuery = params.Encode() @@ -1605,6 +1612,11 @@ func (c *notebookRESTClient) RegisterInstance(ctx context.Context, req *notebook } baseUrl.Path += fmt.Sprintf("/v1beta1/%v/instances:register", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1668,6 +1680,11 @@ func (c *notebookRESTClient) SetInstanceAccelerator(ctx context.Context, req *no } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:setAccelerator", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1731,6 +1748,11 @@ func (c *notebookRESTClient) SetInstanceMachineType(ctx context.Context, req *no } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:setMachineType", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1794,6 +1816,11 @@ func (c *notebookRESTClient) SetInstanceLabels(ctx context.Context, req *noteboo } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:setLabels", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1851,6 +1878,11 @@ func (c *notebookRESTClient) DeleteInstance(ctx context.Context, req *notebooksp } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1914,6 +1946,11 @@ func (c *notebookRESTClient) StartInstance(ctx context.Context, req *notebookspb } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:start", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1977,6 +2014,11 @@ func (c *notebookRESTClient) StopInstance(ctx context.Context, req *notebookspb. } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:stop", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2040,6 +2082,11 @@ func (c *notebookRESTClient) ResetInstance(ctx context.Context, req *notebookspb } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:reset", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2106,6 +2153,11 @@ func (c *notebookRESTClient) ReportInstanceInfo(ctx context.Context, req *notebo } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:report", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2166,6 +2218,11 @@ func (c *notebookRESTClient) IsInstanceUpgradeable(ctx context.Context, req *not } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:isUpgradeable", req.GetNotebookInstance()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "notebook_instance", url.QueryEscape(req.GetNotebookInstance()))) @@ -2228,6 +2285,11 @@ func (c *notebookRESTClient) UpgradeInstance(ctx context.Context, req *notebooks } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:upgrade", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2295,6 +2357,11 @@ func (c *notebookRESTClient) UpgradeInstanceInternal(ctx context.Context, req *n } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:upgradeInternal", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2366,6 +2433,7 @@ func (c *notebookRESTClient) ListEnvironments(ctx context.Context, req *notebook baseUrl.Path += fmt.Sprintf("/v1beta1/%v/environments", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -2439,6 +2507,11 @@ func (c *notebookRESTClient) GetEnvironment(ctx context.Context, req *notebooksp } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2500,6 +2573,7 @@ func (c *notebookRESTClient) CreateEnvironment(ctx context.Context, req *noteboo baseUrl.Path += fmt.Sprintf("/v1beta1/%v/environments", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("environmentId", fmt.Sprintf("%v", req.GetEnvironmentId())) baseUrl.RawQuery = params.Encode() @@ -2561,6 +2635,11 @@ func (c *notebookRESTClient) DeleteEnvironment(ctx context.Context, req *noteboo } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2618,6 +2697,11 @@ func (c *notebookRESTClient) GetLocation(ctx context.Context, req *locationpb.Ge } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2685,6 +2769,7 @@ func (c *notebookRESTClient) ListLocations(ctx context.Context, req *locationpb. baseUrl.Path += fmt.Sprintf("/v1beta1/%v/locations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -2763,6 +2848,7 @@ func (c *notebookRESTClient) GetIamPolicy(ctx context.Context, req *iampb.GetIam baseUrl.Path += fmt.Sprintf("/v1beta1/%v:getIamPolicy", req.GetResource()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetOptions().GetRequestedPolicyVersion() != 0 { params.Add("options.requestedPolicyVersion", fmt.Sprintf("%v", req.GetOptions().GetRequestedPolicyVersion())) } @@ -2832,6 +2918,11 @@ func (c *notebookRESTClient) SetIamPolicy(ctx context.Context, req *iampb.SetIam } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:setIamPolicy", req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) @@ -2897,6 +2988,11 @@ func (c *notebookRESTClient) TestIamPermissions(ctx context.Context, req *iampb. } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:testIamPermissions", req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) @@ -2956,6 +3052,11 @@ func (c *notebookRESTClient) CancelOperation(ctx context.Context, req *longrunni } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:cancel", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2991,6 +3092,11 @@ func (c *notebookRESTClient) DeleteOperation(ctx context.Context, req *longrunni } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -3026,6 +3132,11 @@ func (c *notebookRESTClient) GetOperation(ctx context.Context, req *longrunningp } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -3093,6 +3204,7 @@ func (c *notebookRESTClient) ListOperations(ctx context.Context, req *longrunnin baseUrl.Path += fmt.Sprintf("/v1beta1/%v/operations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/notebooks/apiv1beta1/notebookspb/environment.pb.go b/notebooks/apiv1beta1/notebookspb/environment.pb.go index 23ef85d74e12..391bb68b2fcb 100644 --- a/notebooks/apiv1beta1/notebookspb/environment.pb.go +++ b/notebooks/apiv1beta1/notebookspb/environment.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/notebooks/v1beta1/environment.proto package notebookspb @@ -55,7 +55,6 @@ type Environment struct { // Type of the environment; can be one of VM image, or container image. // // Types that are assignable to ImageType: - // // *Environment_VmImage // *Environment_ContainerImage ImageType isEnvironment_ImageType `protobuf_oneof:"image_type"` @@ -186,7 +185,6 @@ type VmImage struct { // The reference to an external Compute Engine VM image. // // Types that are assignable to Image: - // // *VmImage_ImageName // *VmImage_ImageFamily Image isVmImage_Image `protobuf_oneof:"image"` diff --git a/notebooks/apiv1beta1/notebookspb/instance.pb.go b/notebooks/apiv1beta1/notebookspb/instance.pb.go index 19d1734ff059..060c2d438bdd 100644 --- a/notebooks/apiv1beta1/notebookspb/instance.pb.go +++ b/notebooks/apiv1beta1/notebookspb/instance.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/notebooks/v1beta1/instance.proto package notebookspb @@ -514,7 +514,6 @@ type Instance struct { // Type of the environment; can be one of VM image, or container image. // // Types that are assignable to Environment: - // // *Instance_VmImage // *Instance_ContainerImage Environment isInstance_Environment `protobuf_oneof:"environment"` diff --git a/notebooks/apiv1beta1/notebookspb/service.pb.go b/notebooks/apiv1beta1/notebookspb/service.pb.go index 9475d4336258..89a09fda52bb 100644 --- a/notebooks/apiv1beta1/notebookspb/service.pb.go +++ b/notebooks/apiv1beta1/notebookspb/service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/notebooks/v1beta1/service.proto package notebookspb diff --git a/optimization/apiv1/doc.go b/optimization/apiv1/doc.go index 86fa8af8560a..ebc36608a397 100644 --- a/optimization/apiv1/doc.go +++ b/optimization/apiv1/doc.go @@ -82,6 +82,8 @@ package optimization // import "cloud.google.com/go/optimization/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -170,3 +172,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/optimization/apiv1/fleet_routing_client.go b/optimization/apiv1/fleet_routing_client.go index 8ee75ec143a2..662dceb30c20 100644 --- a/optimization/apiv1/fleet_routing_client.go +++ b/optimization/apiv1/fleet_routing_client.go @@ -17,9 +17,12 @@ package optimization import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,13 +30,16 @@ import ( lroauto "cloud.google.com/go/longrunning/autogen" optimizationpb "cloud.google.com/go/optimization/apiv1/optimizationpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" ) var newFleetRoutingClientHook clientHook @@ -83,6 +89,31 @@ func defaultFleetRoutingCallOptions() *FleetRoutingCallOptions { } } +func defaultFleetRoutingRESTCallOptions() *FleetRoutingCallOptions { + return &FleetRoutingCallOptions{ + OptimizeTours: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + BatchOptimizeTours: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + } +} + // internalFleetRoutingClient is an interface that defines the methods available from Cloud Optimization API. type internalFleetRoutingClient interface { Close() error @@ -320,6 +351,115 @@ func (c *fleetRoutingGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type fleetRoutingRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing FleetRoutingClient + CallOptions **FleetRoutingCallOptions +} + +// NewFleetRoutingRESTClient creates a new fleet routing rest client. +// +// A service for optimizing vehicle tours. +// +// Validity of certain types of fields: +// +// google.protobuf.Timestamp +// +// Times are in Unix time: seconds since 1970-01-01T00:00:00+00:00. +// +// seconds must be in [0, 253402300799], +// i.e. in [1970-01-01T00:00:00+00:00, 9999-12-31T23:59:59+00:00]. +// +// nanos must be unset or set to 0. +// +// google.protobuf.Duration +// +// seconds must be in [0, 253402300799], +// i.e. in [1970-01-01T00:00:00+00:00, 9999-12-31T23:59:59+00:00]. +// +// nanos must be unset or set to 0. +// +// google.type.LatLng +// +// latitude must be in [-90.0, 90.0]. +// +// longitude must be in [-180.0, 180.0]. +// +// at least one of latitude and longitude must be non-zero. +func NewFleetRoutingRESTClient(ctx context.Context, opts ...option.ClientOption) (*FleetRoutingClient, error) { + clientOpts := append(defaultFleetRoutingRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultFleetRoutingRESTCallOptions() + c := &fleetRoutingRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &FleetRoutingClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultFleetRoutingRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://cloudoptimization.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://cloudoptimization.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://cloudoptimization.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *fleetRoutingRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *fleetRoutingRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *fleetRoutingRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *fleetRoutingGRPCClient) OptimizeTours(ctx context.Context, req *optimizationpb.OptimizeToursRequest, opts ...gax.CallOption) (*optimizationpb.OptimizeToursResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 3600000*time.Millisecond) @@ -366,9 +506,164 @@ func (c *fleetRoutingGRPCClient) BatchOptimizeTours(ctx context.Context, req *op }, nil } +// OptimizeTours sends an OptimizeToursRequest containing a ShipmentModel and returns an +// OptimizeToursResponse containing ShipmentRoutes, which are a set of +// routes to be performed by vehicles minimizing the overall cost. +// +// A ShipmentModel model consists mainly of Shipments that need to be +// carried out and Vehicles that can be used to transport the Shipments. +// The ShipmentRoutes assign Shipments to Vehicles. More specifically, +// they assign a series of Visits to each vehicle, where a Visit +// corresponds to a VisitRequest, which is a pickup or delivery for a +// Shipment. +// +// The goal is to provide an assignment of ShipmentRoutes to Vehicles that +// minimizes the total cost where cost has many components defined in the +// ShipmentModel. +func (c *fleetRoutingRESTClient) OptimizeTours(ctx context.Context, req *optimizationpb.OptimizeToursRequest, opts ...gax.CallOption) (*optimizationpb.OptimizeToursResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:optimizeTours", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).OptimizeTours[0:len((*c.CallOptions).OptimizeTours):len((*c.CallOptions).OptimizeTours)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &optimizationpb.OptimizeToursResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// BatchOptimizeTours optimizes vehicle tours for one or more OptimizeToursRequest +// messages as a batch. +// +// This method is a Long Running Operation (LRO). The inputs for optimization +// (OptimizeToursRequest messages) and outputs (OptimizeToursResponse +// messages) are read/written from/to Cloud Storage in user-specified +// format. Like the OptimizeTours method, each OptimizeToursRequest +// contains a ShipmentModel and returns an OptimizeToursResponse +// containing ShipmentRoutes, which are a set of routes to be performed by +// vehicles minimizing the overall cost. +func (c *fleetRoutingRESTClient) BatchOptimizeTours(ctx context.Context, req *optimizationpb.BatchOptimizeToursRequest, opts ...gax.CallOption) (*BatchOptimizeToursOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:batchOptimizeTours", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &BatchOptimizeToursOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + // BatchOptimizeToursOperation manages a long-running operation from BatchOptimizeTours. type BatchOptimizeToursOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // BatchOptimizeToursOperation returns a new BatchOptimizeToursOperation from a given name. @@ -379,10 +674,21 @@ func (c *fleetRoutingGRPCClient) BatchOptimizeToursOperation(name string) *Batch } } +// BatchOptimizeToursOperation returns a new BatchOptimizeToursOperation from a given name. +// The name must be that of a previously created BatchOptimizeToursOperation, possibly from a different process. +func (c *fleetRoutingRESTClient) BatchOptimizeToursOperation(name string) *BatchOptimizeToursOperation { + override := fmt.Sprintf("/v1/%s", name) + return &BatchOptimizeToursOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *BatchOptimizeToursOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*optimizationpb.BatchOptimizeToursResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp optimizationpb.BatchOptimizeToursResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -400,6 +706,7 @@ func (op *BatchOptimizeToursOperation) Wait(ctx context.Context, opts ...gax.Cal // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *BatchOptimizeToursOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*optimizationpb.BatchOptimizeToursResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp optimizationpb.BatchOptimizeToursResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/optimization/apiv1/fleet_routing_client_example_test.go b/optimization/apiv1/fleet_routing_client_example_test.go index 3ecd3186dc7a..2e07fd8a6976 100644 --- a/optimization/apiv1/fleet_routing_client_example_test.go +++ b/optimization/apiv1/fleet_routing_client_example_test.go @@ -40,6 +40,23 @@ func ExampleNewFleetRoutingClient() { _ = c } +func ExampleNewFleetRoutingRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := optimization.NewFleetRoutingRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleFleetRoutingClient_OptimizeTours() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/optimization/apiv1/gapic_metadata.json b/optimization/apiv1/gapic_metadata.json index aa9bc1e72407..c9a1bbf3ac32 100644 --- a/optimization/apiv1/gapic_metadata.json +++ b/optimization/apiv1/gapic_metadata.json @@ -21,6 +21,21 @@ ] } } + }, + "rest": { + "libraryClient": "FleetRoutingClient", + "rpcs": { + "BatchOptimizeTours": { + "methods": [ + "BatchOptimizeTours" + ] + }, + "OptimizeTours": { + "methods": [ + "OptimizeTours" + ] + } + } } } } diff --git a/optimization/apiv1/optimizationpb/async_model.pb.go b/optimization/apiv1/optimizationpb/async_model.pb.go index bf129892f626..0dfa4a4414da 100644 --- a/optimization/apiv1/optimizationpb/async_model.pb.go +++ b/optimization/apiv1/optimizationpb/async_model.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/optimization/v1/async_model.proto package optimizationpb @@ -161,7 +161,6 @@ type InputConfig struct { // Required. // // Types that are assignable to Source: - // // *InputConfig_GcsSource Source isInputConfig_Source `protobuf_oneof:"source"` // The input data format that used to store the model in Cloud Storage. @@ -243,7 +242,6 @@ type OutputConfig struct { // Required. // // Types that are assignable to Destination: - // // *OutputConfig_GcsDestination Destination isOutputConfig_Destination `protobuf_oneof:"destination"` // The output data format that used to store the results in Cloud Storage. diff --git a/optimization/apiv1/optimizationpb/fleet_routing.pb.go b/optimization/apiv1/optimizationpb/fleet_routing.pb.go index 901d8e4c560b..02a75cce7187 100644 --- a/optimization/apiv1/optimizationpb/fleet_routing.pb.go +++ b/optimization/apiv1/optimizationpb/fleet_routing.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/optimization/v1/fleet_routing.proto package optimizationpb @@ -176,11 +176,11 @@ const ( // For two shipments with incompatible types with the // `NOT_IN_SAME_VEHICLE_SIMULTANEOUSLY` incompatibility mode: // - // - If both are pickups only (no deliveries) or deliveries only (no - // pickups), they cannot share the same vehicle at all. - // - If one of the shipments has a delivery and the other a pickup, the two - // shipments can share the same vehicle iff the former shipment is - // delivered before the latter is picked up. + // * If both are pickups only (no deliveries) or deliveries only (no + // pickups), they cannot share the same vehicle at all. + // * If one of the shipments has a delivery and the other a pickup, the two + // shipments can share the same vehicle iff the former shipment is + // delivered before the latter is picked up. ShipmentTypeIncompatibility_NOT_IN_SAME_VEHICLE_SIMULTANEOUSLY ShipmentTypeIncompatibility_IncompatibilityMode = 2 ) @@ -240,10 +240,10 @@ const ( // // A "dependent" shipment pickup must therefore have either: // - // - A delivery-only "required" shipment delivered on the route after, or - // - A "required" shipment picked up on the route before it, and if the - // "required" shipment has a delivery, this delivery must be performed - // after the "dependent" shipment's pickup. + // * A delivery-only "required" shipment delivered on the route after, or + // * A "required" shipment picked up on the route before it, and if the + // "required" shipment has a delivery, this delivery must be performed + // after the "dependent" shipment's pickup. ShipmentTypeRequirement_IN_SAME_VEHICLE_AT_PICKUP_TIME ShipmentTypeRequirement_RequirementMode = 2 // Same as before, except the "dependent" shipments need to have a // "required" shipment on their vehicle at the time of their *delivery*. @@ -609,18 +609,18 @@ type OptimizeToursRequest struct { // // The solution must satisfy some basic validity assumptions: // - // - for all routes, `vehicle_index` must be in range and not be duplicated. - // - for all visits, `shipment_index` and `visit_request_index` must be + // * for all routes, `vehicle_index` must be in range and not be duplicated. + // * for all visits, `shipment_index` and `visit_request_index` must be // in range. - // - a shipment may only be referenced on one route. - // - the pickup of a pickup-delivery shipment must be performed before + // * a shipment may only be referenced on one route. + // * the pickup of a pickup-delivery shipment must be performed before // the delivery. - // - no more than one pickup alternative or delivery alternative of + // * no more than one pickup alternative or delivery alternative of // a shipment may be performed. - // - for all routes, times are increasing (i.e., `vehicle_start_time + // * for all routes, times are increasing (i.e., `vehicle_start_time // <= visits[0].start_time <= visits[1].start_time ... // <= vehicle_end_time`). - // - a shipment may only be performed on a vehicle that is allowed. A + // * a shipment may only be performed on a vehicle that is allowed. A // vehicle is allowed if // [Shipment.allowed_vehicle_indices][google.cloud.optimization.v1.Shipment.allowed_vehicle_indices] // is empty or its `vehicle_index` is included in @@ -658,9 +658,9 @@ type OptimizeToursRequest struct { RefreshDetailsRoutes []*ShipmentRoute `protobuf:"bytes,9,rep,name=refresh_details_routes,json=refreshDetailsRoutes,proto3" json:"refresh_details_routes,omitempty"` // If true: // - // - uses - // [ShipmentRoute.vehicle_label][google.cloud.optimization.v1.ShipmentRoute.vehicle_label] - // instead of `vehicle_index` to + // * uses + // [ShipmentRoute.vehicle_label][google.cloud.optimization.v1.ShipmentRoute.vehicle_label] + // instead of `vehicle_index` to // match routes in an injected solution with vehicles in the request; // reuses the mapping of original // [ShipmentRoute.vehicle_index][google.cloud.optimization.v1.ShipmentRoute.vehicle_index] @@ -670,15 +670,15 @@ type OptimizeToursRequest struct { // [ConstraintRelaxation.vehicle_indices][google.cloud.optimization.v1.InjectedSolutionConstraint.ConstraintRelaxation.vehicle_indices] // if non-empty, but the mapping must be unambiguous (i.e., multiple // `ShipmentRoute`s must not share the same original `vehicle_index`). - // - uses - // [ShipmentRoute.Visit.shipment_label][google.cloud.optimization.v1.ShipmentRoute.Visit.shipment_label] - // instead of `shipment_index` + // * uses + // [ShipmentRoute.Visit.shipment_label][google.cloud.optimization.v1.ShipmentRoute.Visit.shipment_label] + // instead of `shipment_index` // to match visits in an injected solution with shipments in the request; - // - uses - // [SkippedShipment.label][google.cloud.optimization.v1.SkippedShipment.label] - // instead of - // [SkippedShipment.index][google.cloud.optimization.v1.SkippedShipment.index] - // to + // * uses + // [SkippedShipment.label][google.cloud.optimization.v1.SkippedShipment.label] + // instead of + // [SkippedShipment.index][google.cloud.optimization.v1.SkippedShipment.index] + // to // match skipped shipments in the injected solution with request // shipments. // @@ -691,12 +691,12 @@ type OptimizeToursRequest struct { // If true, labels in the following categories must appear at most once in // their category: // - // - [Vehicle.label][google.cloud.optimization.v1.Vehicle.label] in the - // request; - // - [Shipment.label][google.cloud.optimization.v1.Shipment.label] in the - // request; - // - [ShipmentRoute.vehicle_label][google.cloud.optimization.v1.ShipmentRoute.vehicle_label] in the injected solution; - // - [SkippedShipment.label][google.cloud.optimization.v1.SkippedShipment.label] and [ShipmentRoute.Visit.shipment_label][google.cloud.optimization.v1.ShipmentRoute.Visit.shipment_label] in + // * [Vehicle.label][google.cloud.optimization.v1.Vehicle.label] in the + // request; + // * [Shipment.label][google.cloud.optimization.v1.Shipment.label] in the + // request; + // * [ShipmentRoute.vehicle_label][google.cloud.optimization.v1.ShipmentRoute.vehicle_label] in the injected solution; + // * [SkippedShipment.label][google.cloud.optimization.v1.SkippedShipment.label] and [ShipmentRoute.Visit.shipment_label][google.cloud.optimization.v1.ShipmentRoute.Visit.shipment_label] in // the injected solution (except pickup/delivery visit pairs, whose // `shipment_label` must appear twice). // @@ -1198,82 +1198,79 @@ type ShipmentModel struct { // * 1 pickup visit request at locB. // // ``` - // - // model { - // vehicles { start_tags: "locA" end_tags: "locA" } - // shipments { pickups { tags: "locB" } } - // duration_distance_matrix_src_tags: "locA" - // duration_distance_matrix_src_tags: "locB" - // duration_distance_matrix_dst_tags: "locA" - // duration_distance_matrix_dst_tags: "locB" - // duration_distance_matrices { - // rows { # from: locA - // durations { seconds: 0 } meters: 0 # to: locA - // durations { seconds: 100 } meters: 1000 # to: locB - // } - // rows { # from: locB - // durations { seconds: 102 } meters: 990 # to: locA - // durations { seconds: 0 } meters: 0 # to: locB - // } - // } - // } - // + // model { + // vehicles { start_tags: "locA" end_tags: "locA" } + // shipments { pickups { tags: "locB" } } + // duration_distance_matrix_src_tags: "locA" + // duration_distance_matrix_src_tags: "locB" + // duration_distance_matrix_dst_tags: "locA" + // duration_distance_matrix_dst_tags: "locB" + // duration_distance_matrices { + // rows { # from: locA + // durations { seconds: 0 } meters: 0 # to: locA + // durations { seconds: 100 } meters: 1000 # to: locB + // } + // rows { # from: locB + // durations { seconds: 102 } meters: 990 # to: locA + // durations { seconds: 0 } meters: 0 # to: locB + // } + // } + // } // ``` // - // - There are three locations: locA, locB and locC. - // - 1 vehicle starting its route at locA and ending it at locB, using - // matrix "fast". - // - 1 vehicle starting its route at locB and ending it at locB, using - // matrix "slow". - // - 1 vehicle starting its route at locB and ending it at locB, using - // matrix "fast". - // - 1 pickup visit request at locC. // - // ``` - // - // model { - // vehicles { start_tags: "locA" end_tags: "locB" start_tags: "fast" } - // vehicles { start_tags: "locB" end_tags: "locB" start_tags: "slow" } - // vehicles { start_tags: "locB" end_tags: "locB" start_tags: "fast" } - // shipments { pickups { tags: "locC" } } - // duration_distance_matrix_src_tags: "locA" - // duration_distance_matrix_src_tags: "locB" - // duration_distance_matrix_src_tags: "locC" - // duration_distance_matrix_dst_tags: "locB" - // duration_distance_matrix_dst_tags: "locC" - // duration_distance_matrices { - // vehicle_start_tag: "fast" - // rows { # from: locA - // durations { seconds: 1000 } meters: 2000 # to: locB - // durations { seconds: 600 } meters: 1000 # to: locC - // } - // rows { # from: locB - // durations { seconds: 0 } meters: 0 # to: locB - // durations { seconds: 700 } meters: 1200 # to: locC - // } - // rows { # from: locC - // durations { seconds: 702 } meters: 1190 # to: locB - // durations { seconds: 0 } meters: 0 # to: locC - // } - // } - // duration_distance_matrices { - // vehicle_start_tag: "slow" - // rows { # from: locA - // durations { seconds: 1800 } meters: 2001 # to: locB - // durations { seconds: 900 } meters: 1002 # to: locC - // } - // rows { # from: locB - // durations { seconds: 0 } meters: 0 # to: locB - // durations { seconds: 1000 } meters: 1202 # to: locC - // } - // rows { # from: locC - // durations { seconds: 1001 } meters: 1195 # to: locB - // durations { seconds: 0 } meters: 0 # to: locC - // } - // } - // } + // * There are three locations: locA, locB and locC. + // * 1 vehicle starting its route at locA and ending it at locB, using + // matrix "fast". + // * 1 vehicle starting its route at locB and ending it at locB, using + // matrix "slow". + // * 1 vehicle starting its route at locB and ending it at locB, using + // matrix "fast". + // * 1 pickup visit request at locC. // // ``` + // model { + // vehicles { start_tags: "locA" end_tags: "locB" start_tags: "fast" } + // vehicles { start_tags: "locB" end_tags: "locB" start_tags: "slow" } + // vehicles { start_tags: "locB" end_tags: "locB" start_tags: "fast" } + // shipments { pickups { tags: "locC" } } + // duration_distance_matrix_src_tags: "locA" + // duration_distance_matrix_src_tags: "locB" + // duration_distance_matrix_src_tags: "locC" + // duration_distance_matrix_dst_tags: "locB" + // duration_distance_matrix_dst_tags: "locC" + // duration_distance_matrices { + // vehicle_start_tag: "fast" + // rows { # from: locA + // durations { seconds: 1000 } meters: 2000 # to: locB + // durations { seconds: 600 } meters: 1000 # to: locC + // } + // rows { # from: locB + // durations { seconds: 0 } meters: 0 # to: locB + // durations { seconds: 700 } meters: 1200 # to: locC + // } + // rows { # from: locC + // durations { seconds: 702 } meters: 1190 # to: locB + // durations { seconds: 0 } meters: 0 # to: locC + // } + // } + // duration_distance_matrices { + // vehicle_start_tag: "slow" + // rows { # from: locA + // durations { seconds: 1800 } meters: 2001 # to: locB + // durations { seconds: 900 } meters: 1002 # to: locC + // } + // rows { # from: locB + // durations { seconds: 0 } meters: 0 # to: locB + // durations { seconds: 1000 } meters: 1202 # to: locC + // } + // rows { # from: locC + // durations { seconds: 1001 } meters: 1195 # to: locB + // durations { seconds: 0 } meters: 0 # to: locC + // } + // } + // } + // ``` DurationDistanceMatrices []*ShipmentModel_DurationDistanceMatrix `protobuf:"bytes,8,rep,name=duration_distance_matrices,json=durationDistanceMatrices,proto3" json:"duration_distance_matrices,omitempty"` // Tags defining the sources of the duration and distance matrices; // `duration_distance_matrices(i).rows(j)` defines durations and distances @@ -1493,10 +1490,10 @@ type Shipment struct { // Specifies the cost that is incurred when this shipment is delivered by each // vehicle. If specified, it must have EITHER: // - // - the same number of elements as `costs_per_vehicle_indices`. + // * the same number of elements as `costs_per_vehicle_indices`. // `costs_per_vehicle[i]` corresponds to vehicle // `costs_per_vehicle_indices[i]` of the model. - // - the same number of elements as there are vehicles in the model. The + // * the same number of elements as there are vehicles in the model. The // i-th element corresponds to vehicle #i of the model. // // These costs must be in the same unit as `penalty_cost` and must not be @@ -2018,6 +2015,7 @@ type Vehicle struct { // Indices in the `break_rule` field in the source // [ShipmentModel][]. They correspond to break rules enforced on the vehicle. // + // // As of 2018/03, at most one rule index per vehicle can be specified. // // Deprecated: Do not use. @@ -2310,10 +2308,8 @@ type TimeWindow struct { // before soft_start_time, computed as: // // ``` - // - // max(0, soft_start_time - t.seconds) - // * cost_per_hour_before_soft_start_time / 3600, - // + // max(0, soft_start_time - t.seconds) + // * cost_per_hour_before_soft_start_time / 3600, // t being the time of the event. // ``` // @@ -2324,10 +2320,8 @@ type TimeWindow struct { // `soft_end_time`, computed as: // // ``` - // - // max(0, t.seconds - soft_end_time.seconds) - // * cost_per_hour_after_soft_end_time / 3600, - // + // max(0, t.seconds - soft_end_time.seconds) + // * cost_per_hour_after_soft_end_time / 3600, // t being the time of the event. // ``` // @@ -2559,10 +2553,8 @@ type DistanceLimit struct { // additional cost is 0 if the distance is under the limit, otherwise the // formula used to compute the cost is the following: // ``` - // - // (distance_meters - soft_max_meters) / 1000.0 * - // cost_per_kilometer_above_soft_max. - // + // (distance_meters - soft_max_meters) / 1000.0 * + // cost_per_kilometer_above_soft_max. // ``` // The cost must be nonnegative. CostPerKilometerAboveSoftMax *float64 `protobuf:"fixed64,3,opt,name=cost_per_kilometer_above_soft_max,json=costPerKilometerAboveSoftMax,proto3,oneof" json:"cost_per_kilometer_above_soft_max,omitempty"` @@ -2769,7 +2761,6 @@ type Waypoint struct { // Different ways to represent a location. // // Types that are assignable to LocationType: - // // *Waypoint_Location // *Waypoint_PlaceId LocationType isWaypoint_LocationType `protobuf_oneof:"location_type"` @@ -3116,10 +3107,8 @@ type ShipmentRoute struct { // still satisfying the visit and vehicle time windows. For example, // // ``` - // - // start_time(previous_visit) + duration(previous_visit) + - // travel_duration(previous_visit, next_visit) > start_time(next_visit) - // + // start_time(previous_visit) + duration(previous_visit) + + // travel_duration(previous_visit, next_visit) > start_time(next_visit) // ``` // // Arrival at next_visit will likely happen later than its current @@ -3677,224 +3666,207 @@ type OptimizeToursValidationError struct { // the deadline. // // * REQUEST_OPTIONS_ERROR = 12; - // - REQUEST_OPTIONS_INVALID_SOLVING_MODE = 1201; - // - REQUEST_OPTIONS_INVALID_MAX_VALIDATION_ERRORS = 1203; - // - REQUEST_OPTIONS_INVALID_GEODESIC_METERS_PER_SECOND = 1204; - // - REQUEST_OPTIONS_GEODESIC_METERS_PER_SECOND_TOO_SMALL = 1205; - // - REQUEST_OPTIONS_MISSING_GEODESIC_METERS_PER_SECOND = 1206; - // - REQUEST_OPTIONS_POPULATE_PATHFINDER_TRIPS_AND_GEODESIC_DISTANCE - // = 1207; - // - REQUEST_OPTIONS_COST_MODEL_OPTIONS_AND_GEODESIC_DISTANCE = 1208; - // - REQUEST_OPTIONS_TRAVEL_MODE_INCOMPATIBLE_WITH_TRAFFIC = 1211; - // - REQUEST_OPTIONS_MULTIPLE_TRAFFIC_FLAVORS = 1212; - // - REQUEST_OPTIONS_INVALID_TRAFFIC_FLAVOR = 1213; - // - REQUEST_OPTIONS_TRAFFIC_ENABLED_WITHOUT_GLOBAL_START_TIME = 1214; - // - REQUEST_OPTIONS_TRAFFIC_ENABLED_WITH_PRECEDENCES = 1215; - // - REQUEST_OPTIONS_TRAFFIC_PREFILL_MODE_INVALID = 1216; - // - REQUEST_OPTIONS_TRAFFIC_PREFILL_ENABLED_WITHOUT_TRAFFIC = 1217; - // + // * REQUEST_OPTIONS_INVALID_SOLVING_MODE = 1201; + // * REQUEST_OPTIONS_INVALID_MAX_VALIDATION_ERRORS = 1203; + // * REQUEST_OPTIONS_INVALID_GEODESIC_METERS_PER_SECOND = 1204; + // * REQUEST_OPTIONS_GEODESIC_METERS_PER_SECOND_TOO_SMALL = 1205; + // * REQUEST_OPTIONS_MISSING_GEODESIC_METERS_PER_SECOND = 1206; + // * REQUEST_OPTIONS_POPULATE_PATHFINDER_TRIPS_AND_GEODESIC_DISTANCE + // = 1207; + // * REQUEST_OPTIONS_COST_MODEL_OPTIONS_AND_GEODESIC_DISTANCE = 1208; + // * REQUEST_OPTIONS_TRAVEL_MODE_INCOMPATIBLE_WITH_TRAFFIC = 1211; + // * REQUEST_OPTIONS_MULTIPLE_TRAFFIC_FLAVORS = 1212; + // * REQUEST_OPTIONS_INVALID_TRAFFIC_FLAVOR = 1213; + // * REQUEST_OPTIONS_TRAFFIC_ENABLED_WITHOUT_GLOBAL_START_TIME = 1214; + // * REQUEST_OPTIONS_TRAFFIC_ENABLED_WITH_PRECEDENCES = 1215; + // * REQUEST_OPTIONS_TRAFFIC_PREFILL_MODE_INVALID = 1216; + // * REQUEST_OPTIONS_TRAFFIC_PREFILL_ENABLED_WITHOUT_TRAFFIC = 1217; // * INJECTED_SOLUTION_ERROR = 20; - // - INJECTED_SOLUTION_MISSING_LABEL = 2000; - // - INJECTED_SOLUTION_DUPLICATE_LABEL = 2001; - // - INJECTED_SOLUTION_AMBIGUOUS_INDEX = 2002; - // + // * INJECTED_SOLUTION_MISSING_LABEL = 2000; + // * INJECTED_SOLUTION_DUPLICATE_LABEL = 2001; + // * INJECTED_SOLUTION_AMBIGUOUS_INDEX = 2002; // * SHIPMENT_MODEL_ERROR = 22; - // - SHIPMENT_MODEL_TOO_LARGE = 2200; - // - SHIPMENT_MODEL_TOO_MANY_CAPACITY_TYPES = 2201; - // - SHIPMENT_MODEL_GLOBAL_START_TIME_NEGATIVE_OR_NAN = 2202; - // - SHIPMENT_MODEL_GLOBAL_END_TIME_TOO_LARGE_OR_NAN = 2203; - // - SHIPMENT_MODEL_GLOBAL_START_TIME_AFTER_GLOBAL_END_TIME = 2204; - // - SHIPMENT_MODEL_GLOBAL_DURATION_TOO_LONG = 2205; - // + // * SHIPMENT_MODEL_TOO_LARGE = 2200; + // * SHIPMENT_MODEL_TOO_MANY_CAPACITY_TYPES = 2201; + // * SHIPMENT_MODEL_GLOBAL_START_TIME_NEGATIVE_OR_NAN = 2202; + // * SHIPMENT_MODEL_GLOBAL_END_TIME_TOO_LARGE_OR_NAN = 2203; + // * SHIPMENT_MODEL_GLOBAL_START_TIME_AFTER_GLOBAL_END_TIME = 2204; + // * SHIPMENT_MODEL_GLOBAL_DURATION_TOO_LONG = 2205; // * INDEX_ERROR = 24; // * TAG_ERROR = 26; // * TIME_WINDOW_ERROR = 28; - // - TIME_WINDOW_INVALID_START_TIME = 2800; - // - TIME_WINDOW_INVALID_END_TIME = 2801; - // - TIME_WINDOW_INVALID_SOFT_START_TIME = 2802; - // - TIME_WINDOW_INVALID_SOFT_END_TIME = 2803; - // - TIME_WINDOW_OUTSIDE_GLOBAL_TIME_WINDOW = 2804; - // - TIME_WINDOW_START_TIME_AFTER_END_TIME = 2805; - // - TIME_WINDOW_INVALID_COST_PER_HOUR_BEFORE_SOFT_START_TIME = 2806; - // - TIME_WINDOW_INVALID_COST_PER_HOUR_AFTER_SOFT_END_TIME = 2807; - // - TIME_WINDOW_COST_BEFORE_SOFT_START_TIME_WITHOUT_SOFT_START_TIME - // = 2808; - // - TIME_WINDOW_COST_AFTER_SOFT_END_TIME_WITHOUT_SOFT_END_TIME = 2809; - // - TIME_WINDOW_SOFT_START_TIME_WITHOUT_COST_BEFORE_SOFT_START_TIME - // = 2810; - // - TIME_WINDOW_SOFT_END_TIME_WITHOUT_COST_AFTER_SOFT_END_TIME = 2811; - // - TIME_WINDOW_OVERLAPPING_ADJACENT_OR_EARLIER_THAN_PREVIOUS = 2812; - // - TIME_WINDOW_START_TIME_AFTER_SOFT_START_TIME = 2813; - // - TIME_WINDOW_SOFT_START_TIME_AFTER_END_TIME = 2814; - // - TIME_WINDOW_START_TIME_AFTER_SOFT_END_TIME = 2815; - // - TIME_WINDOW_SOFT_END_TIME_AFTER_END_TIME = 2816; - // - TIME_WINDOW_COST_BEFORE_SOFT_START_TIME_SET_AND_MULTIPLE_WINDOWS - // = 2817; - // - TIME_WINDOW_COST_AFTER_SOFT_END_TIME_SET_AND_MULTIPLE_WINDOWS = 2818; - // - TRANSITION_ATTRIBUTES_ERROR = 30; - // - TRANSITION_ATTRIBUTES_INVALID_COST = 3000; - // - TRANSITION_ATTRIBUTES_INVALID_COST_PER_KILOMETER = 3001; - // - TRANSITION_ATTRIBUTES_DUPLICATE_TAG_PAIR = 3002; - // - TRANSITION_ATTRIBUTES_DISTANCE_LIMIT_MAX_METERS_UNSUPPORTED = 3003; - // - TRANSITION_ATTRIBUTES_UNSPECIFIED_SOURCE_TAGS = 3004; - // - TRANSITION_ATTRIBUTES_CONFLICTING_SOURCE_TAGS_FIELDS = 3005; - // - TRANSITION_ATTRIBUTES_UNSPECIFIED_DESTINATION_TAGS = 3006; - // - TRANSITION_ATTRIBUTES_CONFLICTING_DESTINATION_TAGS_FIELDS = 3007; - // - TRANSITION_ATTRIBUTES_DELAY_DURATION_NEGATIVE_OR_NAN = 3008; - // - TRANSITION_ATTRIBUTES_DELAY_DURATION_EXCEEDS_GLOBAL_DURATION = 3009; - // + // * TIME_WINDOW_INVALID_START_TIME = 2800; + // * TIME_WINDOW_INVALID_END_TIME = 2801; + // * TIME_WINDOW_INVALID_SOFT_START_TIME = 2802; + // * TIME_WINDOW_INVALID_SOFT_END_TIME = 2803; + // * TIME_WINDOW_OUTSIDE_GLOBAL_TIME_WINDOW = 2804; + // * TIME_WINDOW_START_TIME_AFTER_END_TIME = 2805; + // * TIME_WINDOW_INVALID_COST_PER_HOUR_BEFORE_SOFT_START_TIME = 2806; + // * TIME_WINDOW_INVALID_COST_PER_HOUR_AFTER_SOFT_END_TIME = 2807; + // * TIME_WINDOW_COST_BEFORE_SOFT_START_TIME_WITHOUT_SOFT_START_TIME + // = 2808; + // * TIME_WINDOW_COST_AFTER_SOFT_END_TIME_WITHOUT_SOFT_END_TIME = 2809; + // * TIME_WINDOW_SOFT_START_TIME_WITHOUT_COST_BEFORE_SOFT_START_TIME + // = 2810; + // * TIME_WINDOW_SOFT_END_TIME_WITHOUT_COST_AFTER_SOFT_END_TIME = 2811; + // * TIME_WINDOW_OVERLAPPING_ADJACENT_OR_EARLIER_THAN_PREVIOUS = 2812; + // * TIME_WINDOW_START_TIME_AFTER_SOFT_START_TIME = 2813; + // * TIME_WINDOW_SOFT_START_TIME_AFTER_END_TIME = 2814; + // * TIME_WINDOW_START_TIME_AFTER_SOFT_END_TIME = 2815; + // * TIME_WINDOW_SOFT_END_TIME_AFTER_END_TIME = 2816; + // * TIME_WINDOW_COST_BEFORE_SOFT_START_TIME_SET_AND_MULTIPLE_WINDOWS + // = 2817; + // * TIME_WINDOW_COST_AFTER_SOFT_END_TIME_SET_AND_MULTIPLE_WINDOWS = 2818; + // * TRANSITION_ATTRIBUTES_ERROR = 30; + // * TRANSITION_ATTRIBUTES_INVALID_COST = 3000; + // * TRANSITION_ATTRIBUTES_INVALID_COST_PER_KILOMETER = 3001; + // * TRANSITION_ATTRIBUTES_DUPLICATE_TAG_PAIR = 3002; + // * TRANSITION_ATTRIBUTES_DISTANCE_LIMIT_MAX_METERS_UNSUPPORTED = 3003; + // * TRANSITION_ATTRIBUTES_UNSPECIFIED_SOURCE_TAGS = 3004; + // * TRANSITION_ATTRIBUTES_CONFLICTING_SOURCE_TAGS_FIELDS = 3005; + // * TRANSITION_ATTRIBUTES_UNSPECIFIED_DESTINATION_TAGS = 3006; + // * TRANSITION_ATTRIBUTES_CONFLICTING_DESTINATION_TAGS_FIELDS = 3007; + // * TRANSITION_ATTRIBUTES_DELAY_DURATION_NEGATIVE_OR_NAN = 3008; + // * TRANSITION_ATTRIBUTES_DELAY_DURATION_EXCEEDS_GLOBAL_DURATION = 3009; // * AMOUNT_ERROR = 31; - // - AMOUNT_NEGATIVE_VALUE = 3100; - // + // * AMOUNT_NEGATIVE_VALUE = 3100; // * LOAD_LIMIT_ERROR = 33; - // - LOAD_LIMIT_INVALID_COST_ABOVE_SOFT_MAX = 3303; - // - LOAD_LIMIT_SOFT_MAX_WITHOUT_COST_ABOVE_SOFT_MAX = 3304; - // - LOAD_LIMIT_COST_ABOVE_SOFT_MAX_WITHOUT_SOFT_MAX = 3305; - // - LOAD_LIMIT_NEGATIVE_SOFT_MAX = 3306; - // - LOAD_LIMIT_MIXED_DEMAND_TYPE = 3307; - // - LOAD_LIMIT_MAX_LOAD_NEGATIVE_VALUE = 3308; - // - LOAD_LIMIT_SOFT_MAX_ABOVE_MAX = 3309; - // + // * LOAD_LIMIT_INVALID_COST_ABOVE_SOFT_MAX = 3303; + // * LOAD_LIMIT_SOFT_MAX_WITHOUT_COST_ABOVE_SOFT_MAX = 3304; + // * LOAD_LIMIT_COST_ABOVE_SOFT_MAX_WITHOUT_SOFT_MAX = 3305; + // * LOAD_LIMIT_NEGATIVE_SOFT_MAX = 3306; + // * LOAD_LIMIT_MIXED_DEMAND_TYPE = 3307; + // * LOAD_LIMIT_MAX_LOAD_NEGATIVE_VALUE = 3308; + // * LOAD_LIMIT_SOFT_MAX_ABOVE_MAX = 3309; // * INTERVAL_ERROR = 34; - // - INTERVAL_MIN_EXCEEDS_MAX = 3401; - // - INTERVAL_NEGATIVE_MIN = 3402; - // - INTERVAL_NEGATIVE_MAX = 3403; - // - INTERVAL_MIN_EXCEEDS_CAPACITY = 3404; - // - INTERVAL_MAX_EXCEEDS_CAPACITY = 3405; - // + // * INTERVAL_MIN_EXCEEDS_MAX = 3401; + // * INTERVAL_NEGATIVE_MIN = 3402; + // * INTERVAL_NEGATIVE_MAX = 3403; + // * INTERVAL_MIN_EXCEEDS_CAPACITY = 3404; + // * INTERVAL_MAX_EXCEEDS_CAPACITY = 3405; // * DISTANCE_LIMIT_ERROR = 36; - // - DISTANCE_LIMIT_INVALID_COST_AFTER_SOFT_MAX = 3601; - // - DISTANCE_LIMIT_SOFT_MAX_WITHOUT_COST_AFTER_SOFT_MAX = 3602; - // - DISTANCE_LIMIT_COST_AFTER_SOFT_MAX_WITHOUT_SOFT_MAX = 3603; - // - DISTANCE_LIMIT_NEGATIVE_MAX = 3604; - // - DISTANCE_LIMIT_NEGATIVE_SOFT_MAX = 3605; - // - DISTANCE_LIMIT_SOFT_MAX_LARGER_THAN_MAX = 3606; - // + // * DISTANCE_LIMIT_INVALID_COST_AFTER_SOFT_MAX = 3601; + // * DISTANCE_LIMIT_SOFT_MAX_WITHOUT_COST_AFTER_SOFT_MAX = 3602; + // * DISTANCE_LIMIT_COST_AFTER_SOFT_MAX_WITHOUT_SOFT_MAX = 3603; + // * DISTANCE_LIMIT_NEGATIVE_MAX = 3604; + // * DISTANCE_LIMIT_NEGATIVE_SOFT_MAX = 3605; + // * DISTANCE_LIMIT_SOFT_MAX_LARGER_THAN_MAX = 3606; // * DURATION_LIMIT_ERROR = 38; - // - DURATION_LIMIT_MAX_DURATION_NEGATIVE_OR_NAN = 3800; - // - DURATION_LIMIT_SOFT_MAX_DURATION_NEGATIVE_OR_NAN = 3801; - // - DURATION_LIMIT_INVALID_COST_PER_HOUR_AFTER_SOFT_MAX = 3802; - // - DURATION_LIMIT_SOFT_MAX_WITHOUT_COST_AFTER_SOFT_MAX = 3803; - // - DURATION_LIMIT_COST_AFTER_SOFT_MAX_WITHOUT_SOFT_MAX = 3804; - // - DURATION_LIMIT_QUADRATIC_SOFT_MAX_DURATION_NEGATIVE_OR_NAN = 3805; - // - DURATION_LIMIT_INVALID_COST_AFTER_QUADRATIC_SOFT_MAX = 3806; - // - DURATION_LIMIT_QUADRATIC_SOFT_MAX_WITHOUT_COST_PER_SQUARE_HOUR - // = 3807; - // - DURATION_LIMIT_COST_PER_SQUARE_HOUR_WITHOUT_QUADRATIC_SOFT_MAX - // = 3808; - // - DURATION_LIMIT_QUADRATIC_SOFT_MAX_WITHOUT_MAX = 3809; - // - DURATION_LIMIT_SOFT_MAX_LARGER_THAN_MAX = 3810; - // - DURATION_LIMIT_QUADRATIC_SOFT_MAX_LARGER_THAN_MAX = 3811; - // - DURATION_LIMIT_DIFF_BETWEEN_MAX_AND_QUADRATIC_SOFT_MAX_TOO_LARGE - // = 3812; - // - DURATION_LIMIT_MAX_DURATION_EXCEEDS_GLOBAL_DURATION = 3813; - // - DURATION_LIMIT_SOFT_MAX_DURATION_EXCEEDS_GLOBAL_DURATION = 3814; - // - DURATION_LIMIT_QUADRATIC_SOFT_MAX_DURATION_EXCEEDS_GLOBAL_DURATION - // = 3815; - // + // * DURATION_LIMIT_MAX_DURATION_NEGATIVE_OR_NAN = 3800; + // * DURATION_LIMIT_SOFT_MAX_DURATION_NEGATIVE_OR_NAN = 3801; + // * DURATION_LIMIT_INVALID_COST_PER_HOUR_AFTER_SOFT_MAX = 3802; + // * DURATION_LIMIT_SOFT_MAX_WITHOUT_COST_AFTER_SOFT_MAX = 3803; + // * DURATION_LIMIT_COST_AFTER_SOFT_MAX_WITHOUT_SOFT_MAX = 3804; + // * DURATION_LIMIT_QUADRATIC_SOFT_MAX_DURATION_NEGATIVE_OR_NAN = 3805; + // * DURATION_LIMIT_INVALID_COST_AFTER_QUADRATIC_SOFT_MAX = 3806; + // * DURATION_LIMIT_QUADRATIC_SOFT_MAX_WITHOUT_COST_PER_SQUARE_HOUR + // = 3807; + // * DURATION_LIMIT_COST_PER_SQUARE_HOUR_WITHOUT_QUADRATIC_SOFT_MAX + // = 3808; + // * DURATION_LIMIT_QUADRATIC_SOFT_MAX_WITHOUT_MAX = 3809; + // * DURATION_LIMIT_SOFT_MAX_LARGER_THAN_MAX = 3810; + // * DURATION_LIMIT_QUADRATIC_SOFT_MAX_LARGER_THAN_MAX = 3811; + // * DURATION_LIMIT_DIFF_BETWEEN_MAX_AND_QUADRATIC_SOFT_MAX_TOO_LARGE + // = 3812; + // * DURATION_LIMIT_MAX_DURATION_EXCEEDS_GLOBAL_DURATION = 3813; + // * DURATION_LIMIT_SOFT_MAX_DURATION_EXCEEDS_GLOBAL_DURATION = 3814; + // * DURATION_LIMIT_QUADRATIC_SOFT_MAX_DURATION_EXCEEDS_GLOBAL_DURATION + // = 3815; // * SHIPMENT_ERROR = 40; - // - SHIPMENT_PD_ABSOLUTE_DETOUR_LIMIT_DURATION_NEGATIVE_OR_NAN = 4000; - // - SHIPMENT_PD_ABSOLUTE_DETOUR_LIMIT_DURATION_EXCEEDS_GLOBAL_DURATION - // = 4001; - // - SHIPMENT_PD_TIME_LIMIT_DURATION_NEGATIVE_OR_NAN = 4002; - // - SHIPMENT_PD_TIME_LIMIT_DURATION_EXCEEDS_GLOBAL_DURATION = 4003; - // - SHIPMENT_EMPTY_SHIPMENT_TYPE = 4004; - // - SHIPMENT_NO_PICKUP_NO_DELIVERY = 4005; - // - SHIPMENT_INVALID_PENALTY_COST = 4006; - // - SHIPMENT_ALLOWED_VEHICLE_INDEX_OUT_OF_BOUNDS = 4007; - // - SHIPMENT_DUPLICATE_ALLOWED_VEHICLE_INDEX = 4008; - // - SHIPMENT_INCONSISTENT_COST_FOR_VEHICLE_SIZE_WITHOUT_INDEX = 4009; - // - SHIPMENT_INCONSISTENT_COST_FOR_VEHICLE_SIZE_WITH_INDEX = 4010; - // - SHIPMENT_INVALID_COST_FOR_VEHICLE = 4011; - // - SHIPMENT_COST_FOR_VEHICLE_INDEX_OUT_OF_BOUNDS = 4012; - // - SHIPMENT_DUPLICATE_COST_FOR_VEHICLE_INDEX = 4013; - // - SHIPMENT_DETOUR_WITHOUT_PICKUP_AND_DELIVERY = 4014; - // + // * SHIPMENT_PD_ABSOLUTE_DETOUR_LIMIT_DURATION_NEGATIVE_OR_NAN = 4000; + // * SHIPMENT_PD_ABSOLUTE_DETOUR_LIMIT_DURATION_EXCEEDS_GLOBAL_DURATION + // = 4001; + // * SHIPMENT_PD_TIME_LIMIT_DURATION_NEGATIVE_OR_NAN = 4002; + // * SHIPMENT_PD_TIME_LIMIT_DURATION_EXCEEDS_GLOBAL_DURATION = 4003; + // * SHIPMENT_EMPTY_SHIPMENT_TYPE = 4004; + // * SHIPMENT_NO_PICKUP_NO_DELIVERY = 4005; + // * SHIPMENT_INVALID_PENALTY_COST = 4006; + // * SHIPMENT_ALLOWED_VEHICLE_INDEX_OUT_OF_BOUNDS = 4007; + // * SHIPMENT_DUPLICATE_ALLOWED_VEHICLE_INDEX = 4008; + // * SHIPMENT_INCONSISTENT_COST_FOR_VEHICLE_SIZE_WITHOUT_INDEX = 4009; + // * SHIPMENT_INCONSISTENT_COST_FOR_VEHICLE_SIZE_WITH_INDEX = 4010; + // * SHIPMENT_INVALID_COST_FOR_VEHICLE = 4011; + // * SHIPMENT_COST_FOR_VEHICLE_INDEX_OUT_OF_BOUNDS = 4012; + // * SHIPMENT_DUPLICATE_COST_FOR_VEHICLE_INDEX = 4013; + // * SHIPMENT_DETOUR_WITHOUT_PICKUP_AND_DELIVERY = 4014; // * VEHICLE_ERROR = 42; - // - VEHICLE_EMPTY_REQUIRED_OPERATOR_TYPE = 4200; - // - VEHICLE_DUPLICATE_REQUIRED_OPERATOR_TYPE = 4201; - // - VEHICLE_NO_OPERATOR_WITH_REQUIRED_OPERATOR_TYPE = 4202; - // - VEHICLE_EMPTY_START_TAG = 4203; - // - VEHICLE_DUPLICATE_START_TAG = 4204; - // - VEHICLE_EMPTY_END_TAG = 4205; - // - VEHICLE_DUPLICATE_END_TAG = 4206; - // - VEHICLE_EXTRA_VISIT_DURATION_NEGATIVE_OR_NAN = 4207; - // - VEHICLE_EXTRA_VISIT_DURATION_EXCEEDS_GLOBAL_DURATION = 4208; - // - VEHICLE_EXTRA_VISIT_DURATION_EMPTY_KEY = 4209; - // - VEHICLE_FIRST_SHIPMENT_INDEX_OUT_OF_BOUNDS = 4210; - // - VEHICLE_FIRST_SHIPMENT_IGNORED = 4211; - // - VEHICLE_FIRST_SHIPMENT_NOT_BOUND = 4212; - // - VEHICLE_LAST_SHIPMENT_INDEX_OUT_OF_BOUNDS = 4213; - // - VEHICLE_LAST_SHIPMENT_IGNORED = 4214; - // - VEHICLE_LAST_SHIPMENT_NOT_BOUND = 4215; - // - VEHICLE_IGNORED_WITH_USED_IF_ROUTE_IS_EMPTY = 4216; - // - VEHICLE_INVALID_COST_PER_KILOMETER = 4217; - // - VEHICLE_INVALID_COST_PER_HOUR = 4218; - // - VEHICLE_INVALID_COST_PER_TRAVELED_HOUR = 4219; - // - VEHICLE_INVALID_FIXED_COST = 4220; - // - VEHICLE_INVALID_TRAVEL_DURATION_MULTIPLE = 4221; - // - VEHICLE_MINIMUM_DURATION_LONGER_THAN_DURATION_LIMIT = 4222; - // + // * VEHICLE_EMPTY_REQUIRED_OPERATOR_TYPE = 4200; + // * VEHICLE_DUPLICATE_REQUIRED_OPERATOR_TYPE = 4201; + // * VEHICLE_NO_OPERATOR_WITH_REQUIRED_OPERATOR_TYPE = 4202; + // * VEHICLE_EMPTY_START_TAG = 4203; + // * VEHICLE_DUPLICATE_START_TAG = 4204; + // * VEHICLE_EMPTY_END_TAG = 4205; + // * VEHICLE_DUPLICATE_END_TAG = 4206; + // * VEHICLE_EXTRA_VISIT_DURATION_NEGATIVE_OR_NAN = 4207; + // * VEHICLE_EXTRA_VISIT_DURATION_EXCEEDS_GLOBAL_DURATION = 4208; + // * VEHICLE_EXTRA_VISIT_DURATION_EMPTY_KEY = 4209; + // * VEHICLE_FIRST_SHIPMENT_INDEX_OUT_OF_BOUNDS = 4210; + // * VEHICLE_FIRST_SHIPMENT_IGNORED = 4211; + // * VEHICLE_FIRST_SHIPMENT_NOT_BOUND = 4212; + // * VEHICLE_LAST_SHIPMENT_INDEX_OUT_OF_BOUNDS = 4213; + // * VEHICLE_LAST_SHIPMENT_IGNORED = 4214; + // * VEHICLE_LAST_SHIPMENT_NOT_BOUND = 4215; + // * VEHICLE_IGNORED_WITH_USED_IF_ROUTE_IS_EMPTY = 4216; + // * VEHICLE_INVALID_COST_PER_KILOMETER = 4217; + // * VEHICLE_INVALID_COST_PER_HOUR = 4218; + // * VEHICLE_INVALID_COST_PER_TRAVELED_HOUR = 4219; + // * VEHICLE_INVALID_FIXED_COST = 4220; + // * VEHICLE_INVALID_TRAVEL_DURATION_MULTIPLE = 4221; + // * VEHICLE_MINIMUM_DURATION_LONGER_THAN_DURATION_LIMIT = 4222; // * VISIT_REQUEST_ERROR = 44; - // - VISIT_REQUEST_EMPTY_TAG = 4400; - // - VISIT_REQUEST_DUPLICATE_TAG = 4401; - // - VISIT_REQUEST_DURATION_NEGATIVE_OR_NAN = 4404; - // - VISIT_REQUEST_DURATION_EXCEEDS_GLOBAL_DURATION = 4405; - // + // * VISIT_REQUEST_EMPTY_TAG = 4400; + // * VISIT_REQUEST_DUPLICATE_TAG = 4401; + // * VISIT_REQUEST_DURATION_NEGATIVE_OR_NAN = 4404; + // * VISIT_REQUEST_DURATION_EXCEEDS_GLOBAL_DURATION = 4405; // * PRECEDENCE_ERROR = 46; // * BREAK_ERROR = 48; - // - BREAK_RULE_EMPTY = 4800; - // - BREAK_REQUEST_UNSPECIFIED_DURATION = 4801; - // - BREAK_REQUEST_UNSPECIFIED_EARLIEST_START_TIME = 4802; - // - BREAK_REQUEST_UNSPECIFIED_LATEST_START_TIME = 4803; - // - BREAK_REQUEST_DURATION_NEGATIVE_OR_NAN = 4804; = 4804; - // - BREAK_REQUEST_LATEST_START_TIME_BEFORE_EARLIEST_START_TIME = 4805; - // - BREAK_REQUEST_EARLIEST_START_TIME_BEFORE_GLOBAL_START_TIME = 4806; - // - BREAK_REQUEST_LATEST_END_TIME_AFTER_GLOBAL_END_TIME = 4807; - // - BREAK_REQUEST_NON_SCHEDULABLE = 4808; - // - BREAK_FREQUENCY_MAX_INTER_BREAK_DURATION_NEGATIVE_OR_NAN = 4809; - // - BREAK_FREQUENCY_MIN_BREAK_DURATION_NEGATIVE_OR_NAN = 4810; - // - BREAK_FREQUENCY_MIN_BREAK_DURATION_EXCEEDS_GLOBAL_DURATION = 4811; - // - BREAK_FREQUENCY_MAX_INTER_BREAK_DURATION_EXCEEDS_GLOBAL_DURATION - // = 4812; - // - BREAK_REQUEST_DURATION_EXCEEDS_GLOBAL_DURATION = 4813; - // - BREAK_FREQUENCY_MISSING_MAX_INTER_BREAK_DURATION = 4814; - // - BREAK_FREQUENCY_MISSING_MIN_BREAK_DURATION = 4815; - // + // * BREAK_RULE_EMPTY = 4800; + // * BREAK_REQUEST_UNSPECIFIED_DURATION = 4801; + // * BREAK_REQUEST_UNSPECIFIED_EARLIEST_START_TIME = 4802; + // * BREAK_REQUEST_UNSPECIFIED_LATEST_START_TIME = 4803; + // * BREAK_REQUEST_DURATION_NEGATIVE_OR_NAN = 4804; = 4804; + // * BREAK_REQUEST_LATEST_START_TIME_BEFORE_EARLIEST_START_TIME = 4805; + // * BREAK_REQUEST_EARLIEST_START_TIME_BEFORE_GLOBAL_START_TIME = 4806; + // * BREAK_REQUEST_LATEST_END_TIME_AFTER_GLOBAL_END_TIME = 4807; + // * BREAK_REQUEST_NON_SCHEDULABLE = 4808; + // * BREAK_FREQUENCY_MAX_INTER_BREAK_DURATION_NEGATIVE_OR_NAN = 4809; + // * BREAK_FREQUENCY_MIN_BREAK_DURATION_NEGATIVE_OR_NAN = 4810; + // * BREAK_FREQUENCY_MIN_BREAK_DURATION_EXCEEDS_GLOBAL_DURATION = 4811; + // * BREAK_FREQUENCY_MAX_INTER_BREAK_DURATION_EXCEEDS_GLOBAL_DURATION + // = 4812; + // * BREAK_REQUEST_DURATION_EXCEEDS_GLOBAL_DURATION = 4813; + // * BREAK_FREQUENCY_MISSING_MAX_INTER_BREAK_DURATION = 4814; + // * BREAK_FREQUENCY_MISSING_MIN_BREAK_DURATION = 4815; // * SHIPMENT_TYPE_INCOMPATIBILITY_ERROR = 50; - // - SHIPMENT_TYPE_INCOMPATIBILITY_EMPTY_TYPE = 5001; - // - SHIPMENT_TYPE_INCOMPATIBILITY_LESS_THAN_TWO_TYPES = 5002; - // - SHIPMENT_TYPE_INCOMPATIBILITY_DUPLICATE_TYPE = 5003; - // - SHIPMENT_TYPE_INCOMPATIBILITY_INVALID_INCOMPATIBILITY_MODE = 5004; - // - SHIPMENT_TYPE_INCOMPATIBILITY_TOO_MANY_INCOMPATIBILITIES = 5005; - // + // * SHIPMENT_TYPE_INCOMPATIBILITY_EMPTY_TYPE = 5001; + // * SHIPMENT_TYPE_INCOMPATIBILITY_LESS_THAN_TWO_TYPES = 5002; + // * SHIPMENT_TYPE_INCOMPATIBILITY_DUPLICATE_TYPE = 5003; + // * SHIPMENT_TYPE_INCOMPATIBILITY_INVALID_INCOMPATIBILITY_MODE = 5004; + // * SHIPMENT_TYPE_INCOMPATIBILITY_TOO_MANY_INCOMPATIBILITIES = 5005; // * SHIPMENT_TYPE_REQUIREMENT_ERROR = 52; - // - SHIPMENT_TYPE_REQUIREMENT_NO_REQUIRED_TYPE = 52001; - // - SHIPMENT_TYPE_REQUIREMENT_NO_DEPENDENT_TYPE = 52002; - // - SHIPMENT_TYPE_REQUIREMENT_INVALID_REQUIREMENT_MODE = 52003; - // - SHIPMENT_TYPE_REQUIREMENT_TOO_MANY_REQUIREMENTS = 52004; - // - SHIPMENT_TYPE_REQUIREMENT_EMPTY_REQUIRED_TYPE = 52005; - // - SHIPMENT_TYPE_REQUIREMENT_DUPLICATE_REQUIRED_TYPE = 52006; - // - SHIPMENT_TYPE_REQUIREMENT_NO_REQUIRED_TYPE_FOUND = 52007; - // - SHIPMENT_TYPE_REQUIREMENT_EMPTY_DEPENDENT_TYPE = 52008; - // - SHIPMENT_TYPE_REQUIREMENT_DUPLICATE_DEPENDENT_TYPE = 52009; - // - SHIPMENT_TYPE_REQUIREMENT_SELF_DEPENDENT_TYPE = 52010; - // - SHIPMENT_TYPE_REQUIREMENT_GRAPH_HAS_CYCLES = 52011; - // + // * SHIPMENT_TYPE_REQUIREMENT_NO_REQUIRED_TYPE = 52001; + // * SHIPMENT_TYPE_REQUIREMENT_NO_DEPENDENT_TYPE = 52002; + // * SHIPMENT_TYPE_REQUIREMENT_INVALID_REQUIREMENT_MODE = 52003; + // * SHIPMENT_TYPE_REQUIREMENT_TOO_MANY_REQUIREMENTS = 52004; + // * SHIPMENT_TYPE_REQUIREMENT_EMPTY_REQUIRED_TYPE = 52005; + // * SHIPMENT_TYPE_REQUIREMENT_DUPLICATE_REQUIRED_TYPE = 52006; + // * SHIPMENT_TYPE_REQUIREMENT_NO_REQUIRED_TYPE_FOUND = 52007; + // * SHIPMENT_TYPE_REQUIREMENT_EMPTY_DEPENDENT_TYPE = 52008; + // * SHIPMENT_TYPE_REQUIREMENT_DUPLICATE_DEPENDENT_TYPE = 52009; + // * SHIPMENT_TYPE_REQUIREMENT_SELF_DEPENDENT_TYPE = 52010; + // * SHIPMENT_TYPE_REQUIREMENT_GRAPH_HAS_CYCLES = 52011; // * VEHICLE_OPERATOR_ERROR = 54; - // - VEHICLE_OPERATOR_EMPTY_TYPE = 5400; - // - VEHICLE_OPERATOR_MULTIPLE_START_TIME_WINDOWS = 5401; - // - VEHICLE_OPERATOR_SOFT_START_TIME_WINDOW = 5402; - // - VEHICLE_OPERATOR_MULTIPLE_END_TIME_WINDOWS = 5403; - // - VEHICLE_OPERATOR_SOFT_END_TIME_WINDOW = 5404; - // + // * VEHICLE_OPERATOR_EMPTY_TYPE = 5400; + // * VEHICLE_OPERATOR_MULTIPLE_START_TIME_WINDOWS = 5401; + // * VEHICLE_OPERATOR_SOFT_START_TIME_WINDOW = 5402; + // * VEHICLE_OPERATOR_MULTIPLE_END_TIME_WINDOWS = 5403; + // * VEHICLE_OPERATOR_SOFT_END_TIME_WINDOW = 5404; // * DURATION_SECONDS_MATRIX_ERROR = 56; - // - DURATION_SECONDS_MATRIX_DURATION_NEGATIVE_OR_NAN = 5600; - // - DURATION_SECONDS_MATRIX_DURATION_EXCEEDS_GLOBAL_DURATION = 5601; - // + // * DURATION_SECONDS_MATRIX_DURATION_NEGATIVE_OR_NAN = 5600; + // * DURATION_SECONDS_MATRIX_DURATION_EXCEEDS_GLOBAL_DURATION = 5601; // * GRAPH_ARC_ERROR = 58; - // - GRAPH_ARC_DURATION_NEGATIVE_OR_NAN = 5800; - // - GRAPH_ARC_DURATION_EXCEEDS_GLOBAL_DURATION = 5801; + // * GRAPH_ARC_DURATION_NEGATIVE_OR_NAN = 5800; + // * GRAPH_ARC_DURATION_EXCEEDS_GLOBAL_DURATION = 5801; Code int32 `protobuf:"varint,1,opt,name=code,proto3" json:"code,omitempty"` // The error display name. DisplayName string `protobuf:"bytes,2,opt,name=display_name,json=displayName,proto3" json:"display_name,omitempty"` @@ -5023,9 +4995,7 @@ type Vehicle_DurationLimit struct { // The additional cost is 0 if the duration is under the threshold, // otherwise the cost depends on the duration as follows: // ``` - // - // cost_per_hour_after_soft_max * (duration - soft_max_duration) - // + // cost_per_hour_after_soft_max * (duration - soft_max_duration) // ``` // The cost must be nonnegative. CostPerHourAfterSoftMax *float64 `protobuf:"fixed64,3,opt,name=cost_per_hour_after_soft_max,json=costPerHourAfterSoftMax,proto3,oneof" json:"cost_per_hour_after_soft_max,omitempty"` @@ -5038,7 +5008,7 @@ type Vehicle_DurationLimit struct { // less than `max_duration`, and the difference must be no larger than one // day: // - // `max_duration - quadratic_soft_max_duration <= 86400 seconds` + // `max_duration - quadratic_soft_max_duration <= 86400 seconds` QuadraticSoftMaxDuration *durationpb.Duration `protobuf:"bytes,4,opt,name=quadratic_soft_max_duration,json=quadraticSoftMaxDuration,proto3" json:"quadratic_soft_max_duration,omitempty"` // Cost per square hour incurred if the // `quadratic_soft_max_duration` threshold is violated. @@ -5047,10 +5017,8 @@ type Vehicle_DurationLimit struct { // otherwise the cost depends on the duration as follows: // // ``` - // - // cost_per_square_hour_after_quadratic_soft_max * - // (duration - quadratic_soft_max_duration)^2 - // + // cost_per_square_hour_after_quadratic_soft_max * + // (duration - quadratic_soft_max_duration)^2 // ``` // // The cost must be nonnegative. @@ -6342,7 +6310,6 @@ type OptimizeToursValidationError_FieldReference struct { // Name of the field, e.g., "vehicles". Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Types that are assignable to IndexOrKey: - // // *OptimizeToursValidationError_FieldReference_Index // *OptimizeToursValidationError_FieldReference_Key IndexOrKey isOptimizeToursValidationError_FieldReference_IndexOrKey `protobuf_oneof:"index_or_key"` diff --git a/orchestration/airflow/service/apiv1/doc.go b/orchestration/airflow/service/apiv1/doc.go index c5d52773308c..4ce958ca58fa 100644 --- a/orchestration/airflow/service/apiv1/doc.go +++ b/orchestration/airflow/service/apiv1/doc.go @@ -85,6 +85,8 @@ package service // import "cloud.google.com/go/orchestration/airflow/service/api import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -173,3 +175,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/orchestration/airflow/service/apiv1/environments_client.go b/orchestration/airflow/service/apiv1/environments_client.go index d599f9d0ed52..afd2ed721911 100644 --- a/orchestration/airflow/service/apiv1/environments_client.go +++ b/orchestration/airflow/service/apiv1/environments_client.go @@ -17,9 +17,12 @@ package service import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,13 +30,16 @@ import ( lroauto "cloud.google.com/go/longrunning/autogen" servicepb "cloud.google.com/go/orchestration/airflow/service/apiv1/servicepb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -80,6 +86,21 @@ func defaultEnvironmentsCallOptions() *EnvironmentsCallOptions { } } +func defaultEnvironmentsRESTCallOptions() *EnvironmentsCallOptions { + return &EnvironmentsCallOptions{ + CreateEnvironment: []gax.CallOption{}, + GetEnvironment: []gax.CallOption{}, + ListEnvironments: []gax.CallOption{}, + UpdateEnvironment: []gax.CallOption{}, + DeleteEnvironment: []gax.CallOption{}, + SaveSnapshot: []gax.CallOption{}, + LoadSnapshot: []gax.CallOption{}, + DeleteOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalEnvironmentsClient is an interface that defines the methods available from Cloud Composer API. type internalEnvironmentsClient interface { Close() error @@ -328,6 +349,89 @@ func (c *environmentsGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type environmentsRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing EnvironmentsClient + CallOptions **EnvironmentsCallOptions +} + +// NewEnvironmentsRESTClient creates a new environments rest client. +// +// Managed Apache Airflow Environments. +func NewEnvironmentsRESTClient(ctx context.Context, opts ...option.ClientOption) (*EnvironmentsClient, error) { + clientOpts := append(defaultEnvironmentsRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultEnvironmentsRESTCallOptions() + c := &environmentsRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &EnvironmentsClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultEnvironmentsRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://composer.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://composer.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://composer.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *environmentsRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *environmentsRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *environmentsRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *environmentsGRPCClient) CreateEnvironment(ctx context.Context, req *servicepb.CreateEnvironmentRequest, opts ...gax.CallOption) (*CreateEnvironmentOperation, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -560,9 +664,694 @@ func (c *environmentsGRPCClient) ListOperations(ctx context.Context, req *longru return it } +// CreateEnvironment create a new environment. +func (c *environmentsRESTClient) CreateEnvironment(ctx context.Context, req *servicepb.CreateEnvironmentRequest, opts ...gax.CallOption) (*CreateEnvironmentOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetEnvironment() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/environments", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateEnvironmentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetEnvironment get an existing environment. +func (c *environmentsRESTClient) GetEnvironment(ctx context.Context, req *servicepb.GetEnvironmentRequest, opts ...gax.CallOption) (*servicepb.Environment, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetEnvironment[0:len((*c.CallOptions).GetEnvironment):len((*c.CallOptions).GetEnvironment)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &servicepb.Environment{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListEnvironments list environments. +func (c *environmentsRESTClient) ListEnvironments(ctx context.Context, req *servicepb.ListEnvironmentsRequest, opts ...gax.CallOption) *EnvironmentIterator { + it := &EnvironmentIterator{} + req = proto.Clone(req).(*servicepb.ListEnvironmentsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*servicepb.Environment, string, error) { + resp := &servicepb.ListEnvironmentsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/environments", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetEnvironments(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// UpdateEnvironment update an environment. +func (c *environmentsRESTClient) UpdateEnvironment(ctx context.Context, req *servicepb.UpdateEnvironmentRequest, opts ...gax.CallOption) (*UpdateEnvironmentOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetEnvironment() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateEnvironmentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteEnvironment delete an environment. +func (c *environmentsRESTClient) DeleteEnvironment(ctx context.Context, req *servicepb.DeleteEnvironmentRequest, opts ...gax.CallOption) (*DeleteEnvironmentOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteEnvironmentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// SaveSnapshot creates a snapshots of a Cloud Composer environment. +// +// As a result of this operation, snapshot of environment’s state is stored +// in a location specified in the SaveSnapshotRequest. +func (c *environmentsRESTClient) SaveSnapshot(ctx context.Context, req *servicepb.SaveSnapshotRequest, opts ...gax.CallOption) (*SaveSnapshotOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:saveSnapshot", req.GetEnvironment()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "environment", url.QueryEscape(req.GetEnvironment()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &SaveSnapshotOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// LoadSnapshot loads a snapshot of a Cloud Composer environment. +// +// As a result of this operation, a snapshot of environment’s specified in +// LoadSnapshotRequest is loaded into the environment. +func (c *environmentsRESTClient) LoadSnapshot(ctx context.Context, req *servicepb.LoadSnapshotRequest, opts ...gax.CallOption) (*LoadSnapshotOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:loadSnapshot", req.GetEnvironment()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "environment", url.QueryEscape(req.GetEnvironment()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &LoadSnapshotOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteOperation is a utility method from google.longrunning.Operations. +func (c *environmentsRESTClient) DeleteOperation(ctx context.Context, req *longrunningpb.DeleteOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *environmentsRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *environmentsRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + // CreateEnvironmentOperation manages a long-running operation from CreateEnvironment. type CreateEnvironmentOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateEnvironmentOperation returns a new CreateEnvironmentOperation from a given name. @@ -573,10 +1362,21 @@ func (c *environmentsGRPCClient) CreateEnvironmentOperation(name string) *Create } } +// CreateEnvironmentOperation returns a new CreateEnvironmentOperation from a given name. +// The name must be that of a previously created CreateEnvironmentOperation, possibly from a different process. +func (c *environmentsRESTClient) CreateEnvironmentOperation(name string) *CreateEnvironmentOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateEnvironmentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateEnvironmentOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*servicepb.Environment, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp servicepb.Environment if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -594,6 +1394,7 @@ func (op *CreateEnvironmentOperation) Wait(ctx context.Context, opts ...gax.Call // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateEnvironmentOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*servicepb.Environment, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp servicepb.Environment if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -631,7 +1432,8 @@ func (op *CreateEnvironmentOperation) Name() string { // DeleteEnvironmentOperation manages a long-running operation from DeleteEnvironment. type DeleteEnvironmentOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteEnvironmentOperation returns a new DeleteEnvironmentOperation from a given name. @@ -642,10 +1444,21 @@ func (c *environmentsGRPCClient) DeleteEnvironmentOperation(name string) *Delete } } +// DeleteEnvironmentOperation returns a new DeleteEnvironmentOperation from a given name. +// The name must be that of a previously created DeleteEnvironmentOperation, possibly from a different process. +func (c *environmentsRESTClient) DeleteEnvironmentOperation(name string) *DeleteEnvironmentOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteEnvironmentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteEnvironmentOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -659,6 +1472,7 @@ func (op *DeleteEnvironmentOperation) Wait(ctx context.Context, opts ...gax.Call // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteEnvironmentOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -689,7 +1503,8 @@ func (op *DeleteEnvironmentOperation) Name() string { // LoadSnapshotOperation manages a long-running operation from LoadSnapshot. type LoadSnapshotOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // LoadSnapshotOperation returns a new LoadSnapshotOperation from a given name. @@ -700,10 +1515,21 @@ func (c *environmentsGRPCClient) LoadSnapshotOperation(name string) *LoadSnapsho } } +// LoadSnapshotOperation returns a new LoadSnapshotOperation from a given name. +// The name must be that of a previously created LoadSnapshotOperation, possibly from a different process. +func (c *environmentsRESTClient) LoadSnapshotOperation(name string) *LoadSnapshotOperation { + override := fmt.Sprintf("/v1/%s", name) + return &LoadSnapshotOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *LoadSnapshotOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*servicepb.LoadSnapshotResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp servicepb.LoadSnapshotResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -721,6 +1547,7 @@ func (op *LoadSnapshotOperation) Wait(ctx context.Context, opts ...gax.CallOptio // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *LoadSnapshotOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*servicepb.LoadSnapshotResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp servicepb.LoadSnapshotResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -758,7 +1585,8 @@ func (op *LoadSnapshotOperation) Name() string { // SaveSnapshotOperation manages a long-running operation from SaveSnapshot. type SaveSnapshotOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // SaveSnapshotOperation returns a new SaveSnapshotOperation from a given name. @@ -769,10 +1597,21 @@ func (c *environmentsGRPCClient) SaveSnapshotOperation(name string) *SaveSnapsho } } +// SaveSnapshotOperation returns a new SaveSnapshotOperation from a given name. +// The name must be that of a previously created SaveSnapshotOperation, possibly from a different process. +func (c *environmentsRESTClient) SaveSnapshotOperation(name string) *SaveSnapshotOperation { + override := fmt.Sprintf("/v1/%s", name) + return &SaveSnapshotOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *SaveSnapshotOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*servicepb.SaveSnapshotResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp servicepb.SaveSnapshotResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -790,6 +1629,7 @@ func (op *SaveSnapshotOperation) Wait(ctx context.Context, opts ...gax.CallOptio // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *SaveSnapshotOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*servicepb.SaveSnapshotResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp servicepb.SaveSnapshotResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -827,7 +1667,8 @@ func (op *SaveSnapshotOperation) Name() string { // UpdateEnvironmentOperation manages a long-running operation from UpdateEnvironment. type UpdateEnvironmentOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateEnvironmentOperation returns a new UpdateEnvironmentOperation from a given name. @@ -838,10 +1679,21 @@ func (c *environmentsGRPCClient) UpdateEnvironmentOperation(name string) *Update } } +// UpdateEnvironmentOperation returns a new UpdateEnvironmentOperation from a given name. +// The name must be that of a previously created UpdateEnvironmentOperation, possibly from a different process. +func (c *environmentsRESTClient) UpdateEnvironmentOperation(name string) *UpdateEnvironmentOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateEnvironmentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateEnvironmentOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*servicepb.Environment, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp servicepb.Environment if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -859,6 +1711,7 @@ func (op *UpdateEnvironmentOperation) Wait(ctx context.Context, opts ...gax.Call // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateEnvironmentOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*servicepb.Environment, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp servicepb.Environment if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/orchestration/airflow/service/apiv1/environments_client_example_test.go b/orchestration/airflow/service/apiv1/environments_client_example_test.go index b3cf5f2b190a..6b44c1263a09 100644 --- a/orchestration/airflow/service/apiv1/environments_client_example_test.go +++ b/orchestration/airflow/service/apiv1/environments_client_example_test.go @@ -42,6 +42,23 @@ func ExampleNewEnvironmentsClient() { _ = c } +func ExampleNewEnvironmentsRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := service.NewEnvironmentsRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleEnvironmentsClient_CreateEnvironment() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/orchestration/airflow/service/apiv1/gapic_metadata.json b/orchestration/airflow/service/apiv1/gapic_metadata.json index b67e494ea918..372b254a9a53 100644 --- a/orchestration/airflow/service/apiv1/gapic_metadata.json +++ b/orchestration/airflow/service/apiv1/gapic_metadata.json @@ -61,6 +61,61 @@ ] } } + }, + "rest": { + "libraryClient": "EnvironmentsClient", + "rpcs": { + "CreateEnvironment": { + "methods": [ + "CreateEnvironment" + ] + }, + "DeleteEnvironment": { + "methods": [ + "DeleteEnvironment" + ] + }, + "DeleteOperation": { + "methods": [ + "DeleteOperation" + ] + }, + "GetEnvironment": { + "methods": [ + "GetEnvironment" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ListEnvironments": { + "methods": [ + "ListEnvironments" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "LoadSnapshot": { + "methods": [ + "LoadSnapshot" + ] + }, + "SaveSnapshot": { + "methods": [ + "SaveSnapshot" + ] + }, + "UpdateEnvironment": { + "methods": [ + "UpdateEnvironment" + ] + } + } } } }, @@ -90,6 +145,31 @@ ] } } + }, + "rest": { + "libraryClient": "ImageVersionsClient", + "rpcs": { + "DeleteOperation": { + "methods": [ + "DeleteOperation" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ListImageVersions": { + "methods": [ + "ListImageVersions" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + } + } } } } diff --git a/orchestration/airflow/service/apiv1/image_versions_client.go b/orchestration/airflow/service/apiv1/image_versions_client.go index e8b27257e644..3ca2f01a1524 100644 --- a/orchestration/airflow/service/apiv1/image_versions_client.go +++ b/orchestration/airflow/service/apiv1/image_versions_client.go @@ -19,18 +19,23 @@ package service import ( "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" servicepb "cloud.google.com/go/orchestration/airflow/service/apiv1/servicepb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -65,6 +70,15 @@ func defaultImageVersionsCallOptions() *ImageVersionsCallOptions { } } +func defaultImageVersionsRESTCallOptions() *ImageVersionsCallOptions { + return &ImageVersionsCallOptions{ + ListImageVersions: []gax.CallOption{}, + DeleteOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalImageVersionsClient is an interface that defines the methods available from Cloud Composer API. type internalImageVersionsClient interface { Close() error @@ -215,6 +229,74 @@ func (c *imageVersionsGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type imageVersionsRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing ImageVersionsClient + CallOptions **ImageVersionsCallOptions +} + +// NewImageVersionsRESTClient creates a new image versions rest client. +// +// Readonly service to query available ImageVersions. +func NewImageVersionsRESTClient(ctx context.Context, opts ...option.ClientOption) (*ImageVersionsClient, error) { + clientOpts := append(defaultImageVersionsRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultImageVersionsRESTCallOptions() + c := &imageVersionsRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &ImageVersionsClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultImageVersionsRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://composer.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://composer.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://composer.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *imageVersionsRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *imageVersionsRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *imageVersionsRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *imageVersionsGRPCClient) ListImageVersions(ctx context.Context, req *servicepb.ListImageVersionsRequest, opts ...gax.CallOption) *ImageVersionIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -335,6 +417,286 @@ func (c *imageVersionsGRPCClient) ListOperations(ctx context.Context, req *longr return it } +// ListImageVersions list ImageVersions for provided location. +func (c *imageVersionsRESTClient) ListImageVersions(ctx context.Context, req *servicepb.ListImageVersionsRequest, opts ...gax.CallOption) *ImageVersionIterator { + it := &ImageVersionIterator{} + req = proto.Clone(req).(*servicepb.ListImageVersionsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*servicepb.ImageVersion, string, error) { + resp := &servicepb.ListImageVersionsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/imageVersions", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetIncludePastReleases() { + params.Add("includePastReleases", fmt.Sprintf("%v", req.GetIncludePastReleases())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetImageVersions(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// DeleteOperation is a utility method from google.longrunning.Operations. +func (c *imageVersionsRESTClient) DeleteOperation(ctx context.Context, req *longrunningpb.DeleteOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *imageVersionsRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *imageVersionsRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + // ImageVersionIterator manages a stream of *servicepb.ImageVersion. type ImageVersionIterator struct { items []*servicepb.ImageVersion diff --git a/orchestration/airflow/service/apiv1/image_versions_client_example_test.go b/orchestration/airflow/service/apiv1/image_versions_client_example_test.go index e804edbd3993..4d234780de19 100644 --- a/orchestration/airflow/service/apiv1/image_versions_client_example_test.go +++ b/orchestration/airflow/service/apiv1/image_versions_client_example_test.go @@ -42,6 +42,23 @@ func ExampleNewImageVersionsClient() { _ = c } +func ExampleNewImageVersionsRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := service.NewImageVersionsRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleImageVersionsClient_ListImageVersions() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/orchestration/airflow/service/apiv1/servicepb/environments.pb.go b/orchestration/airflow/service/apiv1/servicepb/environments.pb.go index 88decaa63fd6..0d5643a617ef 100644 --- a/orchestration/airflow/service/apiv1/servicepb/environments.pb.go +++ b/orchestration/airflow/service/apiv1/servicepb/environments.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/orchestration/airflow/service/v1/environments.proto package servicepb @@ -583,15 +583,15 @@ type UpdateEnvironmentRequest struct { // "config.softwareConfig.pypiPackages.numpy". The included patch // environment would specify the scikit-learn version as follows: // - // { - // "config":{ - // "softwareConfig":{ - // "pypiPackages":{ - // "scikit-learn":"==0.19.0" - // } - // } - // } - // } + // { + // "config":{ + // "softwareConfig":{ + // "pypiPackages":{ + // "scikit-learn":"==0.19.0" + // } + // } + // } + // } // // Note that in the above example, any existing PyPI packages // other than scikit-learn and numpy will be unaffected. @@ -605,12 +605,12 @@ type UpdateEnvironmentRequest struct { // provide the paths "labels.label1", "labels.label2", and "labels.label3" // and populate the patch environment as follows: // - // { - // "labels":{ - // "label1":"new-label1-value" - // "label2":"new-label2-value" - // } - // } + // { + // "labels":{ + // "label1":"new-label1-value" + // "label2":"new-label2-value" + // } + // } // // Note that in the above example, any existing labels that are not // included in the `updateMask` will be unaffected. @@ -623,91 +623,80 @@ type UpdateEnvironmentRequest struct { // the path "config.softwareConfig.pypiPackages", and // the patch environment would be the following: // - // { - // "config":{ - // "softwareConfig":{ - // "pypiPackages":{ - // "botocore":"==1.7.14" - // } - // } - // } - // } + // { + // "config":{ + // "softwareConfig":{ + // "pypiPackages":{ + // "botocore":"==1.7.14" + // } + // } + // } + // } // // **Note:** Only the following fields can be updated: // // * `config.softwareConfig.pypiPackages` - // - Replace all custom custom PyPI packages. If a replacement - // package map is not included in `environment`, all custom - // PyPI packages are cleared. It is an error to provide both - // this mask and a mask specifying an individual package. - // + // * Replace all custom custom PyPI packages. If a replacement + // package map is not included in `environment`, all custom + // PyPI packages are cleared. It is an error to provide both + // this mask and a mask specifying an individual package. // * `config.softwareConfig.pypiPackages.`packagename - // - Update the custom PyPI package *packagename*, - // preserving other packages. To delete the package, include it in - // `updateMask`, and omit the mapping for it in - // `environment.config.softwareConfig.pypiPackages`. It is an error - // to provide both a mask of this form and the - // `config.softwareConfig.pypiPackages` mask. - // + // * Update the custom PyPI package *packagename*, + // preserving other packages. To delete the package, include it in + // `updateMask`, and omit the mapping for it in + // `environment.config.softwareConfig.pypiPackages`. It is an error + // to provide both a mask of this form and the + // `config.softwareConfig.pypiPackages` mask. // * `labels` - // - Replace all environment labels. If a replacement labels map is not - // included in `environment`, all labels are cleared. It is an error to - // provide both this mask and a mask specifying one or more individual - // labels. - // + // * Replace all environment labels. If a replacement labels map is not + // included in `environment`, all labels are cleared. It is an error to + // provide both this mask and a mask specifying one or more individual + // labels. // * `labels.`labelName - // - Set the label named *labelName*, while preserving other - // labels. To delete the label, include it in `updateMask` and omit its - // mapping in `environment.labels`. It is an error to provide both a - // mask of this form and the `labels` mask. - // + // * Set the label named *labelName*, while preserving other + // labels. To delete the label, include it in `updateMask` and omit its + // mapping in `environment.labels`. It is an error to provide both a + // mask of this form and the `labels` mask. // * `config.nodeCount` - // - Horizontally scale the number of nodes in the environment. An integer - // greater than or equal to 3 must be provided in the `config.nodeCount` - // field. Supported for Cloud Composer environments in versions - // composer-1.*.*-airflow-*.*.*. - // + // * Horizontally scale the number of nodes in the environment. An integer + // greater than or equal to 3 must be provided in the `config.nodeCount` + // field. Supported for Cloud Composer environments in versions + // composer-1.*.*-airflow-*.*.*. // * `config.webServerNetworkAccessControl` - // - Replace the environment's current `WebServerNetworkAccessControl`. - // + // * Replace the environment's current `WebServerNetworkAccessControl`. // * `config.softwareConfig.airflowConfigOverrides` - // - Replace all Apache Airflow config overrides. If a replacement config - // overrides map is not included in `environment`, all config overrides - // are cleared. - // It is an error to provide both this mask and a mask specifying one or - // more individual config overrides. - // + // * Replace all Apache Airflow config overrides. If a replacement config + // overrides map is not included in `environment`, all config overrides + // are cleared. + // It is an error to provide both this mask and a mask specifying one or + // more individual config overrides. // * `config.softwareConfig.airflowConfigOverrides.`section-name - // - Override the Apache Airflow config property *name* in the - // section named *section*, preserving other properties. To - // delete the property override, include it in `updateMask` and omit its - // mapping in - // `environment.config.softwareConfig.airflowConfigOverrides`. - // It is an error to provide both a mask of this form and the - // `config.softwareConfig.airflowConfigOverrides` mask. - // + // * Override the Apache Airflow config property *name* in the + // section named *section*, preserving other properties. To + // delete the property override, include it in `updateMask` and omit its + // mapping in + // `environment.config.softwareConfig.airflowConfigOverrides`. + // It is an error to provide both a mask of this form and the + // `config.softwareConfig.airflowConfigOverrides` mask. // * `config.softwareConfig.envVariables` - // - Replace all environment variables. If a replacement environment - // variable map is not included in `environment`, all custom environment - // variables are cleared. - // + // * Replace all environment variables. If a replacement environment + // variable map is not included in `environment`, all custom environment + // variables are cleared. // * `config.softwareConfig.schedulerCount` - // - Horizontally scale the number of schedulers in Airflow. A positive - // integer not greater than the number of nodes must be provided in the - // `config.softwareConfig.schedulerCount` field. Supported for Cloud - // Composer environments in versions composer-1.*.*-airflow-2.*.*. - // + // * Horizontally scale the number of schedulers in Airflow. A positive + // integer not greater than the number of nodes must be provided in the + // `config.softwareConfig.schedulerCount` field. Supported for Cloud + // Composer environments in versions composer-1.*.*-airflow-2.*.*. // * `config.databaseConfig.machineType` - // - Cloud SQL machine type used by Airflow database. - // It has to be one of: db-n1-standard-2, db-n1-standard-4, - // db-n1-standard-8 or db-n1-standard-16. Supported for Cloud Composer - // environments in versions composer-1.*.*-airflow-*.*.*. - // + // * Cloud SQL machine type used by Airflow database. + // It has to be one of: db-n1-standard-2, db-n1-standard-4, + // db-n1-standard-8 or db-n1-standard-16. Supported for Cloud Composer + // environments in versions composer-1.*.*-airflow-*.*.*. // * `config.webServerConfig.machineType` - // - Machine type on which Airflow web server is running. - // It has to be one of: composer-n1-webserver-2, composer-n1-webserver-4 - // or composer-n1-webserver-8. Supported for Cloud Composer environments - // in versions composer-1.*.*-airflow-*.*.*. + // * Machine type on which Airflow web server is running. + // It has to be one of: composer-n1-webserver-2, composer-n1-webserver-4 + // or composer-n1-webserver-8. Supported for Cloud Composer environments + // in versions composer-1.*.*-airflow-*.*.*. UpdateMask *fieldmaskpb.FieldMask `protobuf:"bytes,3,opt,name=update_mask,json=updateMask,proto3" json:"update_mask,omitempty"` } @@ -1725,14 +1714,12 @@ type IPAllocationPolicy struct { // Configuration of allocating IP addresses for pods in the GKE cluster. // // Types that are assignable to ClusterIpAllocation: - // // *IPAllocationPolicy_ClusterSecondaryRangeName // *IPAllocationPolicy_ClusterIpv4CidrBlock ClusterIpAllocation isIPAllocationPolicy_ClusterIpAllocation `protobuf_oneof:"cluster_ip_allocation"` // Configuration of allocating IP addresses for services in the GKE cluster. // // Types that are assignable to ServicesIpAllocation: - // // *IPAllocationPolicy_ServicesSecondaryRangeName // *IPAllocationPolicy_ServicesIpv4CidrBlock ServicesIpAllocation isIPAllocationPolicy_ServicesIpAllocation `protobuf_oneof:"services_ip_allocation"` @@ -2857,8 +2844,7 @@ type WebServerNetworkAccessControl_AllowedIpRange struct { // IP address or range, defined using CIDR notation, of requests that this // rule applies to. // Examples: `192.168.1.1` or `192.168.0.0/16` or `2001:db8::/32` - // - // or `2001:0db8:0000:0042:0000:8a2e:0370:7334`. + // or `2001:0db8:0000:0042:0000:8a2e:0370:7334`. // // IP range prefixes should be properly truncated. For example, // `1.2.3.4/24` should be truncated to `1.2.3.0/24`. Similarly, for IPv6, diff --git a/orchestration/airflow/service/apiv1/servicepb/image_versions.pb.go b/orchestration/airflow/service/apiv1/servicepb/image_versions.pb.go index f9b78c163515..ea6b1f417e2e 100644 --- a/orchestration/airflow/service/apiv1/servicepb/image_versions.pb.go +++ b/orchestration/airflow/service/apiv1/servicepb/image_versions.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/orchestration/airflow/service/v1/image_versions.proto package servicepb diff --git a/orchestration/airflow/service/apiv1/servicepb/operations.pb.go b/orchestration/airflow/service/apiv1/servicepb/operations.pb.go index 957f121bfa19..3a10c209e007 100644 --- a/orchestration/airflow/service/apiv1/servicepb/operations.pb.go +++ b/orchestration/airflow/service/apiv1/servicepb/operations.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/orchestration/airflow/service/v1/operations.proto package servicepb diff --git a/orgpolicy/apiv2/doc.go b/orgpolicy/apiv2/doc.go index d3044cdb8bf5..9d7c45aaabd6 100644 --- a/orgpolicy/apiv2/doc.go +++ b/orgpolicy/apiv2/doc.go @@ -87,6 +87,8 @@ package orgpolicy // import "cloud.google.com/go/orgpolicy/apiv2" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -175,3 +177,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/orgpolicy/apiv2/gapic_metadata.json b/orgpolicy/apiv2/gapic_metadata.json index c07306a370e5..10a84e212d46 100644 --- a/orgpolicy/apiv2/gapic_metadata.json +++ b/orgpolicy/apiv2/gapic_metadata.json @@ -46,6 +46,46 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "CreatePolicy": { + "methods": [ + "CreatePolicy" + ] + }, + "DeletePolicy": { + "methods": [ + "DeletePolicy" + ] + }, + "GetEffectivePolicy": { + "methods": [ + "GetEffectivePolicy" + ] + }, + "GetPolicy": { + "methods": [ + "GetPolicy" + ] + }, + "ListConstraints": { + "methods": [ + "ListConstraints" + ] + }, + "ListPolicies": { + "methods": [ + "ListPolicies" + ] + }, + "UpdatePolicy": { + "methods": [ + "UpdatePolicy" + ] + } + } } } } diff --git a/orgpolicy/apiv2/org_policy_client.go b/orgpolicy/apiv2/org_policy_client.go index 8bf5a4343f65..b39f36683c59 100644 --- a/orgpolicy/apiv2/org_policy_client.go +++ b/orgpolicy/apiv2/org_policy_client.go @@ -17,21 +17,27 @@ package orgpolicy import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" orgpolicypb "cloud.google.com/go/orgpolicy/apiv2/orgpolicypb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -149,6 +155,88 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + ListConstraints: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + ListPolicies: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + GetPolicy: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + GetEffectivePolicy: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + CreatePolicy: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + UpdatePolicy: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + DeletePolicy: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + } +} + // internalClient is an interface that defines the methods available from Organization Policy API. type internalClient interface { Close() error @@ -377,6 +465,93 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new org policy rest client. +// +// An interface for managing organization policies. +// +// The Cloud Org Policy service provides a simple mechanism for organizations to +// restrict the allowed configurations across their entire Cloud Resource +// hierarchy. +// +// You can use a policy to configure restrictions in Cloud resources. For +// example, you can enforce a policy that restricts which Google +// Cloud Platform APIs can be activated in a certain part of your resource +// hierarchy, or prevents serial port access to VM instances in a particular +// folder. +// +// Policies are inherited down through the resource hierarchy. A policy +// applied to a parent resource automatically applies to all its child resources +// unless overridden with a policy lower in the hierarchy. +// +// A constraint defines an aspect of a resource’s configuration that can be +// controlled by an organization’s policy administrator. Policies are a +// collection of constraints that defines their allowable configuration on a +// particular resource and its child resources. +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://orgpolicy.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://orgpolicy.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://orgpolicy.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) ListConstraints(ctx context.Context, req *orgpolicypb.ListConstraintsRequest, opts ...gax.CallOption) *ConstraintIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -573,6 +748,493 @@ func (c *gRPCClient) DeletePolicy(ctx context.Context, req *orgpolicypb.DeletePo return err } +// ListConstraints lists Constraints that could be applied on the specified resource. +func (c *restClient) ListConstraints(ctx context.Context, req *orgpolicypb.ListConstraintsRequest, opts ...gax.CallOption) *ConstraintIterator { + it := &ConstraintIterator{} + req = proto.Clone(req).(*orgpolicypb.ListConstraintsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*orgpolicypb.Constraint, string, error) { + resp := &orgpolicypb.ListConstraintsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/constraints", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetConstraints(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// ListPolicies retrieves all of the Policies that exist on a particular resource. +func (c *restClient) ListPolicies(ctx context.Context, req *orgpolicypb.ListPoliciesRequest, opts ...gax.CallOption) *PolicyIterator { + it := &PolicyIterator{} + req = proto.Clone(req).(*orgpolicypb.ListPoliciesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*orgpolicypb.Policy, string, error) { + resp := &orgpolicypb.ListPoliciesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/policies", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetPolicies(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetPolicy gets a Policy on a resource. +// +// If no Policy is set on the resource, NOT_FOUND is returned. The +// etag value can be used with UpdatePolicy() to update a +// Policy during read-modify-write. +func (c *restClient) GetPolicy(ctx context.Context, req *orgpolicypb.GetPolicyRequest, opts ...gax.CallOption) (*orgpolicypb.Policy, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetPolicy[0:len((*c.CallOptions).GetPolicy):len((*c.CallOptions).GetPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &orgpolicypb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetEffectivePolicy gets the effective Policy on a resource. This is the result of merging +// Policies in the resource hierarchy and evaluating conditions. The +// returned Policy will not have an etag or condition set because it is +// a computed Policy across multiple resources. +// Subtrees of Resource Manager resource hierarchy with ‘under:’ prefix will +// not be expanded. +func (c *restClient) GetEffectivePolicy(ctx context.Context, req *orgpolicypb.GetEffectivePolicyRequest, opts ...gax.CallOption) (*orgpolicypb.Policy, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:getEffectivePolicy", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetEffectivePolicy[0:len((*c.CallOptions).GetEffectivePolicy):len((*c.CallOptions).GetEffectivePolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &orgpolicypb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreatePolicy creates a Policy. +// +// Returns a google.rpc.Status with google.rpc.Code.NOT_FOUND if the +// constraint does not exist. +// Returns a google.rpc.Status with google.rpc.Code.ALREADY_EXISTS if the +// policy already exists on the given Cloud resource. +func (c *restClient) CreatePolicy(ctx context.Context, req *orgpolicypb.CreatePolicyRequest, opts ...gax.CallOption) (*orgpolicypb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetPolicy() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/policies", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreatePolicy[0:len((*c.CallOptions).CreatePolicy):len((*c.CallOptions).CreatePolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &orgpolicypb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdatePolicy updates a Policy. +// +// Returns a google.rpc.Status with google.rpc.Code.NOT_FOUND if the +// constraint or the policy do not exist. +// Returns a google.rpc.Status with google.rpc.Code.ABORTED if the etag +// supplied in the request does not match the persisted etag of the policy +// +// Note: the supplied policy will perform a full overwrite of all +// fields. +func (c *restClient) UpdatePolicy(ctx context.Context, req *orgpolicypb.UpdatePolicyRequest, opts ...gax.CallOption) (*orgpolicypb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetPolicy() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetPolicy().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "policy.name", url.QueryEscape(req.GetPolicy().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdatePolicy[0:len((*c.CallOptions).UpdatePolicy):len((*c.CallOptions).UpdatePolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &orgpolicypb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeletePolicy deletes a Policy. +// +// Returns a google.rpc.Status with google.rpc.Code.NOT_FOUND if the +// constraint or Org Policy does not exist. +func (c *restClient) DeletePolicy(ctx context.Context, req *orgpolicypb.DeletePolicyRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + // ConstraintIterator manages a stream of *orgpolicypb.Constraint. type ConstraintIterator struct { items []*orgpolicypb.Constraint diff --git a/orgpolicy/apiv2/org_policy_client_example_test.go b/orgpolicy/apiv2/org_policy_client_example_test.go index 280fa28f9fed..85c11fc9ac21 100644 --- a/orgpolicy/apiv2/org_policy_client_example_test.go +++ b/orgpolicy/apiv2/org_policy_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := orgpolicy.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_ListConstraints() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/orgpolicy/apiv2/orgpolicypb/constraint.pb.go b/orgpolicy/apiv2/orgpolicypb/constraint.pb.go index c9bbfb23f1e7..96b199824a24 100644 --- a/orgpolicy/apiv2/orgpolicypb/constraint.pb.go +++ b/orgpolicy/apiv2/orgpolicypb/constraint.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/orgpolicy/v2/constraint.proto package orgpolicypb @@ -138,7 +138,6 @@ type Constraint struct { // Immutable after creation. // // Types that are assignable to ConstraintType: - // // *Constraint_ListConstraint_ // *Constraint_BooleanConstraint_ ConstraintType isConstraint_ConstraintType `protobuf_oneof:"constraint_type"` diff --git a/orgpolicy/apiv2/orgpolicypb/orgpolicy.pb.go b/orgpolicy/apiv2/orgpolicypb/orgpolicy.pb.go index 27e165afdfef..2d4d455b722f 100644 --- a/orgpolicy/apiv2/orgpolicypb/orgpolicy.pb.go +++ b/orgpolicy/apiv2/orgpolicypb/orgpolicy.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/orgpolicy/v2/orgpolicy.proto package orgpolicypb @@ -848,7 +848,6 @@ type PolicySpec_PolicyRule struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Kind: - // // *PolicySpec_PolicyRule_Values // *PolicySpec_PolicyRule_AllowAll // *PolicySpec_PolicyRule_DenyAll diff --git a/osconfig/agentendpoint/apiv1/agent_endpoint_client.go b/osconfig/agentendpoint/apiv1/agent_endpoint_client.go index eefee67cf588..79c24a24ac3b 100644 --- a/osconfig/agentendpoint/apiv1/agent_endpoint_client.go +++ b/osconfig/agentendpoint/apiv1/agent_endpoint_client.go @@ -18,17 +18,24 @@ package agentendpoint import ( "context" + "fmt" + "io/ioutil" "math" + "net/http" + "net/url" "time" agentendpointpb "cloud.google.com/go/osconfig/agentendpoint/apiv1/agentendpointpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" ) var newClientHook clientHook @@ -130,6 +137,75 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + ReceiveTaskNotification: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + 499, + http.StatusConflict, + http.StatusInternalServerError, + http.StatusServiceUnavailable) + }), + }, + StartNextTask: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ReportTaskProgress: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ReportTaskComplete: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + RegisterAgent: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ReportInventory: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + } +} + // internalClient is an interface that defines the methods available from OS Config API. type internalClient interface { Close() error @@ -290,6 +366,74 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new agent endpoint service rest client. +// +// OS Config agent endpoint API. +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://osconfig.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://osconfig.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://osconfig.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) ReceiveTaskNotification(ctx context.Context, req *agentendpointpb.ReceiveTaskNotificationRequest, opts ...gax.CallOption) (agentendpointpb.AgentEndpointService_ReceiveTaskNotificationClient, error) { ctx = insertMetadata(ctx, c.xGoogMetadata) var resp agentendpointpb.AgentEndpointService_ReceiveTaskNotificationClient @@ -403,3 +547,446 @@ func (c *gRPCClient) ReportInventory(ctx context.Context, req *agentendpointpb.R } return resp, nil } + +// ReceiveTaskNotification stream established by client to receive Task notifications. +func (c *restClient) ReceiveTaskNotification(ctx context.Context, req *agentendpointpb.ReceiveTaskNotificationRequest, opts ...gax.CallOption) (agentendpointpb.AgentEndpointService_ReceiveTaskNotificationClient, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("agentVersion", fmt.Sprintf("%v", req.GetAgentVersion())) + params.Add("instanceIdToken", fmt.Sprintf("%v", req.GetInstanceIdToken())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + var streamClient *receiveTaskNotificationRESTClient + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + streamClient = &receiveTaskNotificationRESTClient{ + ctx: ctx, + md: metadata.MD(httpRsp.Header), + stream: gax.NewProtoJSONStreamReader(httpRsp.Body, (&agentendpointpb.ReceiveTaskNotificationResponse{}).ProtoReflect().Type()), + } + return nil + }, opts...) + + return streamClient, e +} + +// receiveTaskNotificationRESTClient is the stream client used to consume the server stream created by +// the REST implementation of ReceiveTaskNotification. +type receiveTaskNotificationRESTClient struct { + ctx context.Context + md metadata.MD + stream *gax.ProtoJSONStream +} + +func (c *receiveTaskNotificationRESTClient) Recv() (*agentendpointpb.ReceiveTaskNotificationResponse, error) { + if err := c.ctx.Err(); err != nil { + defer c.stream.Close() + return nil, err + } + msg, err := c.stream.Recv() + if err != nil { + defer c.stream.Close() + return nil, err + } + res := msg.(*agentendpointpb.ReceiveTaskNotificationResponse) + return res, nil +} + +func (c *receiveTaskNotificationRESTClient) Header() (metadata.MD, error) { + return c.md, nil +} + +func (c *receiveTaskNotificationRESTClient) Trailer() metadata.MD { + return c.md +} + +func (c *receiveTaskNotificationRESTClient) CloseSend() error { + // This is a no-op to fulfill the interface. + return fmt.Errorf("this method is not implemented for a server-stream") +} + +func (c *receiveTaskNotificationRESTClient) Context() context.Context { + return c.ctx +} + +func (c *receiveTaskNotificationRESTClient) SendMsg(m interface{}) error { + // This is a no-op to fulfill the interface. + return fmt.Errorf("this method is not implemented for a server-stream") +} + +func (c *receiveTaskNotificationRESTClient) RecvMsg(m interface{}) error { + // This is a no-op to fulfill the interface. + return fmt.Errorf("this method is not implemented, use Recv") +} + +// StartNextTask signals the start of a task execution and returns the task info. +func (c *restClient) StartNextTask(ctx context.Context, req *agentendpointpb.StartNextTaskRequest, opts ...gax.CallOption) (*agentendpointpb.StartNextTaskResponse, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("instanceIdToken", fmt.Sprintf("%v", req.GetInstanceIdToken())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).StartNextTask[0:len((*c.CallOptions).StartNextTask):len((*c.CallOptions).StartNextTask)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &agentendpointpb.StartNextTaskResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ReportTaskProgress signals an intermediary progress checkpoint in task execution. +func (c *restClient) ReportTaskProgress(ctx context.Context, req *agentendpointpb.ReportTaskProgressRequest, opts ...gax.CallOption) (*agentendpointpb.ReportTaskProgressResponse, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetApplyConfigTaskProgress().GetState() != 0 { + params.Add("applyConfigTaskProgress.state", fmt.Sprintf("%v", req.GetApplyConfigTaskProgress().GetState())) + } + params.Add("applyPatchesTaskProgress.state", fmt.Sprintf("%v", req.GetApplyPatchesTaskProgress().GetState())) + params.Add("execStepTaskProgress.state", fmt.Sprintf("%v", req.GetExecStepTaskProgress().GetState())) + params.Add("instanceIdToken", fmt.Sprintf("%v", req.GetInstanceIdToken())) + params.Add("taskId", fmt.Sprintf("%v", req.GetTaskId())) + params.Add("taskType", fmt.Sprintf("%v", req.GetTaskType())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).ReportTaskProgress[0:len((*c.CallOptions).ReportTaskProgress):len((*c.CallOptions).ReportTaskProgress)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &agentendpointpb.ReportTaskProgressResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ReportTaskComplete signals that the task execution is complete and optionally returns the next +// task. +func (c *restClient) ReportTaskComplete(ctx context.Context, req *agentendpointpb.ReportTaskCompleteRequest, opts ...gax.CallOption) (*agentendpointpb.ReportTaskCompleteResponse, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("applyConfigTaskOutput.state", fmt.Sprintf("%v", req.GetApplyConfigTaskOutput().GetState())) + params.Add("applyPatchesTaskOutput.state", fmt.Sprintf("%v", req.GetApplyPatchesTaskOutput().GetState())) + if req.GetErrorMessage() != "" { + params.Add("errorMessage", fmt.Sprintf("%v", req.GetErrorMessage())) + } + params.Add("execStepTaskOutput.exitCode", fmt.Sprintf("%v", req.GetExecStepTaskOutput().GetExitCode())) + params.Add("execStepTaskOutput.state", fmt.Sprintf("%v", req.GetExecStepTaskOutput().GetState())) + params.Add("instanceIdToken", fmt.Sprintf("%v", req.GetInstanceIdToken())) + params.Add("taskId", fmt.Sprintf("%v", req.GetTaskId())) + params.Add("taskType", fmt.Sprintf("%v", req.GetTaskType())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).ReportTaskComplete[0:len((*c.CallOptions).ReportTaskComplete):len((*c.CallOptions).ReportTaskComplete)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &agentendpointpb.ReportTaskCompleteResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// RegisterAgent registers the agent running on the VM. +func (c *restClient) RegisterAgent(ctx context.Context, req *agentendpointpb.RegisterAgentRequest, opts ...gax.CallOption) (*agentendpointpb.RegisterAgentResponse, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("agentVersion", fmt.Sprintf("%v", req.GetAgentVersion())) + params.Add("instanceIdToken", fmt.Sprintf("%v", req.GetInstanceIdToken())) + if req.GetOsArchitecture() != "" { + params.Add("osArchitecture", fmt.Sprintf("%v", req.GetOsArchitecture())) + } + if req.GetOsLongName() != "" { + params.Add("osLongName", fmt.Sprintf("%v", req.GetOsLongName())) + } + if req.GetOsShortName() != "" { + params.Add("osShortName", fmt.Sprintf("%v", req.GetOsShortName())) + } + if req.GetOsVersion() != "" { + params.Add("osVersion", fmt.Sprintf("%v", req.GetOsVersion())) + } + if items := req.GetSupportedCapabilities(); len(items) > 0 { + for _, item := range items { + params.Add("supportedCapabilities", fmt.Sprintf("%v", item)) + } + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).RegisterAgent[0:len((*c.CallOptions).RegisterAgent):len((*c.CallOptions).RegisterAgent)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &agentendpointpb.RegisterAgentResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ReportInventory reports the VMs current inventory. +func (c *restClient) ReportInventory(ctx context.Context, req *agentendpointpb.ReportInventoryRequest, opts ...gax.CallOption) (*agentendpointpb.ReportInventoryResponse, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("instanceIdToken", fmt.Sprintf("%v", req.GetInstanceIdToken())) + if req.GetInventory().GetOsInfo().GetArchitecture() != "" { + params.Add("inventory.osInfo.architecture", fmt.Sprintf("%v", req.GetInventory().GetOsInfo().GetArchitecture())) + } + if req.GetInventory().GetOsInfo().GetHostname() != "" { + params.Add("inventory.osInfo.hostname", fmt.Sprintf("%v", req.GetInventory().GetOsInfo().GetHostname())) + } + if req.GetInventory().GetOsInfo().GetKernelRelease() != "" { + params.Add("inventory.osInfo.kernelRelease", fmt.Sprintf("%v", req.GetInventory().GetOsInfo().GetKernelRelease())) + } + if req.GetInventory().GetOsInfo().GetKernelVersion() != "" { + params.Add("inventory.osInfo.kernelVersion", fmt.Sprintf("%v", req.GetInventory().GetOsInfo().GetKernelVersion())) + } + if req.GetInventory().GetOsInfo().GetLongName() != "" { + params.Add("inventory.osInfo.longName", fmt.Sprintf("%v", req.GetInventory().GetOsInfo().GetLongName())) + } + if req.GetInventory().GetOsInfo().GetOsconfigAgentVersion() != "" { + params.Add("inventory.osInfo.osconfigAgentVersion", fmt.Sprintf("%v", req.GetInventory().GetOsInfo().GetOsconfigAgentVersion())) + } + if req.GetInventory().GetOsInfo().GetShortName() != "" { + params.Add("inventory.osInfo.shortName", fmt.Sprintf("%v", req.GetInventory().GetOsInfo().GetShortName())) + } + if req.GetInventory().GetOsInfo().GetVersion() != "" { + params.Add("inventory.osInfo.version", fmt.Sprintf("%v", req.GetInventory().GetOsInfo().GetVersion())) + } + params.Add("inventoryChecksum", fmt.Sprintf("%v", req.GetInventoryChecksum())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).ReportInventory[0:len((*c.CallOptions).ReportInventory):len((*c.CallOptions).ReportInventory)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &agentendpointpb.ReportInventoryResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} diff --git a/osconfig/agentendpoint/apiv1/agent_endpoint_client_example_test.go b/osconfig/agentendpoint/apiv1/agent_endpoint_client_example_test.go index b3c7f6c62c73..82d1f7c7c3db 100644 --- a/osconfig/agentendpoint/apiv1/agent_endpoint_client_example_test.go +++ b/osconfig/agentendpoint/apiv1/agent_endpoint_client_example_test.go @@ -40,6 +40,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := agentendpoint.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_StartNextTask() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/osconfig/agentendpoint/apiv1/agentendpointpb/agentendpoint.pb.go b/osconfig/agentendpoint/apiv1/agentendpointpb/agentendpoint.pb.go index d9742412bb04..eb8aa561eab6 100644 --- a/osconfig/agentendpoint/apiv1/agentendpointpb/agentendpoint.pb.go +++ b/osconfig/agentendpoint/apiv1/agentendpointpb/agentendpoint.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/osconfig/agentendpoint/v1/agentendpoint.proto package agentendpointpb @@ -264,7 +264,6 @@ type ReportTaskProgressRequest struct { // Intermediate progress of the current task. // // Types that are assignable to Progress: - // // *ReportTaskProgressRequest_ApplyPatchesTaskProgress // *ReportTaskProgressRequest_ExecStepTaskProgress // *ReportTaskProgressRequest_ApplyConfigTaskProgress @@ -451,7 +450,6 @@ type ReportTaskCompleteRequest struct { // Final output details of the current task. // // Types that are assignable to Output: - // // *ReportTaskCompleteRequest_ApplyPatchesTaskOutput // *ReportTaskCompleteRequest_ExecStepTaskOutput // *ReportTaskCompleteRequest_ApplyConfigTaskOutput diff --git a/osconfig/agentendpoint/apiv1/agentendpointpb/config_common.pb.go b/osconfig/agentendpoint/apiv1/agentendpointpb/config_common.pb.go index 3eaac56d5325..41159cfdb098 100644 --- a/osconfig/agentendpoint/apiv1/agentendpointpb/config_common.pb.go +++ b/osconfig/agentendpoint/apiv1/agentendpointpb/config_common.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/osconfig/agentendpoint/v1/config_common.proto package agentendpointpb @@ -302,7 +302,6 @@ type OSPolicyResourceCompliance struct { // Resource specific output. // // Types that are assignable to Output: - // // *OSPolicyResourceCompliance_ExecResourceOutput_ Output isOSPolicyResourceCompliance_Output `protobuf_oneof:"output"` } diff --git a/osconfig/agentendpoint/apiv1/agentendpointpb/inventory.pb.go b/osconfig/agentendpoint/apiv1/agentendpointpb/inventory.pb.go index dd0d748b8446..18818de92368 100644 --- a/osconfig/agentendpoint/apiv1/agentendpointpb/inventory.pb.go +++ b/osconfig/agentendpoint/apiv1/agentendpointpb/inventory.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/osconfig/agentendpoint/v1/inventory.proto package agentendpointpb @@ -229,7 +229,6 @@ type Inventory_SoftwarePackage struct { // Information about the different types of software packages. // // Types that are assignable to Details: - // // *Inventory_SoftwarePackage_YumPackage // *Inventory_SoftwarePackage_AptPackage // *Inventory_SoftwarePackage_ZypperPackage @@ -371,9 +370,8 @@ type Inventory_SoftwarePackage_ZypperPackage struct { type Inventory_SoftwarePackage_GoogetPackage struct { // Details of a Googet package. - // - // For details about the googet package manager, see - // https://github.com/google/googet. + // For details about the googet package manager, see + // https://github.com/google/googet. GoogetPackage *Inventory_VersionedPackage `protobuf:"bytes,4,opt,name=googet_package,json=googetPackage,proto3,oneof"` } diff --git a/osconfig/agentendpoint/apiv1/agentendpointpb/os_policy.pb.go b/osconfig/agentendpoint/apiv1/agentendpointpb/os_policy.pb.go index 6e25e6ca4793..f44a1bc35d0e 100644 --- a/osconfig/agentendpoint/apiv1/agentendpointpb/os_policy.pb.go +++ b/osconfig/agentendpoint/apiv1/agentendpointpb/os_policy.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/osconfig/agentendpoint/v1/os_policy.proto package agentendpointpb @@ -380,7 +380,6 @@ type OSPolicy_Resource struct { // Resource type. // // Types that are assignable to ResourceType: - // // *OSPolicy_Resource_Pkg // *OSPolicy_Resource_Repository // *OSPolicy_Resource_Exec @@ -503,7 +502,6 @@ type OSPolicy_Resource_File struct { // A specific type of file. // // Types that are assignable to Type: - // // *OSPolicy_Resource_File_Remote_ // *OSPolicy_Resource_File_Gcs_ // *OSPolicy_Resource_File_LocalPath @@ -620,7 +618,6 @@ type OSPolicy_Resource_PackageResource struct { // A system package. // // Types that are assignable to SystemPackage: - // // *OSPolicy_Resource_PackageResource_Apt // *OSPolicy_Resource_PackageResource_Deb_ // *OSPolicy_Resource_PackageResource_Yum @@ -790,7 +787,6 @@ type OSPolicy_Resource_RepositoryResource struct { // A specific type of repository. // // Types that are assignable to Repository: - // // *OSPolicy_Resource_RepositoryResource_Apt // *OSPolicy_Resource_RepositoryResource_Yum // *OSPolicy_Resource_RepositoryResource_Zypper @@ -973,7 +969,6 @@ type OSPolicy_Resource_FileResource struct { // The source for the contents of the file. // // Types that are assignable to Source: - // // *OSPolicy_Resource_FileResource_File // *OSPolicy_Resource_FileResource_Content Source isOSPolicy_Resource_FileResource_Source `protobuf_oneof:"source"` @@ -1923,7 +1918,6 @@ type OSPolicy_Resource_ExecResource_Exec struct { // What to execute. // // Types that are assignable to Source: - // // *OSPolicy_Resource_ExecResource_Exec_File // *OSPolicy_Resource_ExecResource_Exec_Script Source isOSPolicy_Resource_ExecResource_Exec_Source `protobuf_oneof:"source"` diff --git a/osconfig/agentendpoint/apiv1/agentendpointpb/patch_jobs.pb.go b/osconfig/agentendpoint/apiv1/agentendpointpb/patch_jobs.pb.go index c48560f851d1..d961afce2b38 100644 --- a/osconfig/agentendpoint/apiv1/agentendpointpb/patch_jobs.pb.go +++ b/osconfig/agentendpoint/apiv1/agentendpointpb/patch_jobs.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/osconfig/agentendpoint/v1/patch_jobs.proto package agentendpointpb @@ -922,7 +922,6 @@ type ExecStepConfig struct { // Location of the executable. // // Types that are assignable to Executable: - // // *ExecStepConfig_LocalPath // *ExecStepConfig_GcsObject Executable isExecStepConfig_Executable `protobuf_oneof:"executable"` diff --git a/osconfig/agentendpoint/apiv1/agentendpointpb/tasks.pb.go b/osconfig/agentendpoint/apiv1/agentendpointpb/tasks.pb.go index 6b3ef62889a5..5f11cb3bb989 100644 --- a/osconfig/agentendpoint/apiv1/agentendpointpb/tasks.pb.go +++ b/osconfig/agentendpoint/apiv1/agentendpointpb/tasks.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/osconfig/agentendpoint/v1/tasks.proto package agentendpointpb @@ -503,7 +503,6 @@ type Task struct { // Specific details about the current task to perform. // // Types that are assignable to TaskDetails: - // // *Task_ApplyPatchesTask // *Task_ExecStepTask // *Task_ApplyConfigTask diff --git a/osconfig/agentendpoint/apiv1/doc.go b/osconfig/agentendpoint/apiv1/doc.go index 16ba892f633d..5581738ecf06 100644 --- a/osconfig/agentendpoint/apiv1/doc.go +++ b/osconfig/agentendpoint/apiv1/doc.go @@ -58,6 +58,8 @@ package agentendpoint // import "cloud.google.com/go/osconfig/agentendpoint/apiv import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -146,3 +148,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/osconfig/agentendpoint/apiv1/gapic_metadata.json b/osconfig/agentendpoint/apiv1/gapic_metadata.json index a1becd796201..63db8300d212 100644 --- a/osconfig/agentendpoint/apiv1/gapic_metadata.json +++ b/osconfig/agentendpoint/apiv1/gapic_metadata.json @@ -41,6 +41,41 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "ReceiveTaskNotification": { + "methods": [ + "ReceiveTaskNotification" + ] + }, + "RegisterAgent": { + "methods": [ + "RegisterAgent" + ] + }, + "ReportInventory": { + "methods": [ + "ReportInventory" + ] + }, + "ReportTaskComplete": { + "methods": [ + "ReportTaskComplete" + ] + }, + "ReportTaskProgress": { + "methods": [ + "ReportTaskProgress" + ] + }, + "StartNextTask": { + "methods": [ + "StartNextTask" + ] + } + } } } } diff --git a/osconfig/agentendpoint/apiv1beta/agent_endpoint_client.go b/osconfig/agentendpoint/apiv1beta/agent_endpoint_client.go index e9af0e98c76b..f827f575e5e6 100644 --- a/osconfig/agentendpoint/apiv1beta/agent_endpoint_client.go +++ b/osconfig/agentendpoint/apiv1beta/agent_endpoint_client.go @@ -558,6 +558,7 @@ func (c *restClient) ReceiveTaskNotification(ctx context.Context, req *agentendp baseUrl.Path += fmt.Sprintf("") params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("agentVersion", fmt.Sprintf("%v", req.GetAgentVersion())) params.Add("instanceIdToken", fmt.Sprintf("%v", req.GetInstanceIdToken())) @@ -655,6 +656,7 @@ func (c *restClient) StartNextTask(ctx context.Context, req *agentendpointpb.Sta baseUrl.Path += fmt.Sprintf("") params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("instanceIdToken", fmt.Sprintf("%v", req.GetInstanceIdToken())) baseUrl.RawQuery = params.Encode() @@ -711,6 +713,7 @@ func (c *restClient) ReportTaskProgress(ctx context.Context, req *agentendpointp baseUrl.Path += fmt.Sprintf("") params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("applyPatchesTaskProgress.state", fmt.Sprintf("%v", req.GetApplyPatchesTaskProgress().GetState())) params.Add("execStepTaskProgress.state", fmt.Sprintf("%v", req.GetExecStepTaskProgress().GetState())) params.Add("instanceIdToken", fmt.Sprintf("%v", req.GetInstanceIdToken())) @@ -772,6 +775,7 @@ func (c *restClient) ReportTaskComplete(ctx context.Context, req *agentendpointp baseUrl.Path += fmt.Sprintf("") params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("applyPatchesTaskOutput.state", fmt.Sprintf("%v", req.GetApplyPatchesTaskOutput().GetState())) if req.GetErrorMessage() != "" { params.Add("errorMessage", fmt.Sprintf("%v", req.GetErrorMessage())) @@ -837,6 +841,7 @@ func (c *restClient) LookupEffectiveGuestPolicy(ctx context.Context, req *agente baseUrl.Path += fmt.Sprintf("") params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("instanceIdToken", fmt.Sprintf("%v", req.GetInstanceIdToken())) if req.GetOsArchitecture() != "" { params.Add("osArchitecture", fmt.Sprintf("%v", req.GetOsArchitecture())) @@ -902,6 +907,7 @@ func (c *restClient) RegisterAgent(ctx context.Context, req *agentendpointpb.Reg baseUrl.Path += fmt.Sprintf("") params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("agentVersion", fmt.Sprintf("%v", req.GetAgentVersion())) params.Add("instanceIdToken", fmt.Sprintf("%v", req.GetInstanceIdToken())) if req.GetOsArchitecture() != "" { @@ -916,8 +922,10 @@ func (c *restClient) RegisterAgent(ctx context.Context, req *agentendpointpb.Reg if req.GetOsVersion() != "" { params.Add("osVersion", fmt.Sprintf("%v", req.GetOsVersion())) } - if req.GetSupportedCapabilities() != nil { - params.Add("supportedCapabilities", fmt.Sprintf("%v", req.GetSupportedCapabilities())) + if items := req.GetSupportedCapabilities(); len(items) > 0 { + for _, item := range items { + params.Add("supportedCapabilities", fmt.Sprintf("%v", item)) + } } baseUrl.RawQuery = params.Encode() diff --git a/osconfig/agentendpoint/apiv1beta/agentendpointpb/agentendpoint.pb.go b/osconfig/agentendpoint/apiv1beta/agentendpointpb/agentendpoint.pb.go index 57c1c19fc395..897b37eb212f 100644 --- a/osconfig/agentendpoint/apiv1beta/agentendpointpb/agentendpoint.pb.go +++ b/osconfig/agentendpoint/apiv1beta/agentendpointpb/agentendpoint.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/osconfig/agentendpoint/v1beta/agentendpoint.proto package agentendpointpb @@ -264,7 +264,6 @@ type ReportTaskProgressRequest struct { // Intermediate progress of the current task. // // Types that are assignable to Progress: - // // *ReportTaskProgressRequest_ApplyPatchesTaskProgress // *ReportTaskProgressRequest_ExecStepTaskProgress Progress isReportTaskProgressRequest_Progress `protobuf_oneof:"progress"` @@ -436,7 +435,6 @@ type ReportTaskCompleteRequest struct { // Final output details of the current task. // // Types that are assignable to Output: - // // *ReportTaskCompleteRequest_ApplyPatchesTaskOutput // *ReportTaskCompleteRequest_ExecStepTaskOutput Output isReportTaskCompleteRequest_Output `protobuf_oneof:"output"` diff --git a/osconfig/agentendpoint/apiv1beta/agentendpointpb/guest_policies.pb.go b/osconfig/agentendpoint/apiv1beta/agentendpointpb/guest_policies.pb.go index 1b0c671629fd..5a4e98957360 100644 --- a/osconfig/agentendpoint/apiv1beta/agentendpointpb/guest_policies.pb.go +++ b/osconfig/agentendpoint/apiv1beta/agentendpointpb/guest_policies.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/osconfig/agentendpoint/v1beta/guest_policies.proto package agentendpointpb @@ -752,7 +752,6 @@ type PackageRepository struct { // A specific type of repository. // // Types that are assignable to Repository: - // // *PackageRepository_Apt // *PackageRepository_Yum // *PackageRepository_Zypper @@ -914,17 +913,12 @@ type SoftwareRecipe struct { // recipe. // // INSTALLED: The software recipe is installed on the instance but won't be - // - // updated to new versions. - // + // updated to new versions. // UPDATED: The software recipe is installed on the instance. The recipe is - // - // updated to a higher version, if a higher version of - // the recipe is assigned to this instance. - // + // updated to a higher version, if a higher version of + // the recipe is assigned to this instance. // REMOVE: Remove is unsupported for software recipes and attempts to - // - // create or update a recipe to the REMOVE state is rejected. + // create or update a recipe to the REMOVE state is rejected. DesiredState DesiredState `protobuf:"varint,6,opt,name=desired_state,json=desiredState,proto3,enum=google.cloud.osconfig.agentendpoint.v1beta.DesiredState" json:"desired_state,omitempty"` } @@ -1165,7 +1159,6 @@ type SoftwareRecipe_Artifact struct { // A specific type of artifact. // // Types that are assignable to Artifact: - // // *SoftwareRecipe_Artifact_Remote_ // *SoftwareRecipe_Artifact_Gcs_ Artifact isSoftwareRecipe_Artifact_Artifact `protobuf_oneof:"artifact"` @@ -1173,9 +1166,7 @@ type SoftwareRecipe_Artifact struct { // based on the artifact type: // // Remote: A checksum must be specified, and only protocols with - // - // transport-layer security are permitted. - // + // transport-layer security are permitted. // GCS: An object generation number must be specified. AllowInsecure bool `protobuf:"varint,4,opt,name=allow_insecure,json=allowInsecure,proto3" json:"allow_insecure,omitempty"` } @@ -1274,7 +1265,6 @@ type SoftwareRecipe_Step struct { // A specific type of step. // // Types that are assignable to Step: - // // *SoftwareRecipe_Step_FileCopy // *SoftwareRecipe_Step_ArchiveExtraction // *SoftwareRecipe_Step_MsiInstallation @@ -1901,7 +1891,6 @@ type SoftwareRecipe_Step_ExecFile struct { // Location of the file to execute. // // Types that are assignable to LocationType: - // // *SoftwareRecipe_Step_ExecFile_ArtifactId // *SoftwareRecipe_Step_ExecFile_LocalPath LocationType isSoftwareRecipe_Step_ExecFile_LocationType `protobuf_oneof:"location_type"` diff --git a/osconfig/agentendpoint/apiv1beta/agentendpointpb/patch_jobs.pb.go b/osconfig/agentendpoint/apiv1beta/agentendpointpb/patch_jobs.pb.go index 31f71922cb04..36fcda54cbd8 100644 --- a/osconfig/agentendpoint/apiv1beta/agentendpointpb/patch_jobs.pb.go +++ b/osconfig/agentendpoint/apiv1beta/agentendpointpb/patch_jobs.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/osconfig/agentendpoint/v1beta/patch_jobs.proto package agentendpointpb @@ -922,7 +922,6 @@ type ExecStepConfig struct { // Location of the executable. // // Types that are assignable to Executable: - // // *ExecStepConfig_LocalPath // *ExecStepConfig_GcsObject Executable isExecStepConfig_Executable `protobuf_oneof:"executable"` diff --git a/osconfig/agentendpoint/apiv1beta/agentendpointpb/tasks.pb.go b/osconfig/agentendpoint/apiv1beta/agentendpointpb/tasks.pb.go index 00072e812c9f..9ec0d7ecb525 100644 --- a/osconfig/agentendpoint/apiv1beta/agentendpointpb/tasks.pb.go +++ b/osconfig/agentendpoint/apiv1beta/agentendpointpb/tasks.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/osconfig/agentendpoint/v1beta/tasks.proto package agentendpointpb @@ -388,7 +388,6 @@ type Task struct { // Specific details about the current task to perform. // // Types that are assignable to TaskDetails: - // // *Task_ApplyPatchesTask // *Task_ExecStepTask TaskDetails isTask_TaskDetails `protobuf_oneof:"task_details"` diff --git a/osconfig/apiv1/doc.go b/osconfig/apiv1/doc.go index 3fe6581daf4f..52cd28f6f153 100644 --- a/osconfig/apiv1/doc.go +++ b/osconfig/apiv1/doc.go @@ -81,6 +81,8 @@ package osconfig // import "cloud.google.com/go/osconfig/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -169,3 +171,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/osconfig/apiv1/gapic_metadata.json b/osconfig/apiv1/gapic_metadata.json index 06c01ce50ebc..4fedf2872790 100644 --- a/osconfig/apiv1/gapic_metadata.json +++ b/osconfig/apiv1/gapic_metadata.json @@ -71,6 +71,71 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "CancelPatchJob": { + "methods": [ + "CancelPatchJob" + ] + }, + "CreatePatchDeployment": { + "methods": [ + "CreatePatchDeployment" + ] + }, + "DeletePatchDeployment": { + "methods": [ + "DeletePatchDeployment" + ] + }, + "ExecutePatchJob": { + "methods": [ + "ExecutePatchJob" + ] + }, + "GetPatchDeployment": { + "methods": [ + "GetPatchDeployment" + ] + }, + "GetPatchJob": { + "methods": [ + "GetPatchJob" + ] + }, + "ListPatchDeployments": { + "methods": [ + "ListPatchDeployments" + ] + }, + "ListPatchJobInstanceDetails": { + "methods": [ + "ListPatchJobInstanceDetails" + ] + }, + "ListPatchJobs": { + "methods": [ + "ListPatchJobs" + ] + }, + "PausePatchDeployment": { + "methods": [ + "PausePatchDeployment" + ] + }, + "ResumePatchDeployment": { + "methods": [ + "ResumePatchDeployment" + ] + }, + "UpdatePatchDeployment": { + "methods": [ + "UpdatePatchDeployment" + ] + } + } } } }, @@ -140,6 +205,71 @@ ] } } + }, + "rest": { + "libraryClient": "OsConfigZonalClient", + "rpcs": { + "CreateOSPolicyAssignment": { + "methods": [ + "CreateOSPolicyAssignment" + ] + }, + "DeleteOSPolicyAssignment": { + "methods": [ + "DeleteOSPolicyAssignment" + ] + }, + "GetInventory": { + "methods": [ + "GetInventory" + ] + }, + "GetOSPolicyAssignment": { + "methods": [ + "GetOSPolicyAssignment" + ] + }, + "GetOSPolicyAssignmentReport": { + "methods": [ + "GetOSPolicyAssignmentReport" + ] + }, + "GetVulnerabilityReport": { + "methods": [ + "GetVulnerabilityReport" + ] + }, + "ListInventories": { + "methods": [ + "ListInventories" + ] + }, + "ListOSPolicyAssignmentReports": { + "methods": [ + "ListOSPolicyAssignmentReports" + ] + }, + "ListOSPolicyAssignmentRevisions": { + "methods": [ + "ListOSPolicyAssignmentRevisions" + ] + }, + "ListOSPolicyAssignments": { + "methods": [ + "ListOSPolicyAssignments" + ] + }, + "ListVulnerabilityReports": { + "methods": [ + "ListVulnerabilityReports" + ] + }, + "UpdateOSPolicyAssignment": { + "methods": [ + "UpdateOSPolicyAssignment" + ] + } + } } } } diff --git a/osconfig/apiv1/os_config_client.go b/osconfig/apiv1/os_config_client.go index 220e376d3056..639f1cfc958b 100644 --- a/osconfig/apiv1/os_config_client.go +++ b/osconfig/apiv1/os_config_client.go @@ -17,21 +17,27 @@ package osconfig import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" osconfigpb "cloud.google.com/go/osconfig/apiv1/osconfigpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -202,6 +208,131 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + ExecutePatchJob: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetPatchJob: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CancelPatchJob: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListPatchJobs: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListPatchJobInstanceDetails: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreatePatchDeployment: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetPatchDeployment: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListPatchDeployments: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeletePatchDeployment: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UpdatePatchDeployment: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + PausePatchDeployment: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ResumePatchDeployment: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + } +} + // internalClient is an interface that defines the methods available from OS Config API. type internalClient interface { Close() error @@ -407,6 +538,77 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new os config service rest client. +// +// # OS Config API +// +// The OS Config service is a server-side component that you can use to +// manage package installations and patch jobs for virtual machine instances. +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://osconfig.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://osconfig.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://osconfig.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) ExecutePatchJob(ctx context.Context, req *osconfigpb.ExecutePatchJobRequest, opts ...gax.CallOption) (*osconfigpb.PatchJob, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) @@ -736,6 +938,830 @@ func (c *gRPCClient) ResumePatchDeployment(ctx context.Context, req *osconfigpb. return resp, nil } +// ExecutePatchJob patch VM instances by creating and running a patch job. +func (c *restClient) ExecutePatchJob(ctx context.Context, req *osconfigpb.ExecutePatchJobRequest, opts ...gax.CallOption) (*osconfigpb.PatchJob, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/patchJobs:execute", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).ExecutePatchJob[0:len((*c.CallOptions).ExecutePatchJob):len((*c.CallOptions).ExecutePatchJob)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &osconfigpb.PatchJob{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetPatchJob get the patch job. This can be used to track the progress of an +// ongoing patch job or review the details of completed jobs. +func (c *restClient) GetPatchJob(ctx context.Context, req *osconfigpb.GetPatchJobRequest, opts ...gax.CallOption) (*osconfigpb.PatchJob, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetPatchJob[0:len((*c.CallOptions).GetPatchJob):len((*c.CallOptions).GetPatchJob)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &osconfigpb.PatchJob{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CancelPatchJob cancel a patch job. The patch job must be active. Canceled patch jobs +// cannot be restarted. +func (c *restClient) CancelPatchJob(ctx context.Context, req *osconfigpb.CancelPatchJobRequest, opts ...gax.CallOption) (*osconfigpb.PatchJob, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CancelPatchJob[0:len((*c.CallOptions).CancelPatchJob):len((*c.CallOptions).CancelPatchJob)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &osconfigpb.PatchJob{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListPatchJobs get a list of patch jobs. +func (c *restClient) ListPatchJobs(ctx context.Context, req *osconfigpb.ListPatchJobsRequest, opts ...gax.CallOption) *PatchJobIterator { + it := &PatchJobIterator{} + req = proto.Clone(req).(*osconfigpb.ListPatchJobsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*osconfigpb.PatchJob, string, error) { + resp := &osconfigpb.ListPatchJobsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/patchJobs", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetPatchJobs(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// ListPatchJobInstanceDetails get a list of instance details for a given patch job. +func (c *restClient) ListPatchJobInstanceDetails(ctx context.Context, req *osconfigpb.ListPatchJobInstanceDetailsRequest, opts ...gax.CallOption) *PatchJobInstanceDetailsIterator { + it := &PatchJobInstanceDetailsIterator{} + req = proto.Clone(req).(*osconfigpb.ListPatchJobInstanceDetailsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*osconfigpb.PatchJobInstanceDetails, string, error) { + resp := &osconfigpb.ListPatchJobInstanceDetailsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/instanceDetails", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetPatchJobInstanceDetails(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CreatePatchDeployment create an OS Config patch deployment. +func (c *restClient) CreatePatchDeployment(ctx context.Context, req *osconfigpb.CreatePatchDeploymentRequest, opts ...gax.CallOption) (*osconfigpb.PatchDeployment, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetPatchDeployment() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/patchDeployments", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("patchDeploymentId", fmt.Sprintf("%v", req.GetPatchDeploymentId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreatePatchDeployment[0:len((*c.CallOptions).CreatePatchDeployment):len((*c.CallOptions).CreatePatchDeployment)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &osconfigpb.PatchDeployment{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetPatchDeployment get an OS Config patch deployment. +func (c *restClient) GetPatchDeployment(ctx context.Context, req *osconfigpb.GetPatchDeploymentRequest, opts ...gax.CallOption) (*osconfigpb.PatchDeployment, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetPatchDeployment[0:len((*c.CallOptions).GetPatchDeployment):len((*c.CallOptions).GetPatchDeployment)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &osconfigpb.PatchDeployment{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListPatchDeployments get a page of OS Config patch deployments. +func (c *restClient) ListPatchDeployments(ctx context.Context, req *osconfigpb.ListPatchDeploymentsRequest, opts ...gax.CallOption) *PatchDeploymentIterator { + it := &PatchDeploymentIterator{} + req = proto.Clone(req).(*osconfigpb.ListPatchDeploymentsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*osconfigpb.PatchDeployment, string, error) { + resp := &osconfigpb.ListPatchDeploymentsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/patchDeployments", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetPatchDeployments(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// DeletePatchDeployment delete an OS Config patch deployment. +func (c *restClient) DeletePatchDeployment(ctx context.Context, req *osconfigpb.DeletePatchDeploymentRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// UpdatePatchDeployment update an OS Config patch deployment. +func (c *restClient) UpdatePatchDeployment(ctx context.Context, req *osconfigpb.UpdatePatchDeploymentRequest, opts ...gax.CallOption) (*osconfigpb.PatchDeployment, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetPatchDeployment() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetPatchDeployment().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "patch_deployment.name", url.QueryEscape(req.GetPatchDeployment().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdatePatchDeployment[0:len((*c.CallOptions).UpdatePatchDeployment):len((*c.CallOptions).UpdatePatchDeployment)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &osconfigpb.PatchDeployment{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// PausePatchDeployment change state of patch deployment to “PAUSED”. +// Patch deployment in paused state doesn’t generate patch jobs. +func (c *restClient) PausePatchDeployment(ctx context.Context, req *osconfigpb.PausePatchDeploymentRequest, opts ...gax.CallOption) (*osconfigpb.PatchDeployment, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:pause", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).PausePatchDeployment[0:len((*c.CallOptions).PausePatchDeployment):len((*c.CallOptions).PausePatchDeployment)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &osconfigpb.PatchDeployment{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ResumePatchDeployment change state of patch deployment back to “ACTIVE”. +// Patch deployment in active state continues to generate patch jobs. +func (c *restClient) ResumePatchDeployment(ctx context.Context, req *osconfigpb.ResumePatchDeploymentRequest, opts ...gax.CallOption) (*osconfigpb.PatchDeployment, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:resume", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).ResumePatchDeployment[0:len((*c.CallOptions).ResumePatchDeployment):len((*c.CallOptions).ResumePatchDeployment)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &osconfigpb.PatchDeployment{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + // PatchDeploymentIterator manages a stream of *osconfigpb.PatchDeployment. type PatchDeploymentIterator struct { items []*osconfigpb.PatchDeployment diff --git a/osconfig/apiv1/os_config_client_example_test.go b/osconfig/apiv1/os_config_client_example_test.go index 4d3f381a4f4f..4c272e3d7108 100644 --- a/osconfig/apiv1/os_config_client_example_test.go +++ b/osconfig/apiv1/os_config_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := osconfig.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_ExecutePatchJob() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/osconfig/apiv1/os_config_zonal_client.go b/osconfig/apiv1/os_config_zonal_client.go index e33f8e4ef214..d6d5e2309356 100644 --- a/osconfig/apiv1/os_config_zonal_client.go +++ b/osconfig/apiv1/os_config_zonal_client.go @@ -17,9 +17,12 @@ package osconfig import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,14 +30,17 @@ import ( lroauto "cloud.google.com/go/longrunning/autogen" osconfigpb "cloud.google.com/go/osconfig/apiv1/osconfigpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -205,6 +211,131 @@ func defaultOsConfigZonalCallOptions() *OsConfigZonalCallOptions { } } +func defaultOsConfigZonalRESTCallOptions() *OsConfigZonalCallOptions { + return &OsConfigZonalCallOptions{ + CreateOSPolicyAssignment: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UpdateOSPolicyAssignment: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetOSPolicyAssignment: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListOSPolicyAssignments: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListOSPolicyAssignmentRevisions: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeleteOSPolicyAssignment: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetOSPolicyAssignmentReport: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListOSPolicyAssignmentReports: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetInventory: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListInventories: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetVulnerabilityReport: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListVulnerabilityReports: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + } +} + // internalOsConfigZonalClient is an interface that defines the methods available from OS Config API. type internalOsConfigZonalClient interface { Close() error @@ -485,6 +616,92 @@ func (c *osConfigZonalGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type osConfigZonalRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing OsConfigZonalClient + CallOptions **OsConfigZonalCallOptions +} + +// NewOsConfigZonalRESTClient creates a new os config zonal service rest client. +// +// # Zonal OS Config API +// +// The OS Config service is the server-side component that allows users to +// manage package installations and patch jobs for Compute Engine VM instances. +func NewOsConfigZonalRESTClient(ctx context.Context, opts ...option.ClientOption) (*OsConfigZonalClient, error) { + clientOpts := append(defaultOsConfigZonalRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultOsConfigZonalRESTCallOptions() + c := &osConfigZonalRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &OsConfigZonalClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultOsConfigZonalRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://osconfig.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://osconfig.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://osconfig.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *osConfigZonalRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *osConfigZonalRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *osConfigZonalRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *osConfigZonalGRPCClient) CreateOSPolicyAssignment(ctx context.Context, req *osconfigpb.CreateOSPolicyAssignmentRequest, opts ...gax.CallOption) (*CreateOSPolicyAssignmentOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) @@ -870,108 +1087,1066 @@ func (c *osConfigZonalGRPCClient) ListVulnerabilityReports(ctx context.Context, return it } -// CreateOSPolicyAssignmentOperation manages a long-running operation from CreateOSPolicyAssignment. -type CreateOSPolicyAssignmentOperation struct { - lro *longrunning.Operation -} - -// CreateOSPolicyAssignmentOperation returns a new CreateOSPolicyAssignmentOperation from a given name. -// The name must be that of a previously created CreateOSPolicyAssignmentOperation, possibly from a different process. -func (c *osConfigZonalGRPCClient) CreateOSPolicyAssignmentOperation(name string) *CreateOSPolicyAssignmentOperation { - return &CreateOSPolicyAssignmentOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} - -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// CreateOSPolicyAssignment create an OS policy assignment. // -// See documentation of Poll for error-handling information. -func (op *CreateOSPolicyAssignmentOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*osconfigpb.OSPolicyAssignment, error) { - var resp osconfigpb.OSPolicyAssignment - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { - return nil, err - } - return &resp, nil -} - -// Poll fetches the latest state of the long-running operation. +// This method also creates the first revision of the OS policy assignment. // -// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// This method returns a long running operation (LRO) that contains the +// rollout details. The rollout can be cancelled by cancelling the LRO. // -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *CreateOSPolicyAssignmentOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*osconfigpb.OSPolicyAssignment, error) { - var resp osconfigpb.OSPolicyAssignment - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { +// For more information, see Method: +// projects.locations.osPolicyAssignments.operations.cancel (at https://cloud.google.com/compute/docs/osconfig/rest/v1/projects.locations.osPolicyAssignments.operations/cancel). +func (c *osConfigZonalRESTClient) CreateOSPolicyAssignment(ctx context.Context, req *osconfigpb.CreateOSPolicyAssignmentRequest, opts ...gax.CallOption) (*CreateOSPolicyAssignmentOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetOsPolicyAssignment() + jsonReq, err := m.Marshal(body) + if err != nil { return nil, err } - if !op.Done() { - return nil, nil - } - return &resp, nil -} -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *CreateOSPolicyAssignmentOperation) Metadata() (*osconfigpb.OSPolicyAssignmentOperationMetadata, error) { - var meta osconfigpb.OSPolicyAssignmentOperationMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - return &meta, nil -} + baseUrl.Path += fmt.Sprintf("/v1/%v/osPolicyAssignments", req.GetParent()) -// Done reports whether the long-running operation has completed. -func (op *CreateOSPolicyAssignmentOperation) Done() bool { - return op.lro.Done() -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("osPolicyAssignmentId", fmt.Sprintf("%v", req.GetOsPolicyAssignmentId())) -// 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 *CreateOSPolicyAssignmentOperation) Name() string { - return op.lro.Name() -} + baseUrl.RawQuery = params.Encode() -// DeleteOSPolicyAssignmentOperation manages a long-running operation from DeleteOSPolicyAssignment. -type DeleteOSPolicyAssignmentOperation struct { - lro *longrunning.Operation -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) -// DeleteOSPolicyAssignmentOperation returns a new DeleteOSPolicyAssignmentOperation from a given name. -// The name must be that of a previously created DeleteOSPolicyAssignmentOperation, possibly from a different process. -func (c *osConfigZonalGRPCClient) DeleteOSPolicyAssignmentOperation(name string) *DeleteOSPolicyAssignmentOperation { - return &DeleteOSPolicyAssignmentOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e } -} -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *DeleteOSPolicyAssignmentOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { - return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateOSPolicyAssignmentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil } -// Poll fetches the latest state of the long-running operation. +// UpdateOSPolicyAssignment update an existing OS policy assignment. // -// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// This method creates a new revision of the OS policy assignment. // -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *DeleteOSPolicyAssignmentOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { - return op.lro.Poll(ctx, nil, opts...) -} - +// This method returns a long running operation (LRO) that contains the +// rollout details. The rollout can be cancelled by cancelling the LRO. +// +// For more information, see Method: +// projects.locations.osPolicyAssignments.operations.cancel (at https://cloud.google.com/compute/docs/osconfig/rest/v1/projects.locations.osPolicyAssignments.operations/cancel). +func (c *osConfigZonalRESTClient) UpdateOSPolicyAssignment(ctx context.Context, req *osconfigpb.UpdateOSPolicyAssignmentRequest, opts ...gax.CallOption) (*UpdateOSPolicyAssignmentOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetOsPolicyAssignment() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetOsPolicyAssignment().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "os_policy_assignment.name", url.QueryEscape(req.GetOsPolicyAssignment().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateOSPolicyAssignmentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetOSPolicyAssignment retrieve an existing OS policy assignment. +// +// This method always returns the latest revision. In order to retrieve a +// previous revision of the assignment, also provide the revision ID in the +// name parameter. +func (c *osConfigZonalRESTClient) GetOSPolicyAssignment(ctx context.Context, req *osconfigpb.GetOSPolicyAssignmentRequest, opts ...gax.CallOption) (*osconfigpb.OSPolicyAssignment, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOSPolicyAssignment[0:len((*c.CallOptions).GetOSPolicyAssignment):len((*c.CallOptions).GetOSPolicyAssignment)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &osconfigpb.OSPolicyAssignment{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOSPolicyAssignments list the OS policy assignments under the parent resource. +// +// For each OS policy assignment, the latest revision is returned. +func (c *osConfigZonalRESTClient) ListOSPolicyAssignments(ctx context.Context, req *osconfigpb.ListOSPolicyAssignmentsRequest, opts ...gax.CallOption) *OSPolicyAssignmentIterator { + it := &OSPolicyAssignmentIterator{} + req = proto.Clone(req).(*osconfigpb.ListOSPolicyAssignmentsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*osconfigpb.OSPolicyAssignment, string, error) { + resp := &osconfigpb.ListOSPolicyAssignmentsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/osPolicyAssignments", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOsPolicyAssignments(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// ListOSPolicyAssignmentRevisions list the OS policy assignment revisions for a given OS policy assignment. +func (c *osConfigZonalRESTClient) ListOSPolicyAssignmentRevisions(ctx context.Context, req *osconfigpb.ListOSPolicyAssignmentRevisionsRequest, opts ...gax.CallOption) *OSPolicyAssignmentIterator { + it := &OSPolicyAssignmentIterator{} + req = proto.Clone(req).(*osconfigpb.ListOSPolicyAssignmentRevisionsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*osconfigpb.OSPolicyAssignment, string, error) { + resp := &osconfigpb.ListOSPolicyAssignmentRevisionsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:listRevisions", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOsPolicyAssignments(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// DeleteOSPolicyAssignment delete the OS policy assignment. +// +// This method creates a new revision of the OS policy assignment. +// +// This method returns a long running operation (LRO) that contains the +// rollout details. The rollout can be cancelled by cancelling the LRO. +// +// If the LRO completes and is not cancelled, all revisions associated with +// the OS policy assignment are deleted. +// +// For more information, see Method: +// projects.locations.osPolicyAssignments.operations.cancel (at https://cloud.google.com/compute/docs/osconfig/rest/v1/projects.locations.osPolicyAssignments.operations/cancel). +func (c *osConfigZonalRESTClient) DeleteOSPolicyAssignment(ctx context.Context, req *osconfigpb.DeleteOSPolicyAssignmentRequest, opts ...gax.CallOption) (*DeleteOSPolicyAssignmentOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteOSPolicyAssignmentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetOSPolicyAssignmentReport get the OS policy asssignment report for the specified Compute Engine VM +// instance. +func (c *osConfigZonalRESTClient) GetOSPolicyAssignmentReport(ctx context.Context, req *osconfigpb.GetOSPolicyAssignmentReportRequest, opts ...gax.CallOption) (*osconfigpb.OSPolicyAssignmentReport, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOSPolicyAssignmentReport[0:len((*c.CallOptions).GetOSPolicyAssignmentReport):len((*c.CallOptions).GetOSPolicyAssignmentReport)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &osconfigpb.OSPolicyAssignmentReport{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOSPolicyAssignmentReports list OS policy asssignment reports for all Compute Engine VM instances in +// the specified zone. +func (c *osConfigZonalRESTClient) ListOSPolicyAssignmentReports(ctx context.Context, req *osconfigpb.ListOSPolicyAssignmentReportsRequest, opts ...gax.CallOption) *OSPolicyAssignmentReportIterator { + it := &OSPolicyAssignmentReportIterator{} + req = proto.Clone(req).(*osconfigpb.ListOSPolicyAssignmentReportsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*osconfigpb.OSPolicyAssignmentReport, string, error) { + resp := &osconfigpb.ListOSPolicyAssignmentReportsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/reports", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOsPolicyAssignmentReports(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetInventory get inventory data for the specified VM instance. If the VM has no +// associated inventory, the message NOT_FOUND is returned. +func (c *osConfigZonalRESTClient) GetInventory(ctx context.Context, req *osconfigpb.GetInventoryRequest, opts ...gax.CallOption) (*osconfigpb.Inventory, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetView() != 0 { + params.Add("view", fmt.Sprintf("%v", req.GetView())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetInventory[0:len((*c.CallOptions).GetInventory):len((*c.CallOptions).GetInventory)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &osconfigpb.Inventory{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListInventories list inventory data for all VM instances in the specified zone. +func (c *osConfigZonalRESTClient) ListInventories(ctx context.Context, req *osconfigpb.ListInventoriesRequest, opts ...gax.CallOption) *InventoryIterator { + it := &InventoryIterator{} + req = proto.Clone(req).(*osconfigpb.ListInventoriesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*osconfigpb.Inventory, string, error) { + resp := &osconfigpb.ListInventoriesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/inventories", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + if req.GetView() != 0 { + params.Add("view", fmt.Sprintf("%v", req.GetView())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetInventories(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetVulnerabilityReport gets the vulnerability report for the specified VM instance. Only VMs with +// inventory data have vulnerability reports associated with them. +func (c *osConfigZonalRESTClient) GetVulnerabilityReport(ctx context.Context, req *osconfigpb.GetVulnerabilityReportRequest, opts ...gax.CallOption) (*osconfigpb.VulnerabilityReport, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetVulnerabilityReport[0:len((*c.CallOptions).GetVulnerabilityReport):len((*c.CallOptions).GetVulnerabilityReport)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &osconfigpb.VulnerabilityReport{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListVulnerabilityReports list vulnerability reports for all VM instances in the specified zone. +func (c *osConfigZonalRESTClient) ListVulnerabilityReports(ctx context.Context, req *osconfigpb.ListVulnerabilityReportsRequest, opts ...gax.CallOption) *VulnerabilityReportIterator { + it := &VulnerabilityReportIterator{} + req = proto.Clone(req).(*osconfigpb.ListVulnerabilityReportsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*osconfigpb.VulnerabilityReport, string, error) { + resp := &osconfigpb.ListVulnerabilityReportsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/vulnerabilityReports", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetVulnerabilityReports(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CreateOSPolicyAssignmentOperation manages a long-running operation from CreateOSPolicyAssignment. +type CreateOSPolicyAssignmentOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateOSPolicyAssignmentOperation returns a new CreateOSPolicyAssignmentOperation from a given name. +// The name must be that of a previously created CreateOSPolicyAssignmentOperation, possibly from a different process. +func (c *osConfigZonalGRPCClient) CreateOSPolicyAssignmentOperation(name string) *CreateOSPolicyAssignmentOperation { + return &CreateOSPolicyAssignmentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateOSPolicyAssignmentOperation returns a new CreateOSPolicyAssignmentOperation from a given name. +// The name must be that of a previously created CreateOSPolicyAssignmentOperation, possibly from a different process. +func (c *osConfigZonalRESTClient) CreateOSPolicyAssignmentOperation(name string) *CreateOSPolicyAssignmentOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateOSPolicyAssignmentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CreateOSPolicyAssignmentOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*osconfigpb.OSPolicyAssignment, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp osconfigpb.OSPolicyAssignment + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *CreateOSPolicyAssignmentOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*osconfigpb.OSPolicyAssignment, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp osconfigpb.OSPolicyAssignment + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *CreateOSPolicyAssignmentOperation) Metadata() (*osconfigpb.OSPolicyAssignmentOperationMetadata, error) { + var meta osconfigpb.OSPolicyAssignmentOperationMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *CreateOSPolicyAssignmentOperation) Done() bool { + return op.lro.Done() +} + +// 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 *CreateOSPolicyAssignmentOperation) Name() string { + return op.lro.Name() +} + +// DeleteOSPolicyAssignmentOperation manages a long-running operation from DeleteOSPolicyAssignment. +type DeleteOSPolicyAssignmentOperation struct { + lro *longrunning.Operation + pollPath string +} + +// DeleteOSPolicyAssignmentOperation returns a new DeleteOSPolicyAssignmentOperation from a given name. +// The name must be that of a previously created DeleteOSPolicyAssignmentOperation, possibly from a different process. +func (c *osConfigZonalGRPCClient) DeleteOSPolicyAssignmentOperation(name string) *DeleteOSPolicyAssignmentOperation { + return &DeleteOSPolicyAssignmentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// DeleteOSPolicyAssignmentOperation returns a new DeleteOSPolicyAssignmentOperation from a given name. +// The name must be that of a previously created DeleteOSPolicyAssignmentOperation, possibly from a different process. +func (c *osConfigZonalRESTClient) DeleteOSPolicyAssignmentOperation(name string) *DeleteOSPolicyAssignmentOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteOSPolicyAssignmentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *DeleteOSPolicyAssignmentOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *DeleteOSPolicyAssignmentOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + return op.lro.Poll(ctx, nil, opts...) +} + // Metadata returns metadata associated with the long-running operation. // Metadata itself does not contact the server, but Poll does. // To get the latest metadata, call this method after a successful call to Poll. @@ -999,7 +2174,8 @@ func (op *DeleteOSPolicyAssignmentOperation) Name() string { // UpdateOSPolicyAssignmentOperation manages a long-running operation from UpdateOSPolicyAssignment. type UpdateOSPolicyAssignmentOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateOSPolicyAssignmentOperation returns a new UpdateOSPolicyAssignmentOperation from a given name. @@ -1010,10 +2186,21 @@ func (c *osConfigZonalGRPCClient) UpdateOSPolicyAssignmentOperation(name string) } } +// UpdateOSPolicyAssignmentOperation returns a new UpdateOSPolicyAssignmentOperation from a given name. +// The name must be that of a previously created UpdateOSPolicyAssignmentOperation, possibly from a different process. +func (c *osConfigZonalRESTClient) UpdateOSPolicyAssignmentOperation(name string) *UpdateOSPolicyAssignmentOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateOSPolicyAssignmentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateOSPolicyAssignmentOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*osconfigpb.OSPolicyAssignment, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp osconfigpb.OSPolicyAssignment if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1031,6 +2218,7 @@ func (op *UpdateOSPolicyAssignmentOperation) Wait(ctx context.Context, opts ...g // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateOSPolicyAssignmentOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*osconfigpb.OSPolicyAssignment, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp osconfigpb.OSPolicyAssignment if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/osconfig/apiv1/os_config_zonal_client_example_test.go b/osconfig/apiv1/os_config_zonal_client_example_test.go index 481663048da2..65ced0841990 100644 --- a/osconfig/apiv1/os_config_zonal_client_example_test.go +++ b/osconfig/apiv1/os_config_zonal_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewOsConfigZonalClient() { _ = c } +func ExampleNewOsConfigZonalRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := osconfig.NewOsConfigZonalRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleOsConfigZonalClient_CreateOSPolicyAssignment() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/osconfig/apiv1/osconfigpb/inventory.pb.go b/osconfig/apiv1/osconfigpb/inventory.pb.go index 3acd3be76e38..9749cfae36d0 100644 --- a/osconfig/apiv1/osconfigpb/inventory.pb.go +++ b/osconfig/apiv1/osconfigpb/inventory.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/osconfig/v1/inventory.proto package osconfigpb @@ -636,7 +636,6 @@ type Inventory_Item struct { // Specific details of this inventory item based on its type. // // Types that are assignable to Details: - // // *Inventory_Item_InstalledPackage // *Inventory_Item_AvailablePackage Details isInventory_Item_Details `protobuf_oneof:"details"` @@ -757,7 +756,6 @@ type Inventory_SoftwarePackage struct { // Information about the different types of software packages. // // Types that are assignable to Details: - // // *Inventory_SoftwarePackage_YumPackage // *Inventory_SoftwarePackage_AptPackage // *Inventory_SoftwarePackage_ZypperPackage @@ -899,9 +897,8 @@ type Inventory_SoftwarePackage_ZypperPackage struct { type Inventory_SoftwarePackage_GoogetPackage struct { // Details of a Googet package. - // - // For details about the googet package manager, see - // https://github.com/google/googet. + // For details about the googet package manager, see + // https://github.com/google/googet. GoogetPackage *Inventory_VersionedPackage `protobuf:"bytes,4,opt,name=googet_package,json=googetPackage,proto3,oneof"` } diff --git a/osconfig/apiv1/osconfigpb/os_policy.pb.go b/osconfig/apiv1/osconfigpb/os_policy.pb.go index 2667734eb553..06185ca3df07 100644 --- a/osconfig/apiv1/osconfigpb/os_policy.pb.go +++ b/osconfig/apiv1/osconfigpb/os_policy.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/osconfig/v1/os_policy.proto package osconfigpb @@ -507,7 +507,6 @@ type OSPolicy_Resource struct { // Resource type. // // Types that are assignable to ResourceType: - // // *OSPolicy_Resource_Pkg // *OSPolicy_Resource_Repository // *OSPolicy_Resource_Exec @@ -708,7 +707,6 @@ type OSPolicy_Resource_File struct { // A specific type of file. // // Types that are assignable to Type: - // // *OSPolicy_Resource_File_Remote_ // *OSPolicy_Resource_File_Gcs_ // *OSPolicy_Resource_File_LocalPath @@ -824,7 +822,6 @@ type OSPolicy_Resource_PackageResource struct { // A system package. // // Types that are assignable to SystemPackage: - // // *OSPolicy_Resource_PackageResource_Apt // *OSPolicy_Resource_PackageResource_Deb_ // *OSPolicy_Resource_PackageResource_Yum @@ -994,7 +991,6 @@ type OSPolicy_Resource_RepositoryResource struct { // A specific type of repository. // // Types that are assignable to Repository: - // // *OSPolicy_Resource_RepositoryResource_Apt // *OSPolicy_Resource_RepositoryResource_Yum // *OSPolicy_Resource_RepositoryResource_Zypper @@ -1202,7 +1198,6 @@ type OSPolicy_Resource_FileResource struct { // The source for the contents of the file. // // Types that are assignable to Source: - // // *OSPolicy_Resource_FileResource_File // *OSPolicy_Resource_FileResource_Content Source isOSPolicy_Resource_FileResource_Source `protobuf_oneof:"source"` @@ -2152,7 +2147,6 @@ type OSPolicy_Resource_ExecResource_Exec struct { // What to execute. // // Types that are assignable to Source: - // // *OSPolicy_Resource_ExecResource_Exec_File // *OSPolicy_Resource_ExecResource_Exec_Script Source isOSPolicy_Resource_ExecResource_Exec_Source `protobuf_oneof:"source"` diff --git a/osconfig/apiv1/osconfigpb/os_policy_assignment_reports.pb.go b/osconfig/apiv1/osconfigpb/os_policy_assignment_reports.pb.go index 55786ac392cb..79c5cba978fa 100644 --- a/osconfig/apiv1/osconfigpb/os_policy_assignment_reports.pb.go +++ b/osconfig/apiv1/osconfigpb/os_policy_assignment_reports.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/osconfig/v1/os_policy_assignment_reports.proto package osconfigpb @@ -302,16 +302,11 @@ type ListOSPolicyAssignmentReportsRequest struct { // // For example: // `projects/{project}/locations/{location}/instances/{instance}/osPolicyAssignments/-/reports` - // - // returns all reports for the instance - // + // returns all reports for the instance // `projects/{project}/locations/{location}/instances/-/osPolicyAssignments/{assignment-id}/reports` - // - // returns all the reports for the given assignment across all instances. - // + // returns all the reports for the given assignment across all instances. // `projects/{project}/locations/{location}/instances/-/osPolicyAssignments/-/reports` - // - // returns all the reports for all assignments across all instances. + // returns all the reports for all assignments across all instances. Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // The maximum number of results to return. PageSize int32 `protobuf:"varint,2,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"` @@ -678,7 +673,6 @@ type OSPolicyAssignmentReport_OSPolicyCompliance_OSPolicyResourceCompliance stru // Resource specific output. // // Types that are assignable to Output: - // // *OSPolicyAssignmentReport_OSPolicyCompliance_OSPolicyResourceCompliance_ExecResourceOutput_ Output isOSPolicyAssignmentReport_OSPolicyCompliance_OSPolicyResourceCompliance_Output `protobuf_oneof:"output"` } diff --git a/osconfig/apiv1/osconfigpb/os_policy_assignments.pb.go b/osconfig/apiv1/osconfigpb/os_policy_assignments.pb.go index 66f7419bac2d..6ad5ddc7772b 100644 --- a/osconfig/apiv1/osconfigpb/os_policy_assignments.pb.go +++ b/osconfig/apiv1/osconfigpb/os_policy_assignments.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/osconfig/v1/os_policy_assignments.proto package osconfigpb @@ -253,9 +253,8 @@ type OSPolicyAssignment struct { // 1) OSPolicyAssignment is created. // 2) OSPolicyAssignment is updated and the update contains changes to one of // the following fields: - // - instance_filter - // - os_policies - // + // - instance_filter + // - os_policies // 3) OSPolicyAssignment is deleted. Rollout *OSPolicyAssignment_Rollout `protobuf:"bytes,5,opt,name=rollout,proto3" json:"rollout,omitempty"` // Output only. The assignment revision ID diff --git a/osconfig/apiv1/osconfigpb/osconfig_common.pb.go b/osconfig/apiv1/osconfigpb/osconfig_common.pb.go index e9b3474140ee..3dc5b7ba3a22 100644 --- a/osconfig/apiv1/osconfigpb/osconfig_common.pb.go +++ b/osconfig/apiv1/osconfigpb/osconfig_common.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/osconfig/v1/osconfig_common.proto package osconfigpb @@ -45,7 +45,6 @@ type FixedOrPercent struct { // Type of the value. // // Types that are assignable to Mode: - // // *FixedOrPercent_Fixed // *FixedOrPercent_Percent Mode isFixedOrPercent_Mode `protobuf_oneof:"mode"` diff --git a/osconfig/apiv1/osconfigpb/osconfig_service.pb.go b/osconfig/apiv1/osconfigpb/osconfig_service.pb.go index 587f66dcb6bb..e2c8b2614d2b 100644 --- a/osconfig/apiv1/osconfigpb/osconfig_service.pb.go +++ b/osconfig/apiv1/osconfigpb/osconfig_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/osconfig/v1/osconfig_service.proto package osconfigpb diff --git a/osconfig/apiv1/osconfigpb/osconfig_zonal_service.pb.go b/osconfig/apiv1/osconfigpb/osconfig_zonal_service.pb.go index 969f458e8970..787a75214ff9 100644 --- a/osconfig/apiv1/osconfigpb/osconfig_zonal_service.pb.go +++ b/osconfig/apiv1/osconfigpb/osconfig_zonal_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/osconfig/v1/osconfig_zonal_service.proto package osconfigpb diff --git a/osconfig/apiv1/osconfigpb/patch_deployments.pb.go b/osconfig/apiv1/osconfigpb/patch_deployments.pb.go index 1c64d7d0215d..7790ec626605 100644 --- a/osconfig/apiv1/osconfigpb/patch_deployments.pb.go +++ b/osconfig/apiv1/osconfigpb/patch_deployments.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/osconfig/v1/patch_deployments.proto package osconfigpb @@ -184,7 +184,6 @@ type PatchDeployment struct { // Schedule for the patch. // // Types that are assignable to Schedule: - // // *PatchDeployment_OneTimeSchedule // *PatchDeployment_RecurringSchedule Schedule isPatchDeployment_Schedule `protobuf_oneof:"schedule"` @@ -418,7 +417,6 @@ type RecurringSchedule struct { // Configurations must match frequency. // // Types that are assignable to ScheduleConfig: - // // *RecurringSchedule_Weekly // *RecurringSchedule_Monthly ScheduleConfig isRecurringSchedule_ScheduleConfig `protobuf_oneof:"schedule_config"` @@ -594,7 +592,7 @@ func (x *WeeklySchedule) GetDayOfWeek() dayofweek.DayOfWeek { if x != nil { return x.DayOfWeek } - return dayofweek.DayOfWeek_DAY_OF_WEEK_UNSPECIFIED + return dayofweek.DayOfWeek(0) } // Represents a monthly schedule. An example of a valid monthly schedule is @@ -607,7 +605,6 @@ type MonthlySchedule struct { // One day in a month. // // Types that are assignable to DayOfMonth: - // // *MonthlySchedule_WeekDayOfMonth // *MonthlySchedule_MonthDay DayOfMonth isMonthlySchedule_DayOfMonth `protobuf_oneof:"day_of_month"` @@ -751,7 +748,7 @@ func (x *WeekDayOfMonth) GetDayOfWeek() dayofweek.DayOfWeek { if x != nil { return x.DayOfWeek } - return dayofweek.DayOfWeek_DAY_OF_WEEK_UNSPECIFIED + return dayofweek.DayOfWeek(0) } func (x *WeekDayOfMonth) GetDayOffset() int32 { diff --git a/osconfig/apiv1/osconfigpb/patch_jobs.pb.go b/osconfig/apiv1/osconfigpb/patch_jobs.pb.go index 33ac3f0ce050..44aa10550f3c 100644 --- a/osconfig/apiv1/osconfigpb/patch_jobs.pb.go +++ b/osconfig/apiv1/osconfigpb/patch_jobs.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/osconfig/v1/patch_jobs.proto package osconfigpb @@ -1912,7 +1912,6 @@ type ExecStepConfig struct { // Location of the executable. // // Types that are assignable to Executable: - // // *ExecStepConfig_LocalPath // *ExecStepConfig_GcsObject Executable isExecStepConfig_Executable `protobuf_oneof:"executable"` diff --git a/osconfig/apiv1/osconfigpb/vulnerability.pb.go b/osconfig/apiv1/osconfigpb/vulnerability.pb.go index 2d07fc213f31..1aa3221414b1 100644 --- a/osconfig/apiv1/osconfigpb/vulnerability.pb.go +++ b/osconfig/apiv1/osconfigpb/vulnerability.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/osconfig/v1/vulnerability.proto package osconfigpb diff --git a/osconfig/apiv1alpha/os_config_zonal_client.go b/osconfig/apiv1alpha/os_config_zonal_client.go index 5ec612700304..5197f12482a9 100644 --- a/osconfig/apiv1alpha/os_config_zonal_client.go +++ b/osconfig/apiv1alpha/os_config_zonal_client.go @@ -1240,6 +1240,7 @@ func (c *osConfigZonalRESTClient) CreateOSPolicyAssignment(ctx context.Context, baseUrl.Path += fmt.Sprintf("/v1alpha/%v/osPolicyAssignments", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("osPolicyAssignmentId", fmt.Sprintf("%v", req.GetOsPolicyAssignmentId())) baseUrl.RawQuery = params.Encode() @@ -1317,6 +1318,7 @@ func (c *osConfigZonalRESTClient) UpdateOSPolicyAssignment(ctx context.Context, baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetOsPolicyAssignment().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -1388,6 +1390,11 @@ func (c *osConfigZonalRESTClient) GetOSPolicyAssignment(ctx context.Context, req } baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1457,6 +1464,7 @@ func (c *osConfigZonalRESTClient) ListOSPolicyAssignments(ctx context.Context, r baseUrl.Path += fmt.Sprintf("/v1alpha/%v/osPolicyAssignments", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -1544,6 +1552,7 @@ func (c *osConfigZonalRESTClient) ListOSPolicyAssignmentRevisions(ctx context.Co baseUrl.Path += fmt.Sprintf("/v1alpha/%v:listRevisions", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -1628,6 +1637,11 @@ func (c *osConfigZonalRESTClient) DeleteOSPolicyAssignment(ctx context.Context, } baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1688,6 +1702,11 @@ func (c *osConfigZonalRESTClient) GetInstanceOSPoliciesCompliance(ctx context.Co } baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1758,6 +1777,7 @@ func (c *osConfigZonalRESTClient) ListInstanceOSPoliciesCompliances(ctx context. baseUrl.Path += fmt.Sprintf("/v1alpha/%v/instanceOSPoliciesCompliances", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1835,6 +1855,11 @@ func (c *osConfigZonalRESTClient) GetOSPolicyAssignmentReport(ctx context.Contex } baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1903,6 +1928,7 @@ func (c *osConfigZonalRESTClient) ListOSPolicyAssignmentReports(ctx context.Cont baseUrl.Path += fmt.Sprintf("/v1alpha/%v/reports", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1981,6 +2007,7 @@ func (c *osConfigZonalRESTClient) GetInventory(ctx context.Context, req *osconfi baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetView() != 0 { params.Add("view", fmt.Sprintf("%v", req.GetView())) } @@ -2054,6 +2081,7 @@ func (c *osConfigZonalRESTClient) ListInventories(ctx context.Context, req *osco baseUrl.Path += fmt.Sprintf("/v1alpha/%v/inventories", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -2134,6 +2162,11 @@ func (c *osConfigZonalRESTClient) GetVulnerabilityReport(ctx context.Context, re } baseUrl.Path += fmt.Sprintf("/v1alpha/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2201,6 +2234,7 @@ func (c *osConfigZonalRESTClient) ListVulnerabilityReports(ctx context.Context, baseUrl.Path += fmt.Sprintf("/v1alpha/%v/vulnerabilityReports", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/osconfig/apiv1alpha/osconfigpb/config_common.pb.go b/osconfig/apiv1alpha/osconfigpb/config_common.pb.go index 3ea0e45ab2a7..d30288d10330 100644 --- a/osconfig/apiv1alpha/osconfigpb/config_common.pb.go +++ b/osconfig/apiv1alpha/osconfigpb/config_common.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/osconfig/v1alpha/config_common.proto package osconfigpb @@ -312,7 +312,6 @@ type OSPolicyResourceCompliance struct { // Resource specific output. // // Types that are assignable to Output: - // // *OSPolicyResourceCompliance_ExecResourceOutput_ Output isOSPolicyResourceCompliance_Output `protobuf_oneof:"output"` } diff --git a/osconfig/apiv1alpha/osconfigpb/instance_os_policies_compliance.pb.go b/osconfig/apiv1alpha/osconfigpb/instance_os_policies_compliance.pb.go index 64a868eb58a7..7a875db20989 100644 --- a/osconfig/apiv1alpha/osconfigpb/instance_os_policies_compliance.pb.go +++ b/osconfig/apiv1alpha/osconfigpb/instance_os_policies_compliance.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/osconfig/v1alpha/instance_os_policies_compliance.proto package osconfigpb diff --git a/osconfig/apiv1alpha/osconfigpb/inventory.pb.go b/osconfig/apiv1alpha/osconfigpb/inventory.pb.go index 1bca7292b094..de22db2e7b1a 100644 --- a/osconfig/apiv1alpha/osconfigpb/inventory.pb.go +++ b/osconfig/apiv1alpha/osconfigpb/inventory.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/osconfig/v1alpha/inventory.proto package osconfigpb @@ -636,7 +636,6 @@ type Inventory_Item struct { // Specific details of this inventory item based on its type. // // Types that are assignable to Details: - // // *Inventory_Item_InstalledPackage // *Inventory_Item_AvailablePackage Details isInventory_Item_Details `protobuf_oneof:"details"` @@ -757,7 +756,6 @@ type Inventory_SoftwarePackage struct { // Information about the different types of software packages. // // Types that are assignable to Details: - // // *Inventory_SoftwarePackage_YumPackage // *Inventory_SoftwarePackage_AptPackage // *Inventory_SoftwarePackage_ZypperPackage @@ -899,9 +897,8 @@ type Inventory_SoftwarePackage_ZypperPackage struct { type Inventory_SoftwarePackage_GoogetPackage struct { // Details of a Googet package. - // - // For details about the googet package manager, see - // https://github.com/google/googet. + // For details about the googet package manager, see + // https://github.com/google/googet. GoogetPackage *Inventory_VersionedPackage `protobuf:"bytes,4,opt,name=googet_package,json=googetPackage,proto3,oneof"` } diff --git a/osconfig/apiv1alpha/osconfigpb/os_policy.pb.go b/osconfig/apiv1alpha/osconfigpb/os_policy.pb.go index d8e84bec84cf..716fea1b965e 100644 --- a/osconfig/apiv1alpha/osconfigpb/os_policy.pb.go +++ b/osconfig/apiv1alpha/osconfigpb/os_policy.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/osconfig/v1alpha/os_policy.proto package osconfigpb @@ -570,7 +570,6 @@ type OSPolicy_Resource struct { // Resource type. // // Types that are assignable to ResourceType: - // // *OSPolicy_Resource_Pkg // *OSPolicy_Resource_Repository // *OSPolicy_Resource_Exec @@ -784,7 +783,6 @@ type OSPolicy_Resource_File struct { // A specific type of file. // // Types that are assignable to Type: - // // *OSPolicy_Resource_File_Remote_ // *OSPolicy_Resource_File_Gcs_ // *OSPolicy_Resource_File_LocalPath @@ -900,7 +898,6 @@ type OSPolicy_Resource_PackageResource struct { // A system package. // // Types that are assignable to SystemPackage: - // // *OSPolicy_Resource_PackageResource_Apt // *OSPolicy_Resource_PackageResource_Deb_ // *OSPolicy_Resource_PackageResource_Yum @@ -1070,7 +1067,6 @@ type OSPolicy_Resource_RepositoryResource struct { // A specific type of repository. // // Types that are assignable to Repository: - // // *OSPolicy_Resource_RepositoryResource_Apt // *OSPolicy_Resource_RepositoryResource_Yum // *OSPolicy_Resource_RepositoryResource_Zypper @@ -1278,7 +1274,6 @@ type OSPolicy_Resource_FileResource struct { // The source for the contents of the file. // // Types that are assignable to Source: - // // *OSPolicy_Resource_FileResource_File // *OSPolicy_Resource_FileResource_Content Source isOSPolicy_Resource_FileResource_Source `protobuf_oneof:"source"` @@ -2228,7 +2223,6 @@ type OSPolicy_Resource_ExecResource_Exec struct { // What to execute. // // Types that are assignable to Source: - // // *OSPolicy_Resource_ExecResource_Exec_File // *OSPolicy_Resource_ExecResource_Exec_Script Source isOSPolicy_Resource_ExecResource_Exec_Source `protobuf_oneof:"source"` diff --git a/osconfig/apiv1alpha/osconfigpb/os_policy_assignment_reports.pb.go b/osconfig/apiv1alpha/osconfigpb/os_policy_assignment_reports.pb.go index 677f62bd69db..d75e22170c18 100644 --- a/osconfig/apiv1alpha/osconfigpb/os_policy_assignment_reports.pb.go +++ b/osconfig/apiv1alpha/osconfigpb/os_policy_assignment_reports.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/osconfig/v1alpha/os_policy_assignment_reports.proto package osconfigpb @@ -302,16 +302,11 @@ type ListOSPolicyAssignmentReportsRequest struct { // // For example: // `projects/{project}/locations/{location}/instances/{instance}/osPolicyAssignments/-/reports` - // - // returns all reports for the instance - // + // returns all reports for the instance // `projects/{project}/locations/{location}/instances/-/osPolicyAssignments/{assignment-id}/reports` - // - // returns all the reports for the given assignment across all instances. - // + // returns all the reports for the given assignment across all instances. // `projects/{project}/locations/{location}/instances/-/osPolicyAssignments/-/reports` - // - // returns all the reports for all assignments across all instances. + // returns all the reports for all assignments across all instances. Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // The maximum number of results to return. PageSize int32 `protobuf:"varint,2,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"` @@ -678,7 +673,6 @@ type OSPolicyAssignmentReport_OSPolicyCompliance_OSPolicyResourceCompliance stru // Resource specific output. // // Types that are assignable to Output: - // // *OSPolicyAssignmentReport_OSPolicyCompliance_OSPolicyResourceCompliance_ExecResourceOutput_ Output isOSPolicyAssignmentReport_OSPolicyCompliance_OSPolicyResourceCompliance_Output `protobuf_oneof:"output"` } diff --git a/osconfig/apiv1alpha/osconfigpb/os_policy_assignments.pb.go b/osconfig/apiv1alpha/osconfigpb/os_policy_assignments.pb.go index e0c36bd04e09..53a530e8d6e1 100644 --- a/osconfig/apiv1alpha/osconfigpb/os_policy_assignments.pb.go +++ b/osconfig/apiv1alpha/osconfigpb/os_policy_assignments.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/osconfig/v1alpha/os_policy_assignments.proto package osconfigpb @@ -253,9 +253,8 @@ type OSPolicyAssignment struct { // 1) OSPolicyAssignment is created. // 2) OSPolicyAssignment is updated and the update contains changes to one of // the following fields: - // - instance_filter - // - os_policies - // + // - instance_filter + // - os_policies // 3) OSPolicyAssignment is deleted. Rollout *OSPolicyAssignment_Rollout `protobuf:"bytes,5,opt,name=rollout,proto3" json:"rollout,omitempty"` // Output only. The assignment revision ID diff --git a/osconfig/apiv1alpha/osconfigpb/osconfig_common.pb.go b/osconfig/apiv1alpha/osconfigpb/osconfig_common.pb.go index 745c39ab626e..8e15003b56a4 100644 --- a/osconfig/apiv1alpha/osconfigpb/osconfig_common.pb.go +++ b/osconfig/apiv1alpha/osconfigpb/osconfig_common.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/osconfig/v1alpha/osconfig_common.proto package osconfigpb @@ -45,7 +45,6 @@ type FixedOrPercent struct { // Type of the value. // // Types that are assignable to Mode: - // // *FixedOrPercent_Fixed // *FixedOrPercent_Percent Mode isFixedOrPercent_Mode `protobuf_oneof:"mode"` diff --git a/osconfig/apiv1alpha/osconfigpb/osconfig_zonal_service.pb.go b/osconfig/apiv1alpha/osconfigpb/osconfig_zonal_service.pb.go index ac9cf100d3ac..412f526ba07c 100644 --- a/osconfig/apiv1alpha/osconfigpb/osconfig_zonal_service.pb.go +++ b/osconfig/apiv1alpha/osconfigpb/osconfig_zonal_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/osconfig/v1alpha/osconfig_zonal_service.proto package osconfigpb diff --git a/osconfig/apiv1alpha/osconfigpb/vulnerability.pb.go b/osconfig/apiv1alpha/osconfigpb/vulnerability.pb.go index 684a1c85db0c..44c4844f2324 100644 --- a/osconfig/apiv1alpha/osconfigpb/vulnerability.pb.go +++ b/osconfig/apiv1alpha/osconfigpb/vulnerability.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/osconfig/v1alpha/vulnerability.proto package osconfigpb diff --git a/osconfig/apiv1beta/os_config_client.go b/osconfig/apiv1beta/os_config_client.go index 6ad795244025..cdec80b3efd4 100644 --- a/osconfig/apiv1beta/os_config_client.go +++ b/osconfig/apiv1beta/os_config_client.go @@ -1272,6 +1272,11 @@ func (c *restClient) ExecutePatchJob(ctx context.Context, req *osconfigpb.Execut } baseUrl.Path += fmt.Sprintf("/v1beta/%v/patchJobs:execute", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1326,6 +1331,11 @@ func (c *restClient) GetPatchJob(ctx context.Context, req *osconfigpb.GetPatchJo } baseUrl.Path += fmt.Sprintf("/v1beta/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1386,6 +1396,11 @@ func (c *restClient) CancelPatchJob(ctx context.Context, req *osconfigpb.CancelP } baseUrl.Path += fmt.Sprintf("/v1beta/%v:cancel", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1453,6 +1468,7 @@ func (c *restClient) ListPatchJobs(ctx context.Context, req *osconfigpb.ListPatc baseUrl.Path += fmt.Sprintf("/v1beta/%v/patchJobs", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1543,6 +1559,7 @@ func (c *restClient) ListPatchJobInstanceDetails(ctx context.Context, req *oscon baseUrl.Path += fmt.Sprintf("/v1beta/%v/instanceDetails", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1627,6 +1644,7 @@ func (c *restClient) CreatePatchDeployment(ctx context.Context, req *osconfigpb. baseUrl.Path += fmt.Sprintf("/v1beta/%v/patchDeployments", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("patchDeploymentId", fmt.Sprintf("%v", req.GetPatchDeploymentId())) baseUrl.RawQuery = params.Encode() @@ -1684,6 +1702,11 @@ func (c *restClient) GetPatchDeployment(ctx context.Context, req *osconfigpb.Get } baseUrl.Path += fmt.Sprintf("/v1beta/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1751,6 +1774,7 @@ func (c *restClient) ListPatchDeployments(ctx context.Context, req *osconfigpb.L baseUrl.Path += fmt.Sprintf("/v1beta/%v/patchDeployments", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -1824,6 +1848,11 @@ func (c *restClient) DeletePatchDeployment(ctx context.Context, req *osconfigpb. } baseUrl.Path += fmt.Sprintf("/v1beta/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1867,6 +1896,7 @@ func (c *restClient) UpdatePatchDeployment(ctx context.Context, req *osconfigpb. baseUrl.Path += fmt.Sprintf("/v1beta/%v", req.GetPatchDeployment().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -1937,6 +1967,11 @@ func (c *restClient) PausePatchDeployment(ctx context.Context, req *osconfigpb.P } baseUrl.Path += fmt.Sprintf("/v1beta/%v:pause", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1997,6 +2032,11 @@ func (c *restClient) ResumePatchDeployment(ctx context.Context, req *osconfigpb. } baseUrl.Path += fmt.Sprintf("/v1beta/%v:resume", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2058,6 +2098,7 @@ func (c *restClient) CreateGuestPolicy(ctx context.Context, req *osconfigpb.Crea baseUrl.Path += fmt.Sprintf("/v1beta/%v/guestPolicies", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("guestPolicyId", fmt.Sprintf("%v", req.GetGuestPolicyId())) baseUrl.RawQuery = params.Encode() @@ -2115,6 +2156,11 @@ func (c *restClient) GetGuestPolicy(ctx context.Context, req *osconfigpb.GetGues } baseUrl.Path += fmt.Sprintf("/v1beta/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2182,6 +2228,7 @@ func (c *restClient) ListGuestPolicies(ctx context.Context, req *osconfigpb.List baseUrl.Path += fmt.Sprintf("/v1beta/%v/guestPolicies", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -2263,6 +2310,7 @@ func (c *restClient) UpdateGuestPolicy(ctx context.Context, req *osconfigpb.Upda baseUrl.Path += fmt.Sprintf("/v1beta/%v", req.GetGuestPolicy().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -2326,6 +2374,11 @@ func (c *restClient) DeleteGuestPolicy(ctx context.Context, req *osconfigpb.Dele } baseUrl.Path += fmt.Sprintf("/v1beta/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2368,6 +2421,11 @@ func (c *restClient) LookupEffectiveGuestPolicy(ctx context.Context, req *osconf } baseUrl.Path += fmt.Sprintf("/v1beta/%v:lookupEffectiveGuestPolicy", req.GetInstance()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "instance", url.QueryEscape(req.GetInstance()))) diff --git a/osconfig/apiv1beta/osconfigpb/guest_policies.pb.go b/osconfig/apiv1beta/osconfigpb/guest_policies.pb.go index 73f928390202..ac0bfe1962ec 100644 --- a/osconfig/apiv1beta/osconfigpb/guest_policies.pb.go +++ b/osconfig/apiv1beta/osconfigpb/guest_policies.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/osconfig/v1beta/guest_policies.proto package osconfigpb @@ -1007,7 +1007,6 @@ type PackageRepository struct { // A specific type of repository. // // Types that are assignable to Repository: - // // *PackageRepository_Apt // *PackageRepository_Yum // *PackageRepository_Zypper @@ -1167,17 +1166,12 @@ type SoftwareRecipe struct { // recipe. // // INSTALLED: The software recipe is installed on the instance but - // - // won't be updated to new versions. - // + // won't be updated to new versions. // UPDATED: The software recipe is installed on the instance. The recipe is - // - // updated to a higher version, if a higher version of the recipe is - // assigned to this instance. - // + // updated to a higher version, if a higher version of the recipe is + // assigned to this instance. // REMOVE: Remove is unsupported for software recipes and attempts to - // - // create or update a recipe to the REMOVE state is rejected. + // create or update a recipe to the REMOVE state is rejected. DesiredState DesiredState `protobuf:"varint,6,opt,name=desired_state,json=desiredState,proto3,enum=google.cloud.osconfig.v1beta.DesiredState" json:"desired_state,omitempty"` } @@ -1900,7 +1894,6 @@ type SoftwareRecipe_Artifact struct { // A specific type of artifact. // // Types that are assignable to Artifact: - // // *SoftwareRecipe_Artifact_Remote_ // *SoftwareRecipe_Artifact_Gcs_ Artifact isSoftwareRecipe_Artifact_Artifact `protobuf_oneof:"artifact"` @@ -2007,7 +2000,6 @@ type SoftwareRecipe_Step struct { // A specific type of step. // // Types that are assignable to Step: - // // *SoftwareRecipe_Step_FileCopy // *SoftwareRecipe_Step_ArchiveExtraction // *SoftwareRecipe_Step_MsiInstallation @@ -2634,7 +2626,6 @@ type SoftwareRecipe_Step_ExecFile struct { // Location of the file to execute. // // Types that are assignable to LocationType: - // // *SoftwareRecipe_Step_ExecFile_ArtifactId // *SoftwareRecipe_Step_ExecFile_LocalPath LocationType isSoftwareRecipe_Step_ExecFile_LocationType `protobuf_oneof:"location_type"` diff --git a/osconfig/apiv1beta/osconfigpb/osconfig_common.pb.go b/osconfig/apiv1beta/osconfigpb/osconfig_common.pb.go index 1add11575163..491544184638 100644 --- a/osconfig/apiv1beta/osconfigpb/osconfig_common.pb.go +++ b/osconfig/apiv1beta/osconfigpb/osconfig_common.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/osconfig/v1beta/osconfig_common.proto package osconfigpb @@ -45,7 +45,6 @@ type FixedOrPercent struct { // Type of the value. // // Types that are assignable to Mode: - // // *FixedOrPercent_Fixed // *FixedOrPercent_Percent Mode isFixedOrPercent_Mode `protobuf_oneof:"mode"` diff --git a/osconfig/apiv1beta/osconfigpb/osconfig_service.pb.go b/osconfig/apiv1beta/osconfigpb/osconfig_service.pb.go index c0b851dddb61..d4f7c5289a02 100644 --- a/osconfig/apiv1beta/osconfigpb/osconfig_service.pb.go +++ b/osconfig/apiv1beta/osconfigpb/osconfig_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/osconfig/v1beta/osconfig_service.proto package osconfigpb diff --git a/osconfig/apiv1beta/osconfigpb/patch_deployments.pb.go b/osconfig/apiv1beta/osconfigpb/patch_deployments.pb.go index c5e492089b89..ed98c5596243 100644 --- a/osconfig/apiv1beta/osconfigpb/patch_deployments.pb.go +++ b/osconfig/apiv1beta/osconfigpb/patch_deployments.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/osconfig/v1beta/patch_deployments.proto package osconfigpb @@ -183,7 +183,6 @@ type PatchDeployment struct { // Schedule for the patch. // // Types that are assignable to Schedule: - // // *PatchDeployment_OneTimeSchedule // *PatchDeployment_RecurringSchedule Schedule isPatchDeployment_Schedule `protobuf_oneof:"schedule"` @@ -417,7 +416,6 @@ type RecurringSchedule struct { // Configurations must match frequency. // // Types that are assignable to ScheduleConfig: - // // *RecurringSchedule_Weekly // *RecurringSchedule_Monthly ScheduleConfig isRecurringSchedule_ScheduleConfig `protobuf_oneof:"schedule_config"` @@ -593,7 +591,7 @@ func (x *WeeklySchedule) GetDayOfWeek() dayofweek.DayOfWeek { if x != nil { return x.DayOfWeek } - return dayofweek.DayOfWeek_DAY_OF_WEEK_UNSPECIFIED + return dayofweek.DayOfWeek(0) } // Represents a monthly schedule. An example of a valid monthly schedule is @@ -606,7 +604,6 @@ type MonthlySchedule struct { // One day in a month. // // Types that are assignable to DayOfMonth: - // // *MonthlySchedule_WeekDayOfMonth // *MonthlySchedule_MonthDay DayOfMonth isMonthlySchedule_DayOfMonth `protobuf_oneof:"day_of_month"` @@ -750,7 +747,7 @@ func (x *WeekDayOfMonth) GetDayOfWeek() dayofweek.DayOfWeek { if x != nil { return x.DayOfWeek } - return dayofweek.DayOfWeek_DAY_OF_WEEK_UNSPECIFIED + return dayofweek.DayOfWeek(0) } func (x *WeekDayOfMonth) GetDayOffset() int32 { diff --git a/osconfig/apiv1beta/osconfigpb/patch_jobs.pb.go b/osconfig/apiv1beta/osconfigpb/patch_jobs.pb.go index ca9d275aba31..32dfec0d370e 100644 --- a/osconfig/apiv1beta/osconfigpb/patch_jobs.pb.go +++ b/osconfig/apiv1beta/osconfigpb/patch_jobs.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/osconfig/v1beta/patch_jobs.proto package osconfigpb @@ -1910,7 +1910,6 @@ type ExecStepConfig struct { // Location of the executable. // // Types that are assignable to Executable: - // // *ExecStepConfig_LocalPath // *ExecStepConfig_GcsObject Executable isExecStepConfig_Executable `protobuf_oneof:"executable"` diff --git a/oslogin/apiv1/doc.go b/oslogin/apiv1/doc.go index 4e9b348ef56b..3573bffec72c 100644 --- a/oslogin/apiv1/doc.go +++ b/oslogin/apiv1/doc.go @@ -81,6 +81,8 @@ package oslogin // import "cloud.google.com/go/oslogin/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -172,3 +174,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/oslogin/apiv1/gapic_metadata.json b/oslogin/apiv1/gapic_metadata.json index 885be96da0da..8e41b224b11a 100644 --- a/oslogin/apiv1/gapic_metadata.json +++ b/oslogin/apiv1/gapic_metadata.json @@ -46,6 +46,46 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "CreateSshPublicKey": { + "methods": [ + "CreateSshPublicKey" + ] + }, + "DeletePosixAccount": { + "methods": [ + "DeletePosixAccount" + ] + }, + "DeleteSshPublicKey": { + "methods": [ + "DeleteSshPublicKey" + ] + }, + "GetLoginProfile": { + "methods": [ + "GetLoginProfile" + ] + }, + "GetSshPublicKey": { + "methods": [ + "GetSshPublicKey" + ] + }, + "ImportSshPublicKey": { + "methods": [ + "ImportSshPublicKey" + ] + }, + "UpdateSshPublicKey": { + "methods": [ + "UpdateSshPublicKey" + ] + } + } } } } diff --git a/oslogin/apiv1/os_login_client.go b/oslogin/apiv1/os_login_client.go index 063a7a3aa2da..06f55409629f 100644 --- a/oslogin/apiv1/os_login_client.go +++ b/oslogin/apiv1/os_login_client.go @@ -17,21 +17,27 @@ package oslogin import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" osloginpb "cloud.google.com/go/oslogin/apiv1/osloginpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" commonpb "google.golang.org/genproto/googleapis/cloud/oslogin/common" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" ) var newClientHook clientHook @@ -137,6 +143,78 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + CreateSshPublicKey: []gax.CallOption{}, + DeletePosixAccount: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + DeleteSshPublicKey: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + GetLoginProfile: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + GetSshPublicKey: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + ImportSshPublicKey: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + UpdateSshPublicKey: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + } +} + // internalClient is an interface that defines the methods available from Cloud OS Login API. type internalClient interface { Close() error @@ -312,6 +390,77 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new os login service rest client. +// +// # Cloud OS Login API +// +// The Cloud OS Login API allows you to manage users and their associated SSH +// public keys for logging into virtual machines on Google Cloud Platform. +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://oslogin.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://oslogin.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://oslogin.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) CreateSshPublicKey(ctx context.Context, req *osloginpb.CreateSshPublicKeyRequest, opts ...gax.CallOption) (*commonpb.SshPublicKey, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -452,3 +601,414 @@ func (c *gRPCClient) UpdateSshPublicKey(ctx context.Context, req *osloginpb.Upda } return resp, nil } + +// CreateSshPublicKey create an SSH public key +func (c *restClient) CreateSshPublicKey(ctx context.Context, req *osloginpb.CreateSshPublicKeyRequest, opts ...gax.CallOption) (*commonpb.SshPublicKey, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetSshPublicKey() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/sshPublicKeys", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateSshPublicKey[0:len((*c.CallOptions).CreateSshPublicKey):len((*c.CallOptions).CreateSshPublicKey)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &commonpb.SshPublicKey{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeletePosixAccount deletes a POSIX account. +func (c *restClient) DeletePosixAccount(ctx context.Context, req *osloginpb.DeletePosixAccountRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// DeleteSshPublicKey deletes an SSH public key. +func (c *restClient) DeleteSshPublicKey(ctx context.Context, req *osloginpb.DeleteSshPublicKeyRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetLoginProfile retrieves the profile information used for logging in to a virtual machine +// on Google Compute Engine. +func (c *restClient) GetLoginProfile(ctx context.Context, req *osloginpb.GetLoginProfileRequest, opts ...gax.CallOption) (*osloginpb.LoginProfile, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/loginProfile", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetProjectId() != "" { + params.Add("projectId", fmt.Sprintf("%v", req.GetProjectId())) + } + if req.GetSystemId() != "" { + params.Add("systemId", fmt.Sprintf("%v", req.GetSystemId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLoginProfile[0:len((*c.CallOptions).GetLoginProfile):len((*c.CallOptions).GetLoginProfile)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &osloginpb.LoginProfile{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetSshPublicKey retrieves an SSH public key. +func (c *restClient) GetSshPublicKey(ctx context.Context, req *osloginpb.GetSshPublicKeyRequest, opts ...gax.CallOption) (*commonpb.SshPublicKey, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetSshPublicKey[0:len((*c.CallOptions).GetSshPublicKey):len((*c.CallOptions).GetSshPublicKey)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &commonpb.SshPublicKey{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ImportSshPublicKey adds an SSH public key and returns the profile information. Default POSIX +// account information is set when no username and UID exist as part of the +// login profile. +func (c *restClient) ImportSshPublicKey(ctx context.Context, req *osloginpb.ImportSshPublicKeyRequest, opts ...gax.CallOption) (*osloginpb.ImportSshPublicKeyResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetSshPublicKey() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:importSshPublicKey", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetProjectId() != "" { + params.Add("projectId", fmt.Sprintf("%v", req.GetProjectId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).ImportSshPublicKey[0:len((*c.CallOptions).ImportSshPublicKey):len((*c.CallOptions).ImportSshPublicKey)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &osloginpb.ImportSshPublicKeyResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateSshPublicKey updates an SSH public key and returns the profile information. This method +// supports patch semantics. +func (c *restClient) UpdateSshPublicKey(ctx context.Context, req *osloginpb.UpdateSshPublicKeyRequest, opts ...gax.CallOption) (*commonpb.SshPublicKey, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetSshPublicKey() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateSshPublicKey[0:len((*c.CallOptions).UpdateSshPublicKey):len((*c.CallOptions).UpdateSshPublicKey)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &commonpb.SshPublicKey{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} diff --git a/oslogin/apiv1/os_login_client_example_test.go b/oslogin/apiv1/os_login_client_example_test.go index e085800dc814..5550bad0eadf 100644 --- a/oslogin/apiv1/os_login_client_example_test.go +++ b/oslogin/apiv1/os_login_client_example_test.go @@ -40,6 +40,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := oslogin.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_CreateSshPublicKey() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/oslogin/apiv1/osloginpb/oslogin.pb.go b/oslogin/apiv1/osloginpb/oslogin.pb.go index b3455d50931c..a8c8b5f1ba99 100644 --- a/oslogin/apiv1/osloginpb/oslogin.pb.go +++ b/oslogin/apiv1/osloginpb/oslogin.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/oslogin/v1/oslogin.proto package osloginpb diff --git a/oslogin/apiv1beta/os_login_client.go b/oslogin/apiv1beta/os_login_client.go index c914a33ab578..73ea14b2a5ee 100644 --- a/oslogin/apiv1beta/os_login_client.go +++ b/oslogin/apiv1beta/os_login_client.go @@ -617,6 +617,11 @@ func (c *restClient) CreateSshPublicKey(ctx context.Context, req *osloginpb.Crea } baseUrl.Path += fmt.Sprintf("/v1beta/%v/sshPublicKeys", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -670,6 +675,11 @@ func (c *restClient) DeletePosixAccount(ctx context.Context, req *osloginpb.Dele } baseUrl.Path += fmt.Sprintf("/v1beta/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -705,6 +715,11 @@ func (c *restClient) DeleteSshPublicKey(ctx context.Context, req *osloginpb.Dele } baseUrl.Path += fmt.Sprintf("/v1beta/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -742,6 +757,7 @@ func (c *restClient) GetLoginProfile(ctx context.Context, req *osloginpb.GetLogi baseUrl.Path += fmt.Sprintf("/v1beta/%v/loginProfile", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetProjectId() != "" { params.Add("projectId", fmt.Sprintf("%v", req.GetProjectId())) } @@ -807,6 +823,11 @@ func (c *restClient) GetSshPublicKey(ctx context.Context, req *osloginpb.GetSshP } baseUrl.Path += fmt.Sprintf("/v1beta/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -870,6 +891,7 @@ func (c *restClient) ImportSshPublicKey(ctx context.Context, req *osloginpb.Impo baseUrl.Path += fmt.Sprintf("/v1beta/%v:importSshPublicKey", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetProjectId() != "" { params.Add("projectId", fmt.Sprintf("%v", req.GetProjectId())) } @@ -941,6 +963,7 @@ func (c *restClient) UpdateSshPublicKey(ctx context.Context, req *osloginpb.Upda baseUrl.Path += fmt.Sprintf("/v1beta/%v", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { diff --git a/oslogin/apiv1beta/osloginpb/oslogin.pb.go b/oslogin/apiv1beta/osloginpb/oslogin.pb.go index f0c6020362c1..8586ddcd845b 100644 --- a/oslogin/apiv1beta/osloginpb/oslogin.pb.go +++ b/oslogin/apiv1beta/osloginpb/oslogin.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/oslogin/v1beta/oslogin.proto package osloginpb @@ -677,7 +677,6 @@ type SecurityKey struct { // The FIDO protocol type used to register this credential. // // Types that are assignable to ProtocolType: - // // *SecurityKey_UniversalTwoFactor // *SecurityKey_WebAuthn ProtocolType isSecurityKey_ProtocolType `protobuf_oneof:"protocol_type"` diff --git a/phishingprotection/apiv1beta1/phishing_protection_service_v1_beta1_client.go b/phishingprotection/apiv1beta1/phishing_protection_service_v1_beta1_client.go index 8addc31925b5..5dcf6c828d79 100644 --- a/phishingprotection/apiv1beta1/phishing_protection_service_v1_beta1_client.go +++ b/phishingprotection/apiv1beta1/phishing_protection_service_v1_beta1_client.go @@ -314,6 +314,11 @@ func (c *phishingProtectionServiceV1Beta1RESTClient) ReportPhishing(ctx context. } baseUrl.Path += fmt.Sprintf("/v1beta1/%v/phishing:report", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) diff --git a/phishingprotection/apiv1beta1/phishingprotectionpb/phishingprotection.pb.go b/phishingprotection/apiv1beta1/phishingprotectionpb/phishingprotection.pb.go index e034e224d29b..2efc3933dbd4 100644 --- a/phishingprotection/apiv1beta1/phishingprotectionpb/phishingprotection.pb.go +++ b/phishingprotection/apiv1beta1/phishingprotectionpb/phishingprotection.pb.go @@ -15,8 +15,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/phishingprotection/v1beta1/phishingprotection.proto package phishingprotectionpb diff --git a/policytroubleshooter/apiv1/doc.go b/policytroubleshooter/apiv1/doc.go index cec2cc1e3a67..89a198f0b475 100644 --- a/policytroubleshooter/apiv1/doc.go +++ b/policytroubleshooter/apiv1/doc.go @@ -78,6 +78,8 @@ package policytroubleshooter // import "cloud.google.com/go/policytroubleshooter import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -166,3 +168,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/policytroubleshooter/apiv1/gapic_metadata.json b/policytroubleshooter/apiv1/gapic_metadata.json index d2e85d113643..b828aa541766 100644 --- a/policytroubleshooter/apiv1/gapic_metadata.json +++ b/policytroubleshooter/apiv1/gapic_metadata.json @@ -16,6 +16,16 @@ ] } } + }, + "rest": { + "libraryClient": "IamCheckerClient", + "rpcs": { + "TroubleshootIamPolicy": { + "methods": [ + "TroubleshootIamPolicy" + ] + } + } } } } diff --git a/policytroubleshooter/apiv1/iam_checker_client.go b/policytroubleshooter/apiv1/iam_checker_client.go index c99cf002738b..60e57c2c1885 100644 --- a/policytroubleshooter/apiv1/iam_checker_client.go +++ b/policytroubleshooter/apiv1/iam_checker_client.go @@ -17,17 +17,25 @@ package policytroubleshooter import ( + "bytes" "context" + "fmt" + "io/ioutil" "math" + "net/http" + "net/url" "time" policytroubleshooterpb "cloud.google.com/go/policytroubleshooter/apiv1/policytroubleshooterpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" ) var newIamCheckerClientHook clientHook @@ -55,6 +63,12 @@ func defaultIamCheckerCallOptions() *IamCheckerCallOptions { } } +func defaultIamCheckerRESTCallOptions() *IamCheckerCallOptions { + return &IamCheckerCallOptions{ + TroubleshootIamPolicy: []gax.CallOption{}, + } +} + // internalIamCheckerClient is an interface that defines the methods available from Policy Troubleshooter API. type internalIamCheckerClient interface { Close() error @@ -189,6 +203,76 @@ func (c *iamCheckerGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type iamCheckerRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing IamCheckerClient + CallOptions **IamCheckerCallOptions +} + +// NewIamCheckerRESTClient creates a new iam checker rest client. +// +// IAM Policy Troubleshooter service. +// +// This service helps you troubleshoot access issues for Google Cloud resources. +func NewIamCheckerRESTClient(ctx context.Context, opts ...option.ClientOption) (*IamCheckerClient, error) { + clientOpts := append(defaultIamCheckerRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultIamCheckerRESTCallOptions() + c := &iamCheckerRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &IamCheckerClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultIamCheckerRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://policytroubleshooter.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://policytroubleshooter.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://policytroubleshooter.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *iamCheckerRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *iamCheckerRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *iamCheckerRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *iamCheckerGRPCClient) TroubleshootIamPolicy(ctx context.Context, req *policytroubleshooterpb.TroubleshootIamPolicyRequest, opts ...gax.CallOption) (*policytroubleshooterpb.TroubleshootIamPolicyResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) @@ -208,3 +292,66 @@ func (c *iamCheckerGRPCClient) TroubleshootIamPolicy(ctx context.Context, req *p } return resp, nil } + +// TroubleshootIamPolicy checks whether a member has a specific permission for a specific resource, +// and explains why the member does or does not have that permission. +func (c *iamCheckerRESTClient) TroubleshootIamPolicy(ctx context.Context, req *policytroubleshooterpb.TroubleshootIamPolicyRequest, opts ...gax.CallOption) (*policytroubleshooterpb.TroubleshootIamPolicyResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/iam:troubleshoot") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).TroubleshootIamPolicy[0:len((*c.CallOptions).TroubleshootIamPolicy):len((*c.CallOptions).TroubleshootIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &policytroubleshooterpb.TroubleshootIamPolicyResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} diff --git a/policytroubleshooter/apiv1/iam_checker_client_example_test.go b/policytroubleshooter/apiv1/iam_checker_client_example_test.go index fcbcaa44b6eb..4c859a70a62d 100644 --- a/policytroubleshooter/apiv1/iam_checker_client_example_test.go +++ b/policytroubleshooter/apiv1/iam_checker_client_example_test.go @@ -40,6 +40,23 @@ func ExampleNewIamCheckerClient() { _ = c } +func ExampleNewIamCheckerRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := policytroubleshooter.NewIamCheckerRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleIamCheckerClient_TroubleshootIamPolicy() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/policytroubleshooter/apiv1/policytroubleshooterpb/checker.pb.go b/policytroubleshooter/apiv1/policytroubleshooterpb/checker.pb.go index 05785845595e..8d16e42aaff0 100644 --- a/policytroubleshooter/apiv1/policytroubleshooterpb/checker.pb.go +++ b/policytroubleshooter/apiv1/policytroubleshooterpb/checker.pb.go @@ -15,8 +15,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/policytroubleshooter/v1/checker.proto package policytroubleshooterpb diff --git a/policytroubleshooter/apiv1/policytroubleshooterpb/explanations.pb.go b/policytroubleshooter/apiv1/policytroubleshooterpb/explanations.pb.go index 885765d06f26..e9a6b5a7be3d 100644 --- a/policytroubleshooter/apiv1/policytroubleshooterpb/explanations.pb.go +++ b/policytroubleshooter/apiv1/policytroubleshooterpb/explanations.pb.go @@ -15,8 +15,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/policytroubleshooter/v1/explanations.proto package policytroubleshooterpb @@ -224,9 +224,9 @@ const ( // The binding includes the member. The member can be included directly // or indirectly. For example: // - // - A member is included directly if that member is listed in the binding. - // - A member is included indirectly if that member is in a Google group or - // G Suite domain that is listed in the binding. + // * A member is included directly if that member is listed in the binding. + // * A member is included indirectly if that member is in a Google group or + // G Suite domain that is listed in the binding. BindingExplanation_MEMBERSHIP_INCLUDED BindingExplanation_Membership = 1 // The binding does not include the member. BindingExplanation_MEMBERSHIP_NOT_INCLUDED BindingExplanation_Membership = 2 diff --git a/privatecatalog/apiv1beta1/private_catalog_client.go b/privatecatalog/apiv1beta1/private_catalog_client.go index d8e09b78e154..3d69255d7f46 100644 --- a/privatecatalog/apiv1beta1/private_catalog_client.go +++ b/privatecatalog/apiv1beta1/private_catalog_client.go @@ -505,6 +505,7 @@ func (c *restClient) SearchCatalogs(ctx context.Context, req *privatecatalogpb.S baseUrl.Path += fmt.Sprintf("/v1beta1/%v/catalogs:search", req.GetResource()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -596,6 +597,7 @@ func (c *restClient) SearchProducts(ctx context.Context, req *privatecatalogpb.S baseUrl.Path += fmt.Sprintf("/v1beta1/%v/products:search", req.GetResource()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -687,6 +689,7 @@ func (c *restClient) SearchVersions(ctx context.Context, req *privatecatalogpb.S baseUrl.Path += fmt.Sprintf("/v1beta1/%v/versions:search", req.GetResource()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } diff --git a/privatecatalog/apiv1beta1/privatecatalogpb/private_catalog.pb.go b/privatecatalog/apiv1beta1/privatecatalogpb/private_catalog.pb.go index 89ae5ac57bcb..603a20945b01 100644 --- a/privatecatalog/apiv1beta1/privatecatalogpb/private_catalog.pb.go +++ b/privatecatalog/apiv1beta1/privatecatalogpb/private_catalog.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/privatecatalog/v1beta1/private_catalog.proto package privatecatalogpb @@ -642,45 +642,43 @@ type Product struct { // "$schema": http://json-schema.org/draft-04/schema# // type: object // properties: - // - // name: - // type: string - // minLength: 1 - // maxLength: 64 - // description: - // type: string - // minLength: 1 - // maxLength: 2048 - // tagline: - // type: string - // minLength: 1 - // maxLength: 100 - // support_info: - // type: string - // minLength: 1 - // maxLength: 2048 - // creator: - // type: string - // minLength: 1 - // maxLength: 100 - // documentations: - // type: array - // items: - // type: object - // properties: - // url: - // type: string - // pattern: - // "^(https?)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]" - // title: - // type: string - // minLength: 1 - // maxLength: 64 - // description: - // type: string - // minLength: 1 - // maxLength: 2048 - // + // name: + // type: string + // minLength: 1 + // maxLength: 64 + // description: + // type: string + // minLength: 1 + // maxLength: 2048 + // tagline: + // type: string + // minLength: 1 + // maxLength: 100 + // support_info: + // type: string + // minLength: 1 + // maxLength: 2048 + // creator: + // type: string + // minLength: 1 + // maxLength: 100 + // documentations: + // type: array + // items: + // type: object + // properties: + // url: + // type: string + // pattern: + // "^(https?)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]" + // title: + // type: string + // minLength: 1 + // maxLength: 64 + // description: + // type: string + // minLength: 1 + // maxLength: 2048 // required: // - name // - description @@ -695,49 +693,47 @@ type Product struct { // "$schema": http://json-schema.org/draft-04/schema# // type: object // properties: - // - // name: - // type: string - // minLength: 1 - // maxLength: 64 - // description: - // type: string - // minLength: 1 - // maxLength: 2048 - // tagline: - // type: string - // minLength: 1 - // maxLength: 100 - // support_info: - // type: string - // minLength: 1 - // maxLength: 2048 - // creator: - // type: string - // minLength: 1 - // maxLength: 100 - // documentations: - // type: array - // items: - // type: object - // properties: - // url: - // type: string - // pattern: - // "^(https?)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]" - // title: - // type: string - // minLength: 1 - // maxLength: 64 - // description: - // type: string - // minLength: 1 - // maxLength: 2048 - // signup_url: - // type: string - // pattern: - // "^(https?)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]" - // + // name: + // type: string + // minLength: 1 + // maxLength: 64 + // description: + // type: string + // minLength: 1 + // maxLength: 2048 + // tagline: + // type: string + // minLength: 1 + // maxLength: 100 + // support_info: + // type: string + // minLength: 1 + // maxLength: 2048 + // creator: + // type: string + // minLength: 1 + // maxLength: 100 + // documentations: + // type: array + // items: + // type: object + // properties: + // url: + // type: string + // pattern: + // "^(https?)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]" + // title: + // type: string + // minLength: 1 + // maxLength: 64 + // description: + // type: string + // minLength: 1 + // maxLength: 2048 + // signup_url: + // type: string + // pattern: + // "^(https?)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]" // required: // - name // - description @@ -753,45 +749,43 @@ type Product struct { // "$schema": http://json-schema.org/draft-04/schema# // type: object // properties: - // - // name: - // type: string - // minLength: 1 - // maxLength: 64 - // description: - // type: string - // minLength: 1 - // maxLength: 2048 - // tagline: - // type: string - // minLength: 1 - // maxLength: 100 - // support_info: - // type: string - // minLength: 1 - // maxLength: 2048 - // creator: - // type: string - // minLength: 1 - // maxLength: 100 - // documentations: - // type: array - // items: - // type: object - // properties: - // url: - // type: string - // pattern: - // "^(https?)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]" - // title: - // type: string - // minLength: 1 - // maxLength: 64 - // description: - // type: string - // minLength: 1 - // maxLength: 2048 - // + // name: + // type: string + // minLength: 1 + // maxLength: 64 + // description: + // type: string + // minLength: 1 + // maxLength: 2048 + // tagline: + // type: string + // minLength: 1 + // maxLength: 100 + // support_info: + // type: string + // minLength: 1 + // maxLength: 2048 + // creator: + // type: string + // minLength: 1 + // maxLength: 100 + // documentations: + // type: array + // items: + // type: object + // properties: + // url: + // type: string + // pattern: + // "^(https?)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]" + // title: + // type: string + // minLength: 1 + // maxLength: 64 + // description: + // type: string + // minLength: 1 + // maxLength: 2048 // required: // - name // - description @@ -909,7 +903,6 @@ type AssetReference struct { // The destination of the asset. // // Types that are assignable to Source: - // // *AssetReference_Asset // *AssetReference_GcsPath // *AssetReference_GitSource @@ -1212,7 +1205,6 @@ type GitSource struct { // commit SHA, or any Git ref. // // Types that are assignable to Ref: - // // *GitSource_Commit // *GitSource_Branch // *GitSource_Tag diff --git a/pubsub/apiv1/doc.go b/pubsub/apiv1/doc.go index 026c28260c6b..cd1688dab2c3 100644 --- a/pubsub/apiv1/doc.go +++ b/pubsub/apiv1/doc.go @@ -81,6 +81,8 @@ package pubsub // import "cloud.google.com/go/pubsub/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -170,3 +172,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/pubsub/apiv1/gapic_metadata.json b/pubsub/apiv1/gapic_metadata.json index 64b2999668a6..2446ebbab3c7 100644 --- a/pubsub/apiv1/gapic_metadata.json +++ b/pubsub/apiv1/gapic_metadata.json @@ -71,6 +71,71 @@ ] } } + }, + "rest": { + "libraryClient": "PublisherClient", + "rpcs": { + "CreateTopic": { + "methods": [ + "CreateTopic" + ] + }, + "DeleteTopic": { + "methods": [ + "DeleteTopic" + ] + }, + "DetachSubscription": { + "methods": [ + "DetachSubscription" + ] + }, + "GetIamPolicy": { + "methods": [ + "GetIamPolicy" + ] + }, + "GetTopic": { + "methods": [ + "GetTopic" + ] + }, + "ListTopicSnapshots": { + "methods": [ + "ListTopicSnapshots" + ] + }, + "ListTopicSubscriptions": { + "methods": [ + "ListTopicSubscriptions" + ] + }, + "ListTopics": { + "methods": [ + "ListTopics" + ] + }, + "Publish": { + "methods": [ + "Publish" + ] + }, + "SetIamPolicy": { + "methods": [ + "SetIamPolicy" + ] + }, + "TestIamPermissions": { + "methods": [ + "TestIamPermissions" + ] + }, + "UpdateTopic": { + "methods": [ + "UpdateTopic" + ] + } + } } } }, @@ -125,6 +190,56 @@ ] } } + }, + "rest": { + "libraryClient": "SchemaClient", + "rpcs": { + "CreateSchema": { + "methods": [ + "CreateSchema" + ] + }, + "DeleteSchema": { + "methods": [ + "DeleteSchema" + ] + }, + "GetIamPolicy": { + "methods": [ + "GetIamPolicy" + ] + }, + "GetSchema": { + "methods": [ + "GetSchema" + ] + }, + "ListSchemas": { + "methods": [ + "ListSchemas" + ] + }, + "SetIamPolicy": { + "methods": [ + "SetIamPolicy" + ] + }, + "TestIamPermissions": { + "methods": [ + "TestIamPermissions" + ] + }, + "ValidateMessage": { + "methods": [ + "ValidateMessage" + ] + }, + "ValidateSchema": { + "methods": [ + "ValidateSchema" + ] + } + } } } }, @@ -229,6 +344,106 @@ ] } } + }, + "rest": { + "libraryClient": "SubscriberClient", + "rpcs": { + "Acknowledge": { + "methods": [ + "Acknowledge" + ] + }, + "CreateSnapshot": { + "methods": [ + "CreateSnapshot" + ] + }, + "CreateSubscription": { + "methods": [ + "CreateSubscription" + ] + }, + "DeleteSnapshot": { + "methods": [ + "DeleteSnapshot" + ] + }, + "DeleteSubscription": { + "methods": [ + "DeleteSubscription" + ] + }, + "GetIamPolicy": { + "methods": [ + "GetIamPolicy" + ] + }, + "GetSnapshot": { + "methods": [ + "GetSnapshot" + ] + }, + "GetSubscription": { + "methods": [ + "GetSubscription" + ] + }, + "ListSnapshots": { + "methods": [ + "ListSnapshots" + ] + }, + "ListSubscriptions": { + "methods": [ + "ListSubscriptions" + ] + }, + "ModifyAckDeadline": { + "methods": [ + "ModifyAckDeadline" + ] + }, + "ModifyPushConfig": { + "methods": [ + "ModifyPushConfig" + ] + }, + "Pull": { + "methods": [ + "Pull" + ] + }, + "Seek": { + "methods": [ + "Seek" + ] + }, + "SetIamPolicy": { + "methods": [ + "SetIamPolicy" + ] + }, + "StreamingPull": { + "methods": [ + "StreamingPull" + ] + }, + "TestIamPermissions": { + "methods": [ + "TestIamPermissions" + ] + }, + "UpdateSnapshot": { + "methods": [ + "UpdateSnapshot" + ] + }, + "UpdateSubscription": { + "methods": [ + "UpdateSubscription" + ] + } + } } } } diff --git a/pubsub/apiv1/publisher_client.go b/pubsub/apiv1/publisher_client.go index db2c24243de4..84609843dbae 100644 --- a/pubsub/apiv1/publisher_client.go +++ b/pubsub/apiv1/publisher_client.go @@ -17,22 +17,28 @@ package pubsub import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" pubsubpb "cloud.google.com/go/pubsub/apiv1/pubsubpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" iampb "google.golang.org/genproto/googleapis/iam/v1" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -187,6 +193,118 @@ func defaultPublisherCallOptions() *PublisherCallOptions { } } +func defaultPublisherRESTCallOptions() *PublisherCallOptions { + return &PublisherCallOptions{ + CreateTopic: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UpdateTopic: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + Publish: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusConflict, + 499, + http.StatusInternalServerError, + http.StatusTooManyRequests, + http.StatusInternalServerError, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + GetTopic: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusInternalServerError, + http.StatusConflict, + http.StatusServiceUnavailable) + }), + }, + ListTopics: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusInternalServerError, + http.StatusConflict, + http.StatusServiceUnavailable) + }), + }, + ListTopicSubscriptions: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusInternalServerError, + http.StatusConflict, + http.StatusServiceUnavailable) + }), + }, + ListTopicSnapshots: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusInternalServerError, + http.StatusConflict, + http.StatusServiceUnavailable) + }), + }, + DeleteTopic: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DetachSubscription: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetIamPolicy: []gax.CallOption{}, + SetIamPolicy: []gax.CallOption{}, + TestIamPermissions: []gax.CallOption{}, + } +} + // internalPublisherClient is an interface that defines the methods available from Cloud Pub/Sub API. type internalPublisherClient interface { Close() error @@ -412,6 +530,75 @@ func (c *publisherGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type publisherRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing PublisherClient + CallOptions **PublisherCallOptions +} + +// NewPublisherRESTClient creates a new publisher rest client. +// +// The service that an application uses to manipulate topics, and to send +// messages to a topic. +func NewPublisherRESTClient(ctx context.Context, opts ...option.ClientOption) (*PublisherClient, error) { + clientOpts := append(defaultPublisherRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultPublisherRESTCallOptions() + c := &publisherRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &PublisherClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultPublisherRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://pubsub.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://pubsub.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://pubsub.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *publisherRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *publisherRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *publisherRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *publisherGRPCClient) CreateTopic(ctx context.Context, req *pubsubpb.Topic, opts ...gax.CallOption) (*pubsubpb.Topic, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) @@ -726,6 +913,832 @@ func (c *publisherGRPCClient) TestIamPermissions(ctx context.Context, req *iampb return resp, nil } +// CreateTopic creates the given topic with the given name. See the [resource name rules] +// (https://cloud.google.com/pubsub/docs/admin#resource_names (at https://cloud.google.com/pubsub/docs/admin#resource_names)). +func (c *publisherRESTClient) CreateTopic(ctx context.Context, req *pubsubpb.Topic, opts ...gax.CallOption) (*pubsubpb.Topic, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateTopic[0:len((*c.CallOptions).CreateTopic):len((*c.CallOptions).CreateTopic)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &pubsubpb.Topic{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PUT", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateTopic updates an existing topic. Note that certain properties of a +// topic are not modifiable. +func (c *publisherRESTClient) UpdateTopic(ctx context.Context, req *pubsubpb.UpdateTopicRequest, opts ...gax.CallOption) (*pubsubpb.Topic, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetTopic().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "topic.name", url.QueryEscape(req.GetTopic().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateTopic[0:len((*c.CallOptions).UpdateTopic):len((*c.CallOptions).UpdateTopic)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &pubsubpb.Topic{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// Publish adds one or more messages to the topic. Returns NOT_FOUND if the topic +// does not exist. +func (c *publisherRESTClient) Publish(ctx context.Context, req *pubsubpb.PublishRequest, opts ...gax.CallOption) (*pubsubpb.PublishResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:publish", req.GetTopic()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "topic", url.QueryEscape(req.GetTopic()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).Publish[0:len((*c.CallOptions).Publish):len((*c.CallOptions).Publish)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &pubsubpb.PublishResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetTopic gets the configuration of a topic. +func (c *publisherRESTClient) GetTopic(ctx context.Context, req *pubsubpb.GetTopicRequest, opts ...gax.CallOption) (*pubsubpb.Topic, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetTopic()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "topic", url.QueryEscape(req.GetTopic()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetTopic[0:len((*c.CallOptions).GetTopic):len((*c.CallOptions).GetTopic)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &pubsubpb.Topic{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListTopics lists matching topics. +func (c *publisherRESTClient) ListTopics(ctx context.Context, req *pubsubpb.ListTopicsRequest, opts ...gax.CallOption) *TopicIterator { + it := &TopicIterator{} + req = proto.Clone(req).(*pubsubpb.ListTopicsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*pubsubpb.Topic, string, error) { + resp := &pubsubpb.ListTopicsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/topics", req.GetProject()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetTopics(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// ListTopicSubscriptions lists the names of the attached subscriptions on this topic. +func (c *publisherRESTClient) ListTopicSubscriptions(ctx context.Context, req *pubsubpb.ListTopicSubscriptionsRequest, opts ...gax.CallOption) *StringIterator { + it := &StringIterator{} + req = proto.Clone(req).(*pubsubpb.ListTopicSubscriptionsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]string, string, error) { + resp := &pubsubpb.ListTopicSubscriptionsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/subscriptions", req.GetTopic()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetSubscriptions(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// ListTopicSnapshots lists the names of the snapshots on this topic. Snapshots are used in +// Seek (at https://cloud.google.com/pubsub/docs/replay-overview) operations, +// which allow you to manage message acknowledgments in bulk. That is, you can +// set the acknowledgment state of messages in an existing subscription to the +// state captured by a snapshot. +func (c *publisherRESTClient) ListTopicSnapshots(ctx context.Context, req *pubsubpb.ListTopicSnapshotsRequest, opts ...gax.CallOption) *StringIterator { + it := &StringIterator{} + req = proto.Clone(req).(*pubsubpb.ListTopicSnapshotsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]string, string, error) { + resp := &pubsubpb.ListTopicSnapshotsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/snapshots", req.GetTopic()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetSnapshots(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// DeleteTopic deletes the topic with the given name. Returns NOT_FOUND if the topic +// does not exist. After a topic is deleted, a new topic may be created with +// the same name; this is an entirely new topic with none of the old +// configuration or subscriptions. Existing subscriptions to this topic are +// not deleted, but their topic field is set to _deleted-topic_. +func (c *publisherRESTClient) DeleteTopic(ctx context.Context, req *pubsubpb.DeleteTopicRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetTopic()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "topic", url.QueryEscape(req.GetTopic()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// DetachSubscription detaches a subscription from this topic. All messages retained in the +// subscription are dropped. Subsequent Pull and StreamingPull requests +// will return FAILED_PRECONDITION. If the subscription is a push +// subscription, pushes to the endpoint will stop. +func (c *publisherRESTClient) DetachSubscription(ctx context.Context, req *pubsubpb.DetachSubscriptionRequest, opts ...gax.CallOption) (*pubsubpb.DetachSubscriptionResponse, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:detach", req.GetSubscription()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "subscription", url.QueryEscape(req.GetSubscription()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).DetachSubscription[0:len((*c.CallOptions).DetachSubscription):len((*c.CallOptions).DetachSubscription)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &pubsubpb.DetachSubscriptionResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetIamPolicy gets the access control policy for a resource. Returns an empty policy +// if the resource exists and does not have a policy set. +func (c *publisherRESTClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:getIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetOptions().GetRequestedPolicyVersion() != 0 { + params.Add("options.requestedPolicyVersion", fmt.Sprintf("%v", req.GetOptions().GetRequestedPolicyVersion())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SetIamPolicy sets the access control policy on the specified resource. Replaces +// any existing policy. +// +// Can return NOT_FOUND, INVALID_ARGUMENT, and PERMISSION_DENIED +// errors. +func (c *publisherRESTClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:setIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// TestIamPermissions returns permissions that a caller has on the specified resource. If the +// resource does not exist, this will return an empty set of +// permissions, not a NOT_FOUND error. +// +// Note: This operation is designed to be used for building +// permission-aware UIs and command-line tools, not for authorization +// checking. This operation may “fail open” without warning. +func (c *publisherRESTClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:testIamPermissions", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.TestIamPermissionsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + // StringIterator manages a stream of string. type StringIterator struct { items []string diff --git a/pubsub/apiv1/publisher_client_example_test.go b/pubsub/apiv1/publisher_client_example_test.go index 07695c75f9dd..63f667254a9b 100644 --- a/pubsub/apiv1/publisher_client_example_test.go +++ b/pubsub/apiv1/publisher_client_example_test.go @@ -42,6 +42,23 @@ func ExampleNewPublisherClient() { _ = c } +func ExampleNewPublisherRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := pubsub.NewPublisherRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExamplePublisherClient_CreateTopic() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/pubsub/apiv1/pubsubpb/pubsub.pb.go b/pubsub/apiv1/pubsubpb/pubsub.pb.go index 84fd669008c9..525a73f7d5f5 100644 --- a/pubsub/apiv1/pubsubpb/pubsub.pb.go +++ b/pubsub/apiv1/pubsubpb/pubsub.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/pubsub/v1/pubsub.proto package pubsubpb @@ -1778,7 +1778,6 @@ type PushConfig struct { // authenticated push. // // Types that are assignable to AuthenticationMethod: - // // *PushConfig_OidcToken_ AuthenticationMethod isPushConfig_AuthenticationMethod `protobuf_oneof:"authentication_method"` } @@ -2906,14 +2905,12 @@ type CreateSnapshotRequest struct { Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Required. The subscription whose backlog the snapshot retains. // Specifically, the created snapshot is guaranteed to retain: - // - // (a) The existing backlog on the subscription. More precisely, this is - // defined as the messages in the subscription's backlog that are - // unacknowledged upon the successful completion of the - // `CreateSnapshot` request; as well as: - // (b) Any messages published to the subscription's topic following the - // successful completion of the CreateSnapshot request. - // + // (a) The existing backlog on the subscription. More precisely, this is + // defined as the messages in the subscription's backlog that are + // unacknowledged upon the successful completion of the + // `CreateSnapshot` request; as well as: + // (b) Any messages published to the subscription's topic following the + // successful completion of the CreateSnapshot request. // Format is `projects/{project}/subscriptions/{sub}`. Subscription string `protobuf:"bytes,2,opt,name=subscription,proto3" json:"subscription,omitempty"` // See Creating and @@ -3361,7 +3358,6 @@ type SeekRequest struct { // Required. The subscription to affect. Subscription string `protobuf:"bytes,1,opt,name=subscription,proto3" json:"subscription,omitempty"` // Types that are assignable to Target: - // // *SeekRequest_Time // *SeekRequest_Snapshot Target isSeekRequest_Target `protobuf_oneof:"target"` diff --git a/pubsub/apiv1/pubsubpb/schema.pb.go b/pubsub/apiv1/pubsubpb/schema.pb.go index 814159324a5a..c05e97cbf9ba 100644 --- a/pubsub/apiv1/pubsubpb/schema.pb.go +++ b/pubsub/apiv1/pubsubpb/schema.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/pubsub/v1/schema.proto package pubsubpb @@ -708,7 +708,6 @@ type ValidateMessageRequest struct { // Format is `projects/{project-id}`. Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // Types that are assignable to SchemaSpec: - // // *ValidateMessageRequest_Name // *ValidateMessageRequest_Schema SchemaSpec isValidateMessageRequest_SchemaSpec `protobuf_oneof:"schema_spec"` diff --git a/pubsub/apiv1/schema_client.go b/pubsub/apiv1/schema_client.go index f710c070a796..3f7a3b53576c 100644 --- a/pubsub/apiv1/schema_client.go +++ b/pubsub/apiv1/schema_client.go @@ -17,20 +17,26 @@ package pubsub import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" pubsubpb "cloud.google.com/go/pubsub/apiv1/pubsubpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" iampb "google.golang.org/genproto/googleapis/iam/v1" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -75,6 +81,20 @@ func defaultSchemaCallOptions() *SchemaCallOptions { } } +func defaultSchemaRESTCallOptions() *SchemaCallOptions { + return &SchemaCallOptions{ + CreateSchema: []gax.CallOption{}, + GetSchema: []gax.CallOption{}, + ListSchemas: []gax.CallOption{}, + DeleteSchema: []gax.CallOption{}, + ValidateSchema: []gax.CallOption{}, + ValidateMessage: []gax.CallOption{}, + GetIamPolicy: []gax.CallOption{}, + SetIamPolicy: []gax.CallOption{}, + TestIamPermissions: []gax.CallOption{}, + } +} + // internalSchemaClient is an interface that defines the methods available from Cloud Pub/Sub API. type internalSchemaClient interface { Close() error @@ -266,6 +286,74 @@ func (c *schemaGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type schemaRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing SchemaClient + CallOptions **SchemaCallOptions +} + +// NewSchemaRESTClient creates a new schema service rest client. +// +// Service for doing schema-related operations. +func NewSchemaRESTClient(ctx context.Context, opts ...option.ClientOption) (*SchemaClient, error) { + clientOpts := append(defaultSchemaRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultSchemaRESTCallOptions() + c := &schemaRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &SchemaClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultSchemaRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://pubsub.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://pubsub.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://pubsub.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *schemaRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *schemaRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *schemaRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *schemaGRPCClient) CreateSchema(ctx context.Context, req *pubsubpb.CreateSchemaRequest, opts ...gax.CallOption) (*pubsubpb.Schema, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -443,6 +531,594 @@ func (c *schemaGRPCClient) TestIamPermissions(ctx context.Context, req *iampb.Te return resp, nil } +// CreateSchema creates a schema. +func (c *schemaRESTClient) CreateSchema(ctx context.Context, req *pubsubpb.CreateSchemaRequest, opts ...gax.CallOption) (*pubsubpb.Schema, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetSchema() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/schemas", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetSchemaId() != "" { + params.Add("schemaId", fmt.Sprintf("%v", req.GetSchemaId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateSchema[0:len((*c.CallOptions).CreateSchema):len((*c.CallOptions).CreateSchema)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &pubsubpb.Schema{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetSchema gets a schema. +func (c *schemaRESTClient) GetSchema(ctx context.Context, req *pubsubpb.GetSchemaRequest, opts ...gax.CallOption) (*pubsubpb.Schema, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetView() != 0 { + params.Add("view", fmt.Sprintf("%v", req.GetView())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetSchema[0:len((*c.CallOptions).GetSchema):len((*c.CallOptions).GetSchema)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &pubsubpb.Schema{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListSchemas lists schemas in a project. +func (c *schemaRESTClient) ListSchemas(ctx context.Context, req *pubsubpb.ListSchemasRequest, opts ...gax.CallOption) *SchemaIterator { + it := &SchemaIterator{} + req = proto.Clone(req).(*pubsubpb.ListSchemasRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*pubsubpb.Schema, string, error) { + resp := &pubsubpb.ListSchemasResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/schemas", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + if req.GetView() != 0 { + params.Add("view", fmt.Sprintf("%v", req.GetView())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetSchemas(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// DeleteSchema deletes a schema. +func (c *schemaRESTClient) DeleteSchema(ctx context.Context, req *pubsubpb.DeleteSchemaRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// ValidateSchema validates a schema. +func (c *schemaRESTClient) ValidateSchema(ctx context.Context, req *pubsubpb.ValidateSchemaRequest, opts ...gax.CallOption) (*pubsubpb.ValidateSchemaResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/schemas:validate", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).ValidateSchema[0:len((*c.CallOptions).ValidateSchema):len((*c.CallOptions).ValidateSchema)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &pubsubpb.ValidateSchemaResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ValidateMessage validates a message against a schema. +func (c *schemaRESTClient) ValidateMessage(ctx context.Context, req *pubsubpb.ValidateMessageRequest, opts ...gax.CallOption) (*pubsubpb.ValidateMessageResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/schemas:validateMessage", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).ValidateMessage[0:len((*c.CallOptions).ValidateMessage):len((*c.CallOptions).ValidateMessage)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &pubsubpb.ValidateMessageResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetIamPolicy gets the access control policy for a resource. Returns an empty policy +// if the resource exists and does not have a policy set. +func (c *schemaRESTClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:getIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetOptions().GetRequestedPolicyVersion() != 0 { + params.Add("options.requestedPolicyVersion", fmt.Sprintf("%v", req.GetOptions().GetRequestedPolicyVersion())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SetIamPolicy sets the access control policy on the specified resource. Replaces +// any existing policy. +// +// Can return NOT_FOUND, INVALID_ARGUMENT, and PERMISSION_DENIED +// errors. +func (c *schemaRESTClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:setIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// TestIamPermissions returns permissions that a caller has on the specified resource. If the +// resource does not exist, this will return an empty set of +// permissions, not a NOT_FOUND error. +// +// Note: This operation is designed to be used for building +// permission-aware UIs and command-line tools, not for authorization +// checking. This operation may “fail open” without warning. +func (c *schemaRESTClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:testIamPermissions", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.TestIamPermissionsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + // SchemaIterator manages a stream of *pubsubpb.Schema. type SchemaIterator struct { items []*pubsubpb.Schema diff --git a/pubsub/apiv1/schema_client_example_test.go b/pubsub/apiv1/schema_client_example_test.go index 6ac595f8c9da..774dcd3a1ce8 100644 --- a/pubsub/apiv1/schema_client_example_test.go +++ b/pubsub/apiv1/schema_client_example_test.go @@ -42,6 +42,23 @@ func ExampleNewSchemaClient() { _ = c } +func ExampleNewSchemaRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := pubsub.NewSchemaRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleSchemaClient_CreateSchema() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/pubsub/apiv1/subscriber_client.go b/pubsub/apiv1/subscriber_client.go index 60c8371488a7..9c17f736366e 100644 --- a/pubsub/apiv1/subscriber_client.go +++ b/pubsub/apiv1/subscriber_client.go @@ -17,22 +17,28 @@ package pubsub import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" pubsubpb "cloud.google.com/go/pubsub/apiv1/pubsubpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" iampb "google.golang.org/genproto/googleapis/iam/v1" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -275,6 +281,192 @@ func defaultSubscriberCallOptions() *SubscriberCallOptions { } } +func defaultSubscriberRESTCallOptions() *SubscriberCallOptions { + return &SubscriberCallOptions{ + CreateSubscription: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusInternalServerError, + http.StatusConflict, + http.StatusServiceUnavailable) + }), + }, + GetSubscription: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusInternalServerError, + http.StatusConflict, + http.StatusServiceUnavailable) + }), + }, + UpdateSubscription: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListSubscriptions: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusInternalServerError, + http.StatusConflict, + http.StatusServiceUnavailable) + }), + }, + DeleteSubscription: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ModifyAckDeadline: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + Acknowledge: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + Pull: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusInternalServerError, + http.StatusConflict, + http.StatusServiceUnavailable) + }), + }, + StreamingPull: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusTooManyRequests, + http.StatusConflict, + http.StatusInternalServerError, + http.StatusServiceUnavailable) + }), + }, + ModifyPushConfig: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetSnapshot: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusInternalServerError, + http.StatusConflict, + http.StatusServiceUnavailable) + }), + }, + ListSnapshots: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusInternalServerError, + http.StatusConflict, + http.StatusServiceUnavailable) + }), + }, + CreateSnapshot: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UpdateSnapshot: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeleteSnapshot: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + Seek: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusInternalServerError, + http.StatusConflict, + http.StatusServiceUnavailable) + }), + }, + GetIamPolicy: []gax.CallOption{}, + SetIamPolicy: []gax.CallOption{}, + TestIamPermissions: []gax.CallOption{}, + } +} + // internalSubscriberClient is an interface that defines the methods available from Cloud Pub/Sub API. type internalSubscriberClient interface { Close() error @@ -412,6 +604,8 @@ func (c *SubscriberClient) Pull(ctx context.Context, req *pubsubpb.PullRequest, // reassign server-side resources, in which case, the client should // re-establish the stream. Flow control can be achieved by configuring the // underlying RPC channel. +// +// This method is not supported for the REST transport. func (c *SubscriberClient) StreamingPull(ctx context.Context, opts ...gax.CallOption) (pubsubpb.Subscriber_StreamingPullClient, error) { return c.internalClient.StreamingPull(ctx, opts...) } @@ -609,6 +803,76 @@ func (c *subscriberGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type subscriberRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing SubscriberClient + CallOptions **SubscriberCallOptions +} + +// NewSubscriberRESTClient creates a new subscriber rest client. +// +// The service that an application uses to manipulate subscriptions and to +// consume messages from a subscription via the Pull method or by +// establishing a bi-directional stream using the StreamingPull method. +func NewSubscriberRESTClient(ctx context.Context, opts ...option.ClientOption) (*SubscriberClient, error) { + clientOpts := append(defaultSubscriberRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultSubscriberRESTCallOptions() + c := &subscriberRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &SubscriberClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultSubscriberRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://pubsub.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://pubsub.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://pubsub.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *subscriberRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *subscriberRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *subscriberRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *subscriberGRPCClient) CreateSubscription(ctx context.Context, req *pubsubpb.Subscription, opts ...gax.CallOption) (*pubsubpb.Subscription, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) @@ -1031,6 +1295,1186 @@ func (c *subscriberGRPCClient) TestIamPermissions(ctx context.Context, req *iamp return resp, nil } +// CreateSubscription creates a subscription to a given topic. See the [resource name rules] +// (https://cloud.google.com/pubsub/docs/admin#resource_names (at https://cloud.google.com/pubsub/docs/admin#resource_names)). +// If the subscription already exists, returns ALREADY_EXISTS. +// If the corresponding topic doesn’t exist, returns NOT_FOUND. +// +// If the name is not provided in the request, the server will assign a random +// name for this subscription on the same project as the topic, conforming +// to the [resource name format] +// (https://cloud.google.com/pubsub/docs/admin#resource_names (at https://cloud.google.com/pubsub/docs/admin#resource_names)). The generated +// name is populated in the returned Subscription object. Note that for REST +// API requests, you must specify a name in the request. +func (c *subscriberRESTClient) CreateSubscription(ctx context.Context, req *pubsubpb.Subscription, opts ...gax.CallOption) (*pubsubpb.Subscription, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateSubscription[0:len((*c.CallOptions).CreateSubscription):len((*c.CallOptions).CreateSubscription)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &pubsubpb.Subscription{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PUT", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetSubscription gets the configuration details of a subscription. +func (c *subscriberRESTClient) GetSubscription(ctx context.Context, req *pubsubpb.GetSubscriptionRequest, opts ...gax.CallOption) (*pubsubpb.Subscription, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetSubscription()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "subscription", url.QueryEscape(req.GetSubscription()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetSubscription[0:len((*c.CallOptions).GetSubscription):len((*c.CallOptions).GetSubscription)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &pubsubpb.Subscription{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateSubscription updates an existing subscription. Note that certain properties of a +// subscription, such as its topic, are not modifiable. +func (c *subscriberRESTClient) UpdateSubscription(ctx context.Context, req *pubsubpb.UpdateSubscriptionRequest, opts ...gax.CallOption) (*pubsubpb.Subscription, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetSubscription().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "subscription.name", url.QueryEscape(req.GetSubscription().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateSubscription[0:len((*c.CallOptions).UpdateSubscription):len((*c.CallOptions).UpdateSubscription)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &pubsubpb.Subscription{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListSubscriptions lists matching subscriptions. +func (c *subscriberRESTClient) ListSubscriptions(ctx context.Context, req *pubsubpb.ListSubscriptionsRequest, opts ...gax.CallOption) *SubscriptionIterator { + it := &SubscriptionIterator{} + req = proto.Clone(req).(*pubsubpb.ListSubscriptionsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*pubsubpb.Subscription, string, error) { + resp := &pubsubpb.ListSubscriptionsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/subscriptions", req.GetProject()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetSubscriptions(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// DeleteSubscription deletes an existing subscription. All messages retained in the subscription +// are immediately dropped. Calls to Pull after deletion will return +// NOT_FOUND. After a subscription is deleted, a new one may be created with +// the same name, but the new one has no association with the old +// subscription or its topic unless the same topic is specified. +func (c *subscriberRESTClient) DeleteSubscription(ctx context.Context, req *pubsubpb.DeleteSubscriptionRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetSubscription()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "subscription", url.QueryEscape(req.GetSubscription()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// ModifyAckDeadline modifies the ack deadline for a specific message. This method is useful +// to indicate that more time is needed to process a message by the +// subscriber, or to make the message available for redelivery if the +// processing was interrupted. Note that this does not modify the +// subscription-level ackDeadlineSeconds used for subsequent messages. +func (c *subscriberRESTClient) ModifyAckDeadline(ctx context.Context, req *pubsubpb.ModifyAckDeadlineRequest, opts ...gax.CallOption) error { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:modifyAckDeadline", req.GetSubscription()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "subscription", url.QueryEscape(req.GetSubscription()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// Acknowledge acknowledges the messages associated with the ack_ids in the +// AcknowledgeRequest. The Pub/Sub system can remove the relevant messages +// from the subscription. +// +// Acknowledging a message whose ack deadline has expired may succeed, +// but such a message may be redelivered later. Acknowledging a message more +// than once will not result in an error. +func (c *subscriberRESTClient) Acknowledge(ctx context.Context, req *pubsubpb.AcknowledgeRequest, opts ...gax.CallOption) error { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:acknowledge", req.GetSubscription()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "subscription", url.QueryEscape(req.GetSubscription()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// Pull pulls messages from the server. The server may return UNAVAILABLE if +// there are too many concurrent pull requests pending for the given +// subscription. +func (c *subscriberRESTClient) Pull(ctx context.Context, req *pubsubpb.PullRequest, opts ...gax.CallOption) (*pubsubpb.PullResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:pull", req.GetSubscription()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "subscription", url.QueryEscape(req.GetSubscription()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).Pull[0:len((*c.CallOptions).Pull):len((*c.CallOptions).Pull)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &pubsubpb.PullResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// StreamingPull establishes a stream with the server, which sends messages down to the +// client. The client streams acknowledgements and ack deadline modifications +// back to the server. The server will close the stream and return the status +// on any error. The server may close the stream with status UNAVAILABLE to +// reassign server-side resources, in which case, the client should +// re-establish the stream. Flow control can be achieved by configuring the +// underlying RPC channel. +// +// This method is not supported for the REST transport. +func (c *subscriberRESTClient) StreamingPull(ctx context.Context, opts ...gax.CallOption) (pubsubpb.Subscriber_StreamingPullClient, error) { + return nil, fmt.Errorf("StreamingPull not yet supported for REST clients") +} + +// ModifyPushConfig modifies the PushConfig for a specified subscription. +// +// This may be used to change a push subscription to a pull one (signified by +// an empty PushConfig) or vice versa, or change the endpoint URL and other +// attributes of a push subscription. Messages will accumulate for delivery +// continuously through the call regardless of changes to the PushConfig. +func (c *subscriberRESTClient) ModifyPushConfig(ctx context.Context, req *pubsubpb.ModifyPushConfigRequest, opts ...gax.CallOption) error { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:modifyPushConfig", req.GetSubscription()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "subscription", url.QueryEscape(req.GetSubscription()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetSnapshot gets the configuration details of a snapshot. Snapshots are used in +// Seek (at https://cloud.google.com/pubsub/docs/replay-overview) +// operations, which allow you to manage message acknowledgments in bulk. That +// is, you can set the acknowledgment state of messages in an existing +// subscription to the state captured by a snapshot. +func (c *subscriberRESTClient) GetSnapshot(ctx context.Context, req *pubsubpb.GetSnapshotRequest, opts ...gax.CallOption) (*pubsubpb.Snapshot, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetSnapshot()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "snapshot", url.QueryEscape(req.GetSnapshot()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetSnapshot[0:len((*c.CallOptions).GetSnapshot):len((*c.CallOptions).GetSnapshot)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &pubsubpb.Snapshot{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListSnapshots lists the existing snapshots. Snapshots are used in Seek (at https://cloud.google.com/pubsub/docs/replay-overview) operations, which +// allow you to manage message acknowledgments in bulk. That is, you can set +// the acknowledgment state of messages in an existing subscription to the +// state captured by a snapshot. +func (c *subscriberRESTClient) ListSnapshots(ctx context.Context, req *pubsubpb.ListSnapshotsRequest, opts ...gax.CallOption) *SnapshotIterator { + it := &SnapshotIterator{} + req = proto.Clone(req).(*pubsubpb.ListSnapshotsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*pubsubpb.Snapshot, string, error) { + resp := &pubsubpb.ListSnapshotsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/snapshots", req.GetProject()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetSnapshots(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CreateSnapshot creates a snapshot from the requested subscription. Snapshots are used in +// Seek (at https://cloud.google.com/pubsub/docs/replay-overview) operations, +// which allow you to manage message acknowledgments in bulk. That is, you can +// set the acknowledgment state of messages in an existing subscription to the +// state captured by a snapshot. +// If the snapshot already exists, returns ALREADY_EXISTS. +// If the requested subscription doesn’t exist, returns NOT_FOUND. +// If the backlog in the subscription is too old – and the resulting snapshot +// would expire in less than 1 hour – then FAILED_PRECONDITION is returned. +// See also the Snapshot.expire_time field. If the name is not provided in +// the request, the server will assign a random +// name for this snapshot on the same project as the subscription, conforming +// to the [resource name format] +// (https://cloud.google.com/pubsub/docs/admin#resource_names (at https://cloud.google.com/pubsub/docs/admin#resource_names)). The +// generated name is populated in the returned Snapshot object. Note that for +// REST API requests, you must specify a name in the request. +func (c *subscriberRESTClient) CreateSnapshot(ctx context.Context, req *pubsubpb.CreateSnapshotRequest, opts ...gax.CallOption) (*pubsubpb.Snapshot, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateSnapshot[0:len((*c.CallOptions).CreateSnapshot):len((*c.CallOptions).CreateSnapshot)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &pubsubpb.Snapshot{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PUT", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateSnapshot updates an existing snapshot. Snapshots are used in +// Seek (at https://cloud.google.com/pubsub/docs/replay-overview) +// operations, which allow +// you to manage message acknowledgments in bulk. That is, you can set the +// acknowledgment state of messages in an existing subscription to the state +// captured by a snapshot. +func (c *subscriberRESTClient) UpdateSnapshot(ctx context.Context, req *pubsubpb.UpdateSnapshotRequest, opts ...gax.CallOption) (*pubsubpb.Snapshot, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetSnapshot().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "snapshot.name", url.QueryEscape(req.GetSnapshot().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateSnapshot[0:len((*c.CallOptions).UpdateSnapshot):len((*c.CallOptions).UpdateSnapshot)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &pubsubpb.Snapshot{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteSnapshot removes an existing snapshot. Snapshots are used in [Seek] +// (https://cloud.google.com/pubsub/docs/replay-overview (at https://cloud.google.com/pubsub/docs/replay-overview)) operations, which +// allow you to manage message acknowledgments in bulk. That is, you can set +// the acknowledgment state of messages in an existing subscription to the +// state captured by a snapshot. +// When the snapshot is deleted, all messages retained in the snapshot +// are immediately dropped. After a snapshot is deleted, a new one may be +// created with the same name, but the new one has no association with the old +// snapshot or its subscription, unless the same subscription is specified. +func (c *subscriberRESTClient) DeleteSnapshot(ctx context.Context, req *pubsubpb.DeleteSnapshotRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetSnapshot()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "snapshot", url.QueryEscape(req.GetSnapshot()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// Seek seeks an existing subscription to a point in time or to a given snapshot, +// whichever is provided in the request. Snapshots are used in [Seek] +// (https://cloud.google.com/pubsub/docs/replay-overview (at https://cloud.google.com/pubsub/docs/replay-overview)) operations, which +// allow you to manage message acknowledgments in bulk. That is, you can set +// the acknowledgment state of messages in an existing subscription to the +// state captured by a snapshot. Note that both the subscription and the +// snapshot must be on the same topic. +func (c *subscriberRESTClient) Seek(ctx context.Context, req *pubsubpb.SeekRequest, opts ...gax.CallOption) (*pubsubpb.SeekResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:seek", req.GetSubscription()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "subscription", url.QueryEscape(req.GetSubscription()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).Seek[0:len((*c.CallOptions).Seek):len((*c.CallOptions).Seek)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &pubsubpb.SeekResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetIamPolicy gets the access control policy for a resource. Returns an empty policy +// if the resource exists and does not have a policy set. +func (c *subscriberRESTClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:getIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetOptions().GetRequestedPolicyVersion() != 0 { + params.Add("options.requestedPolicyVersion", fmt.Sprintf("%v", req.GetOptions().GetRequestedPolicyVersion())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SetIamPolicy sets the access control policy on the specified resource. Replaces +// any existing policy. +// +// Can return NOT_FOUND, INVALID_ARGUMENT, and PERMISSION_DENIED +// errors. +func (c *subscriberRESTClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:setIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// TestIamPermissions returns permissions that a caller has on the specified resource. If the +// resource does not exist, this will return an empty set of +// permissions, not a NOT_FOUND error. +// +// Note: This operation is designed to be used for building +// permission-aware UIs and command-line tools, not for authorization +// checking. This operation may “fail open” without warning. +func (c *subscriberRESTClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:testIamPermissions", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.TestIamPermissionsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + // SnapshotIterator manages a stream of *pubsubpb.Snapshot. type SnapshotIterator struct { items []*pubsubpb.Snapshot diff --git a/pubsub/apiv1/subscriber_client_example_test.go b/pubsub/apiv1/subscriber_client_example_test.go index 1c199f7de88c..ee4216dffa05 100644 --- a/pubsub/apiv1/subscriber_client_example_test.go +++ b/pubsub/apiv1/subscriber_client_example_test.go @@ -43,6 +43,23 @@ func ExampleNewSubscriberClient() { _ = c } +func ExampleNewSubscriberRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := pubsub.NewSubscriberRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleSubscriberClient_CreateSubscription() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/pubsublite/apiv1/pubsublitepb/admin.pb.go b/pubsublite/apiv1/pubsublitepb/admin.pb.go index 3977d90981b9..cc6c7146f764 100644 --- a/pubsublite/apiv1/pubsublitepb/admin.pb.go +++ b/pubsublite/apiv1/pubsublitepb/admin.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/pubsublite/v1/admin.proto package pubsublitepb @@ -1074,7 +1074,6 @@ type SeekSubscriptionRequest struct { // The target to seek to. Must be set. // // Types that are assignable to Target: - // // *SeekSubscriptionRequest_NamedTarget_ // *SeekSubscriptionRequest_TimeTarget Target isSeekSubscriptionRequest_Target `protobuf_oneof:"target"` diff --git a/pubsublite/apiv1/pubsublitepb/common.pb.go b/pubsublite/apiv1/pubsublitepb/common.pb.go index cdf1d0199845..1ba7de1bc658 100644 --- a/pubsublite/apiv1/pubsublitepb/common.pb.go +++ b/pubsublite/apiv1/pubsublitepb/common.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/pubsublite/v1/common.proto package pubsublitepb @@ -662,7 +662,6 @@ type ExportConfig struct { // The destination to export to. Required. // // Types that are assignable to Destination: - // // *ExportConfig_PubsubConfig Destination isExportConfig_Destination `protobuf_oneof:"destination"` } @@ -756,7 +755,6 @@ type TimeTarget struct { // The type of message time to query. // // Types that are assignable to Time: - // // *TimeTarget_PublishTime // *TimeTarget_EventTime Time isTimeTarget_Time `protobuf_oneof:"time"` @@ -855,7 +853,6 @@ type Topic_PartitionConfig struct { // The throughput dimension of this topic. // // Types that are assignable to Dimension: - // // *Topic_PartitionConfig_Scale // *Topic_PartitionConfig_Capacity_ Dimension isTopic_PartitionConfig_Dimension `protobuf_oneof:"dimension"` diff --git a/pubsublite/apiv1/pubsublitepb/cursor.pb.go b/pubsublite/apiv1/pubsublitepb/cursor.pb.go index 1c02931872cc..f6f9f18cc285 100644 --- a/pubsublite/apiv1/pubsublitepb/cursor.pb.go +++ b/pubsublite/apiv1/pubsublitepb/cursor.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/pubsublite/v1/cursor.proto package pubsublitepb @@ -250,7 +250,6 @@ type StreamingCommitCursorRequest struct { // The type of request this is. // // Types that are assignable to Request: - // // *StreamingCommitCursorRequest_Initial // *StreamingCommitCursorRequest_Commit Request isStreamingCommitCursorRequest_Request `protobuf_oneof:"request"` @@ -336,7 +335,6 @@ type StreamingCommitCursorResponse struct { // The type of request this is. // // Types that are assignable to Request: - // // *StreamingCommitCursorResponse_Initial // *StreamingCommitCursorResponse_Commit Request isStreamingCommitCursorResponse_Request `protobuf_oneof:"request"` diff --git a/pubsublite/apiv1/pubsublitepb/publisher.pb.go b/pubsublite/apiv1/pubsublitepb/publisher.pb.go index a690544496f2..8610d770a3a4 100644 --- a/pubsublite/apiv1/pubsublitepb/publisher.pb.go +++ b/pubsublite/apiv1/pubsublitepb/publisher.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/pubsublite/v1/publisher.proto package pubsublitepb @@ -247,7 +247,6 @@ type PublishRequest struct { // The type of request this is. // // Types that are assignable to RequestType: - // // *PublishRequest_InitialRequest // *PublishRequest_MessagePublishRequest RequestType isPublishRequest_RequestType `protobuf_oneof:"request_type"` @@ -333,7 +332,6 @@ type PublishResponse struct { // The type of response this is. // // Types that are assignable to ResponseType: - // // *PublishResponse_InitialResponse // *PublishResponse_MessageResponse ResponseType isPublishResponse_ResponseType `protobuf_oneof:"response_type"` diff --git a/pubsublite/apiv1/pubsublitepb/subscriber.pb.go b/pubsublite/apiv1/pubsublitepb/subscriber.pb.go index ba3c9b530249..1bfad63245d3 100644 --- a/pubsublite/apiv1/pubsublitepb/subscriber.pb.go +++ b/pubsublite/apiv1/pubsublitepb/subscriber.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/pubsublite/v1/subscriber.proto package pubsublitepb @@ -230,7 +230,6 @@ type SeekRequest struct { // The target to seek to. Must be set. // // Types that are assignable to Target: - // // *SeekRequest_NamedTarget_ // *SeekRequest_Cursor Target isSeekRequest_Target `protobuf_oneof:"target"` @@ -425,7 +424,6 @@ type SubscribeRequest struct { // The type of request this is. // // Types that are assignable to Request: - // // *SubscribeRequest_Initial // *SubscribeRequest_Seek // *SubscribeRequest_FlowControl @@ -580,7 +578,6 @@ type SubscribeResponse struct { // The type of response this is. // // Types that are assignable to Response: - // // *SubscribeResponse_Initial // *SubscribeResponse_Seek // *SubscribeResponse_Messages @@ -843,7 +840,6 @@ type PartitionAssignmentRequest struct { // The type of request this is. // // Types that are assignable to Request: - // // *PartitionAssignmentRequest_Initial // *PartitionAssignmentRequest_Ack Request isPartitionAssignmentRequest_Request `protobuf_oneof:"request"` diff --git a/pubsublite/apiv1/pubsublitepb/topic_stats.pb.go b/pubsublite/apiv1/pubsublitepb/topic_stats.pb.go index a84904e1cfd4..d16667d97926 100644 --- a/pubsublite/apiv1/pubsublitepb/topic_stats.pb.go +++ b/pubsublite/apiv1/pubsublitepb/topic_stats.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/pubsublite/v1/topic_stats.proto package pubsublitepb diff --git a/recaptchaenterprise/v2/apiv1/doc.go b/recaptchaenterprise/v2/apiv1/doc.go index 86127b7eed6a..c44348179937 100644 --- a/recaptchaenterprise/v2/apiv1/doc.go +++ b/recaptchaenterprise/v2/apiv1/doc.go @@ -78,6 +78,8 @@ package recaptchaenterprise // import "cloud.google.com/go/recaptchaenterprise/v import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -166,3 +168,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/recaptchaenterprise/v2/apiv1/gapic_metadata.json b/recaptchaenterprise/v2/apiv1/gapic_metadata.json index 06f89091b913..ae4f9d6b8467 100644 --- a/recaptchaenterprise/v2/apiv1/gapic_metadata.json +++ b/recaptchaenterprise/v2/apiv1/gapic_metadata.json @@ -76,6 +76,76 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "AnnotateAssessment": { + "methods": [ + "AnnotateAssessment" + ] + }, + "CreateAssessment": { + "methods": [ + "CreateAssessment" + ] + }, + "CreateKey": { + "methods": [ + "CreateKey" + ] + }, + "DeleteKey": { + "methods": [ + "DeleteKey" + ] + }, + "GetKey": { + "methods": [ + "GetKey" + ] + }, + "GetMetrics": { + "methods": [ + "GetMetrics" + ] + }, + "ListKeys": { + "methods": [ + "ListKeys" + ] + }, + "ListRelatedAccountGroupMemberships": { + "methods": [ + "ListRelatedAccountGroupMemberships" + ] + }, + "ListRelatedAccountGroups": { + "methods": [ + "ListRelatedAccountGroups" + ] + }, + "MigrateKey": { + "methods": [ + "MigrateKey" + ] + }, + "RetrieveLegacySecretKey": { + "methods": [ + "RetrieveLegacySecretKey" + ] + }, + "SearchRelatedAccountGroupMemberships": { + "methods": [ + "SearchRelatedAccountGroupMemberships" + ] + }, + "UpdateKey": { + "methods": [ + "UpdateKey" + ] + } + } } } } diff --git a/recaptchaenterprise/v2/apiv1/recaptcha_enterprise_client.go b/recaptchaenterprise/v2/apiv1/recaptcha_enterprise_client.go index c34d4794e390..de3b5e1987b6 100644 --- a/recaptchaenterprise/v2/apiv1/recaptcha_enterprise_client.go +++ b/recaptchaenterprise/v2/apiv1/recaptcha_enterprise_client.go @@ -17,20 +17,26 @@ package recaptchaenterprise import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" recaptchaenterprisepb "cloud.google.com/go/recaptchaenterprise/v2/apiv1/recaptchaenterprisepb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -83,6 +89,24 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + CreateAssessment: []gax.CallOption{}, + AnnotateAssessment: []gax.CallOption{}, + CreateKey: []gax.CallOption{}, + ListKeys: []gax.CallOption{}, + RetrieveLegacySecretKey: []gax.CallOption{}, + GetKey: []gax.CallOption{}, + UpdateKey: []gax.CallOption{}, + DeleteKey: []gax.CallOption{}, + MigrateKey: []gax.CallOption{}, + GetMetrics: []gax.CallOption{}, + ListRelatedAccountGroups: []gax.CallOption{}, + ListRelatedAccountGroupMemberships: []gax.CallOption{}, + SearchRelatedAccountGroupMemberships: []gax.CallOption{}, + } +} + // internalClient is an interface that defines the methods available from reCAPTCHA Enterprise API. type internalClient interface { Close() error @@ -293,6 +317,74 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new recaptcha enterprise service rest client. +// +// Service to determine the likelihood an event is legitimate. +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://recaptchaenterprise.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://recaptchaenterprise.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://recaptchaenterprise.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) CreateAssessment(ctx context.Context, req *recaptchaenterprisepb.CreateAssessmentRequest, opts ...gax.CallOption) (*recaptchaenterprisepb.Assessment, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) @@ -652,6 +744,911 @@ func (c *gRPCClient) SearchRelatedAccountGroupMemberships(ctx context.Context, r return it } +// CreateAssessment creates an Assessment of the likelihood an event is legitimate. +func (c *restClient) CreateAssessment(ctx context.Context, req *recaptchaenterprisepb.CreateAssessmentRequest, opts ...gax.CallOption) (*recaptchaenterprisepb.Assessment, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetAssessment() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/assessments", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateAssessment[0:len((*c.CallOptions).CreateAssessment):len((*c.CallOptions).CreateAssessment)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &recaptchaenterprisepb.Assessment{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// AnnotateAssessment annotates a previously created Assessment to provide additional information +// on whether the event turned out to be authentic or fraudulent. +func (c *restClient) AnnotateAssessment(ctx context.Context, req *recaptchaenterprisepb.AnnotateAssessmentRequest, opts ...gax.CallOption) (*recaptchaenterprisepb.AnnotateAssessmentResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:annotate", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).AnnotateAssessment[0:len((*c.CallOptions).AnnotateAssessment):len((*c.CallOptions).AnnotateAssessment)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &recaptchaenterprisepb.AnnotateAssessmentResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateKey creates a new reCAPTCHA Enterprise key. +func (c *restClient) CreateKey(ctx context.Context, req *recaptchaenterprisepb.CreateKeyRequest, opts ...gax.CallOption) (*recaptchaenterprisepb.Key, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetKey() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/keys", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateKey[0:len((*c.CallOptions).CreateKey):len((*c.CallOptions).CreateKey)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &recaptchaenterprisepb.Key{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListKeys returns the list of all keys that belong to a project. +func (c *restClient) ListKeys(ctx context.Context, req *recaptchaenterprisepb.ListKeysRequest, opts ...gax.CallOption) *KeyIterator { + it := &KeyIterator{} + req = proto.Clone(req).(*recaptchaenterprisepb.ListKeysRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*recaptchaenterprisepb.Key, string, error) { + resp := &recaptchaenterprisepb.ListKeysResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/keys", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetKeys(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// RetrieveLegacySecretKey returns the secret key related to the specified public key. +// You must use the legacy secret key only in a 3rd party integration with +// legacy reCAPTCHA. +func (c *restClient) RetrieveLegacySecretKey(ctx context.Context, req *recaptchaenterprisepb.RetrieveLegacySecretKeyRequest, opts ...gax.CallOption) (*recaptchaenterprisepb.RetrieveLegacySecretKeyResponse, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:retrieveLegacySecretKey", req.GetKey()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "key", url.QueryEscape(req.GetKey()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).RetrieveLegacySecretKey[0:len((*c.CallOptions).RetrieveLegacySecretKey):len((*c.CallOptions).RetrieveLegacySecretKey)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &recaptchaenterprisepb.RetrieveLegacySecretKeyResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetKey returns the specified key. +func (c *restClient) GetKey(ctx context.Context, req *recaptchaenterprisepb.GetKeyRequest, opts ...gax.CallOption) (*recaptchaenterprisepb.Key, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetKey[0:len((*c.CallOptions).GetKey):len((*c.CallOptions).GetKey)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &recaptchaenterprisepb.Key{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateKey updates the specified key. +func (c *restClient) UpdateKey(ctx context.Context, req *recaptchaenterprisepb.UpdateKeyRequest, opts ...gax.CallOption) (*recaptchaenterprisepb.Key, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetKey() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetKey().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "key.name", url.QueryEscape(req.GetKey().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateKey[0:len((*c.CallOptions).UpdateKey):len((*c.CallOptions).UpdateKey)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &recaptchaenterprisepb.Key{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteKey deletes the specified key. +func (c *restClient) DeleteKey(ctx context.Context, req *recaptchaenterprisepb.DeleteKeyRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// MigrateKey migrates an existing key from reCAPTCHA to reCAPTCHA Enterprise. +// Once a key is migrated, it can be used from either product. SiteVerify +// requests are billed as CreateAssessment calls. You must be +// authenticated as one of the current owners of the reCAPTCHA Site Key, and +// your user must have the reCAPTCHA Enterprise Admin IAM role in the +// destination project. +func (c *restClient) MigrateKey(ctx context.Context, req *recaptchaenterprisepb.MigrateKeyRequest, opts ...gax.CallOption) (*recaptchaenterprisepb.Key, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:migrate", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).MigrateKey[0:len((*c.CallOptions).MigrateKey):len((*c.CallOptions).MigrateKey)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &recaptchaenterprisepb.Key{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetMetrics get some aggregated metrics for a Key. This data can be used to build +// dashboards. +func (c *restClient) GetMetrics(ctx context.Context, req *recaptchaenterprisepb.GetMetricsRequest, opts ...gax.CallOption) (*recaptchaenterprisepb.Metrics, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetMetrics[0:len((*c.CallOptions).GetMetrics):len((*c.CallOptions).GetMetrics)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &recaptchaenterprisepb.Metrics{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListRelatedAccountGroups list groups of related accounts. +func (c *restClient) ListRelatedAccountGroups(ctx context.Context, req *recaptchaenterprisepb.ListRelatedAccountGroupsRequest, opts ...gax.CallOption) *RelatedAccountGroupIterator { + it := &RelatedAccountGroupIterator{} + req = proto.Clone(req).(*recaptchaenterprisepb.ListRelatedAccountGroupsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*recaptchaenterprisepb.RelatedAccountGroup, string, error) { + resp := &recaptchaenterprisepb.ListRelatedAccountGroupsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/relatedaccountgroups", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetRelatedAccountGroups(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// ListRelatedAccountGroupMemberships get memberships in a group of related accounts. +func (c *restClient) ListRelatedAccountGroupMemberships(ctx context.Context, req *recaptchaenterprisepb.ListRelatedAccountGroupMembershipsRequest, opts ...gax.CallOption) *RelatedAccountGroupMembershipIterator { + it := &RelatedAccountGroupMembershipIterator{} + req = proto.Clone(req).(*recaptchaenterprisepb.ListRelatedAccountGroupMembershipsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*recaptchaenterprisepb.RelatedAccountGroupMembership, string, error) { + resp := &recaptchaenterprisepb.ListRelatedAccountGroupMembershipsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/memberships", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetRelatedAccountGroupMemberships(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// SearchRelatedAccountGroupMemberships search group memberships related to a given account. +func (c *restClient) SearchRelatedAccountGroupMemberships(ctx context.Context, req *recaptchaenterprisepb.SearchRelatedAccountGroupMembershipsRequest, opts ...gax.CallOption) *RelatedAccountGroupMembershipIterator { + it := &RelatedAccountGroupMembershipIterator{} + req = proto.Clone(req).(*recaptchaenterprisepb.SearchRelatedAccountGroupMembershipsRequest) + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*recaptchaenterprisepb.RelatedAccountGroupMembership, string, error) { + resp := &recaptchaenterprisepb.SearchRelatedAccountGroupMembershipsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, "", err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/relatedaccountgroupmemberships:search", req.GetProject()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetRelatedAccountGroupMemberships(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + // KeyIterator manages a stream of *recaptchaenterprisepb.Key. type KeyIterator struct { items []*recaptchaenterprisepb.Key diff --git a/recaptchaenterprise/v2/apiv1/recaptcha_enterprise_client_example_test.go b/recaptchaenterprise/v2/apiv1/recaptcha_enterprise_client_example_test.go index 49d797d3fb41..f6e43d163bca 100644 --- a/recaptchaenterprise/v2/apiv1/recaptcha_enterprise_client_example_test.go +++ b/recaptchaenterprise/v2/apiv1/recaptcha_enterprise_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := recaptchaenterprise.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_CreateAssessment() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/recaptchaenterprise/v2/apiv1/recaptchaenterprisepb/recaptchaenterprise.pb.go b/recaptchaenterprise/v2/apiv1/recaptchaenterprisepb/recaptchaenterprise.pb.go index 8c30f9fd9ada..b1bf6cce4c9b 100644 --- a/recaptchaenterprise/v2/apiv1/recaptchaenterprisepb/recaptchaenterprise.pb.go +++ b/recaptchaenterprise/v2/apiv1/recaptchaenterprisepb/recaptchaenterprise.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/recaptchaenterprise/v1/recaptchaenterprise.proto package recaptchaenterprisepb @@ -2020,7 +2020,6 @@ type Key struct { // platform for which the settings are enabled. // // Types that are assignable to PlatformSettings: - // // *Key_WebSettings // *Key_AndroidSettings // *Key_IosSettings diff --git a/recaptchaenterprise/v2/apiv1beta1/recaptcha_enterprise_service_v1_beta1_client.go b/recaptchaenterprise/v2/apiv1beta1/recaptcha_enterprise_service_v1_beta1_client.go index 9bdd03fcce4b..2e1b82968d81 100644 --- a/recaptchaenterprise/v2/apiv1beta1/recaptcha_enterprise_service_v1_beta1_client.go +++ b/recaptchaenterprise/v2/apiv1beta1/recaptcha_enterprise_service_v1_beta1_client.go @@ -335,6 +335,11 @@ func (c *recaptchaEnterpriseServiceV1Beta1RESTClient) CreateAssessment(ctx conte } baseUrl.Path += fmt.Sprintf("/v1beta1/%v/assessments", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -395,6 +400,11 @@ func (c *recaptchaEnterpriseServiceV1Beta1RESTClient) AnnotateAssessment(ctx con } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:annotate", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) diff --git a/recaptchaenterprise/v2/apiv1beta1/recaptchaenterprisepb/recaptchaenterprise.pb.go b/recaptchaenterprise/v2/apiv1beta1/recaptchaenterprisepb/recaptchaenterprise.pb.go index c7e0d1a91c6f..86eb5dbcc6f9 100644 --- a/recaptchaenterprise/v2/apiv1beta1/recaptchaenterprisepb/recaptchaenterprise.pb.go +++ b/recaptchaenterprise/v2/apiv1beta1/recaptchaenterprisepb/recaptchaenterprise.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/recaptchaenterprise/v1beta1/recaptchaenterprise.proto package recaptchaenterprisepb diff --git a/recommendationengine/apiv1beta1/catalog_client.go b/recommendationengine/apiv1beta1/catalog_client.go index 3ecf1e132689..b27770350847 100644 --- a/recommendationengine/apiv1beta1/catalog_client.go +++ b/recommendationengine/apiv1beta1/catalog_client.go @@ -660,6 +660,11 @@ func (c *catalogRESTClient) CreateCatalogItem(ctx context.Context, req *recommen } baseUrl.Path += fmt.Sprintf("/v1beta1/%v/catalogItems", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -713,6 +718,11 @@ func (c *catalogRESTClient) GetCatalogItem(ctx context.Context, req *recommendat } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -780,6 +790,7 @@ func (c *catalogRESTClient) ListCatalogItems(ctx context.Context, req *recommend baseUrl.Path += fmt.Sprintf("/v1beta1/%v/catalogItems", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -865,6 +876,7 @@ func (c *catalogRESTClient) UpdateCatalogItem(ctx context.Context, req *recommen baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -928,6 +940,11 @@ func (c *catalogRESTClient) DeleteCatalogItem(ctx context.Context, req *recommen } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -974,6 +991,11 @@ func (c *catalogRESTClient) ImportCatalogItems(ctx context.Context, req *recomme } baseUrl.Path += fmt.Sprintf("/v1beta1/%v/catalogItems:import", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) diff --git a/recommendationengine/apiv1beta1/prediction_api_key_registry_client.go b/recommendationengine/apiv1beta1/prediction_api_key_registry_client.go index 2c054dc6b884..f367949b96e4 100644 --- a/recommendationengine/apiv1beta1/prediction_api_key_registry_client.go +++ b/recommendationengine/apiv1beta1/prediction_api_key_registry_client.go @@ -461,6 +461,11 @@ func (c *predictionApiKeyRegistryRESTClient) CreatePredictionApiKeyRegistration( } baseUrl.Path += fmt.Sprintf("/v1beta1/%v/predictionApiKeyRegistrations", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -528,6 +533,7 @@ func (c *predictionApiKeyRegistryRESTClient) ListPredictionApiKeyRegistrations(c baseUrl.Path += fmt.Sprintf("/v1beta1/%v/predictionApiKeyRegistrations", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -601,6 +607,11 @@ func (c *predictionApiKeyRegistryRESTClient) DeletePredictionApiKeyRegistration( } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) diff --git a/recommendationengine/apiv1beta1/prediction_client.go b/recommendationengine/apiv1beta1/prediction_client.go index f6f9a6f51ca1..99af66f64331 100644 --- a/recommendationengine/apiv1beta1/prediction_client.go +++ b/recommendationengine/apiv1beta1/prediction_client.go @@ -368,6 +368,11 @@ func (c *predictionRESTClient) Predict(ctx context.Context, req *recommendatione } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:predict", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { diff --git a/recommendationengine/apiv1beta1/recommendationenginepb/catalog.pb.go b/recommendationengine/apiv1beta1/recommendationenginepb/catalog.pb.go index 2224d693f252..2e7cb9f30cc5 100644 --- a/recommendationengine/apiv1beta1/recommendationenginepb/catalog.pb.go +++ b/recommendationengine/apiv1beta1/recommendationenginepb/catalog.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/recommendationengine/v1beta1/catalog.proto package recommendationenginepb @@ -119,10 +119,10 @@ type CatalogItem struct { // ["Sports & Fitness" -> "Athletic Clothing" -> "Shoes"], it could be // represented as: // - // "categoryHierarchies": [ - // { "categories": ["Shoes & Accessories", "Shoes"]}, - // { "categories": ["Sports & Fitness", "Athletic Clothing", "Shoes"] } - // ] + // "categoryHierarchies": [ + // { "categories": ["Shoes & Accessories", "Shoes"]}, + // { "categories": ["Sports & Fitness", "Athletic Clothing", "Shoes"] } + // ] CategoryHierarchies []*CatalogItem_CategoryHierarchy `protobuf:"bytes,2,rep,name=category_hierarchies,json=categoryHierarchies,proto3" json:"category_hierarchies,omitempty"` // Required. Catalog item title. UTF-8 encoded string with a length limit of 1 // KiB. @@ -157,7 +157,6 @@ type CatalogItem struct { // Extra catalog item metadata for different recommendation types. // // Types that are assignable to RecommendationType: - // // *CatalogItem_ProductMetadata RecommendationType isCatalogItem_RecommendationType `protobuf_oneof:"recommendation_type"` } @@ -284,7 +283,6 @@ type ProductCatalogItem struct { // Product price. Only one of 'exactPrice'/'priceRange' can be provided. // // Types that are assignable to Price: - // // *ProductCatalogItem_ExactPrice_ // *ProductCatalogItem_PriceRange_ Price isProductCatalogItem_Price `protobuf_oneof:"price"` diff --git a/recommendationengine/apiv1beta1/recommendationenginepb/catalog_service.pb.go b/recommendationengine/apiv1beta1/recommendationenginepb/catalog_service.pb.go index d6bf63747d7e..6559ea73b008 100644 --- a/recommendationengine/apiv1beta1/recommendationenginepb/catalog_service.pb.go +++ b/recommendationengine/apiv1beta1/recommendationenginepb/catalog_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/recommendationengine/v1beta1/catalog_service.proto package recommendationenginepb diff --git a/recommendationengine/apiv1beta1/recommendationenginepb/common.pb.go b/recommendationengine/apiv1beta1/recommendationenginepb/common.pb.go index 00a95b11cae2..cae0618f057e 100644 --- a/recommendationengine/apiv1beta1/recommendationenginepb/common.pb.go +++ b/recommendationengine/apiv1beta1/recommendationenginepb/common.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/recommendationengine/v1beta1/common.proto package recommendationenginepb @@ -50,8 +50,7 @@ type FeatureMap struct { // Feature names and values must be UTF-8 encoded strings. // // For example: `{ "colors": {"value": ["yellow", "green"]}, - // - // "sizes": {"value":["S", "M"]}` + // "sizes": {"value":["S", "M"]}` CategoricalFeatures map[string]*FeatureMap_StringList `protobuf:"bytes,1,rep,name=categorical_features,json=categoricalFeatures,proto3" json:"categorical_features,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` // Numerical features. Some examples would be the height/weight of a product, // or age of a customer. @@ -59,8 +58,7 @@ type FeatureMap struct { // Feature names must be UTF-8 encoded strings. // // For example: `{ "lengths_cm": {"value":[2.3, 15.4]}, - // - // "heights_cm": {"value":[8.1, 6.4]} }` + // "heights_cm": {"value":[8.1, 6.4]} }` NumericalFeatures map[string]*FeatureMap_FloatList `protobuf:"bytes,2,rep,name=numerical_features,json=numericalFeatures,proto3" json:"numerical_features,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` } diff --git a/recommendationengine/apiv1beta1/recommendationenginepb/import.pb.go b/recommendationengine/apiv1beta1/recommendationenginepb/import.pb.go index 96d1f397811a..106fde96991b 100644 --- a/recommendationengine/apiv1beta1/recommendationenginepb/import.pb.go +++ b/recommendationengine/apiv1beta1/recommendationenginepb/import.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/recommendationengine/v1beta1/import.proto package recommendationenginepb @@ -202,7 +202,6 @@ type ImportErrorsConfig struct { // Required. Errors destination. // // Types that are assignable to Destination: - // // *ImportErrorsConfig_GcsPrefix Destination isImportErrorsConfig_Destination `protobuf_oneof:"destination"` } @@ -437,7 +436,6 @@ type InputConfig struct { // Required. The source of the input. // // Types that are assignable to Source: - // // *InputConfig_CatalogInlineSource // *InputConfig_GcsSource // *InputConfig_UserEventInlineSource diff --git a/recommendationengine/apiv1beta1/recommendationenginepb/prediction_apikey_registry_service.pb.go b/recommendationengine/apiv1beta1/recommendationenginepb/prediction_apikey_registry_service.pb.go index 31f84363f466..b552d082b673 100644 --- a/recommendationengine/apiv1beta1/recommendationenginepb/prediction_apikey_registry_service.pb.go +++ b/recommendationengine/apiv1beta1/recommendationenginepb/prediction_apikey_registry_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/recommendationengine/v1beta1/prediction_apikey_registry_service.proto package recommendationenginepb diff --git a/recommendationengine/apiv1beta1/recommendationenginepb/prediction_service.pb.go b/recommendationengine/apiv1beta1/recommendationenginepb/prediction_service.pb.go index 23d8fb586b2d..7b1c04c91e43 100644 --- a/recommendationengine/apiv1beta1/recommendationenginepb/prediction_service.pb.go +++ b/recommendationengine/apiv1beta1/recommendationenginepb/prediction_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/recommendationengine/v1beta1/prediction_service.proto package recommendationenginepb @@ -54,25 +54,25 @@ type PredictRequest struct { // // We currently support three placements with the following IDs by default: // - // - `shopping_cart`: Predicts items frequently bought together with one or - // more catalog items in the same shopping session. Commonly displayed after - // `add-to-cart` events, on product detail pages, or on the shopping cart - // page. + // * `shopping_cart`: Predicts items frequently bought together with one or + // more catalog items in the same shopping session. Commonly displayed after + // `add-to-cart` events, on product detail pages, or on the shopping cart + // page. // - // - `home_page`: Predicts the next product that a user will most likely - // engage with or purchase based on the shopping or viewing history of the - // specified `userId` or `visitorId`. For example - Recommendations for you. + // * `home_page`: Predicts the next product that a user will most likely + // engage with or purchase based on the shopping or viewing history of the + // specified `userId` or `visitorId`. For example - Recommendations for you. // - // - `product_detail`: Predicts the next product that a user will most likely - // engage with or purchase. The prediction is based on the shopping or - // viewing history of the specified `userId` or `visitorId` and its - // relevance to a specified `CatalogItem`. Typically used on product detail - // pages. For example - More items like this. + // * `product_detail`: Predicts the next product that a user will most likely + // engage with or purchase. The prediction is based on the shopping or + // viewing history of the specified `userId` or `visitorId` and its + // relevance to a specified `CatalogItem`. Typically used on product detail + // pages. For example - More items like this. // - // - `recently_viewed_default`: Returns up to 75 items recently viewed by the - // specified `userId` or `visitorId`, most recent ones first. Returns - // nothing if neither of them has viewed any items yet. For example - - // Recently viewed. + // * `recently_viewed_default`: Returns up to 75 items recently viewed by the + // specified `userId` or `visitorId`, most recent ones first. Returns + // nothing if neither of them has viewed any items yet. For example - + // Recently viewed. // // The full list of available placements can be seen at // https://console.cloud.google.com/recommendation/datafeeds/default_catalog/dashboard @@ -91,21 +91,21 @@ type PredictRequest struct { // Optional. Filter for restricting prediction results. Accepts values for // tags and the `filterOutOfStockItems` flag. // - // - Tag expressions. Restricts predictions to items that match all of the - // specified tags. Boolean operators `OR` and `NOT` are supported if the - // expression is enclosed in parentheses, and must be separated from the - // tag values by a space. `-"tagA"` is also supported and is equivalent to - // `NOT "tagA"`. Tag values must be double quoted UTF-8 encoded strings - // with a size limit of 1 KiB. + // * Tag expressions. Restricts predictions to items that match all of the + // specified tags. Boolean operators `OR` and `NOT` are supported if the + // expression is enclosed in parentheses, and must be separated from the + // tag values by a space. `-"tagA"` is also supported and is equivalent to + // `NOT "tagA"`. Tag values must be double quoted UTF-8 encoded strings + // with a size limit of 1 KiB. // - // - filterOutOfStockItems. Restricts predictions to items that do not have a - // stockState value of OUT_OF_STOCK. + // * filterOutOfStockItems. Restricts predictions to items that do not have a + // stockState value of OUT_OF_STOCK. // // Examples: // - // - tag=("Red" OR "Blue") tag="New-Arrival" tag=(NOT "promotional") - // - filterOutOfStockItems tag=(-"promotional") - // - filterOutOfStockItems + // * tag=("Red" OR "Blue") tag="New-Arrival" tag=(NOT "promotional") + // * filterOutOfStockItems tag=(-"promotional") + // * filterOutOfStockItems Filter string `protobuf:"bytes,3,opt,name=filter,proto3" json:"filter,omitempty"` // Optional. Use dryRun mode for this prediction query. If set to true, a // dummy model will be used that returns arbitrary catalog items. @@ -116,23 +116,23 @@ type PredictRequest struct { // // Allowed values: // - // - `returnCatalogItem`: Boolean. If set to true, the associated catalogItem - // object will be returned in the - // `PredictResponse.PredictionResult.itemMetadata` object in the method - // response. - // - `returnItemScore`: Boolean. If set to true, the prediction 'score' - // corresponding to each returned item will be set in the `metadata` - // field in the prediction response. The given 'score' indicates the - // probability of an item being clicked/purchased given the user's context - // and history. + // * `returnCatalogItem`: Boolean. If set to true, the associated catalogItem + // object will be returned in the + // `PredictResponse.PredictionResult.itemMetadata` object in the method + // response. + // * `returnItemScore`: Boolean. If set to true, the prediction 'score' + // corresponding to each returned item will be set in the `metadata` + // field in the prediction response. The given 'score' indicates the + // probability of an item being clicked/purchased given the user's context + // and history. Params map[string]*structpb.Value `protobuf:"bytes,6,rep,name=params,proto3" json:"params,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` // Optional. The labels for the predict request. // - // - Label keys can contain lowercase letters, digits and hyphens, must start - // with a letter, and must end with a letter or digit. - // - Non-zero label values can contain lowercase letters, digits and hyphens, - // must start with a letter, and must end with a letter or digit. - // - No more than 64 labels can be associated with a given request. + // * Label keys can contain lowercase letters, digits and hyphens, must start + // with a letter, and must end with a letter or digit. + // * Non-zero label values can contain lowercase letters, digits and hyphens, + // must start with a letter, and must end with a letter or digit. + // * No more than 64 labels can be associated with a given request. // // See https://goo.gl/xmQnxf for more information on and examples of labels. Labels map[string]string `protobuf:"bytes,9,rep,name=labels,proto3" json:"labels,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` @@ -336,10 +336,10 @@ type PredictResponse_PredictionResult struct { // // Possible values: // - // - `catalogItem`: JSON representation of the catalogItem. Will be set if - // `returnCatalogItem` is set to true in `PredictRequest.params`. - // - `score`: Prediction score in double value. Will be set if - // `returnItemScore` is set to true in `PredictRequest.params`. + // * `catalogItem`: JSON representation of the catalogItem. Will be set if + // `returnCatalogItem` is set to true in `PredictRequest.params`. + // * `score`: Prediction score in double value. Will be set if + // `returnItemScore` is set to true in `PredictRequest.params`. ItemMetadata map[string]*structpb.Value `protobuf:"bytes,2,rep,name=item_metadata,json=itemMetadata,proto3" json:"item_metadata,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` } diff --git a/recommendationengine/apiv1beta1/recommendationenginepb/recommendationengine_resources.pb.go b/recommendationengine/apiv1beta1/recommendationenginepb/recommendationengine_resources.pb.go index 2b8c2944e2b7..621b9d3e2f44 100644 --- a/recommendationengine/apiv1beta1/recommendationenginepb/recommendationengine_resources.pb.go +++ b/recommendationengine/apiv1beta1/recommendationenginepb/recommendationengine_resources.pb.go @@ -16,8 +16,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/recommendationengine/v1beta1/recommendationengine_resources.proto package recommendationenginepb diff --git a/recommendationengine/apiv1beta1/recommendationenginepb/user_event.pb.go b/recommendationengine/apiv1beta1/recommendationenginepb/user_event.pb.go index 989c860a53be..c10596869273 100644 --- a/recommendationengine/apiv1beta1/recommendationenginepb/user_event.pb.go +++ b/recommendationengine/apiv1beta1/recommendationenginepb/user_event.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/recommendationengine/v1beta1/user_event.proto package recommendationenginepb @@ -105,22 +105,22 @@ type UserEvent struct { // Required. User event type. Allowed values are: // - // - `add-to-cart` Products being added to cart. - // - `add-to-list` Items being added to a list (shopping list, favorites - // etc). - // - `category-page-view` Special pages such as sale or promotion pages - // viewed. - // - `checkout-start` User starting a checkout process. - // - `detail-page-view` Products detail page viewed. - // - `home-page-view` Homepage viewed. - // - `page-visit` Generic page visits not included in the event types above. - // - `purchase-complete` User finishing a purchase. - // - `refund` Purchased items being refunded or returned. - // - `remove-from-cart` Products being removed from cart. - // - `remove-from-list` Items being removed from a list. - // - `search` Product search. - // - `shopping-cart-page-view` User viewing a shopping cart. - // - `impression` List of items displayed. Used by Google Tag Manager. + // * `add-to-cart` Products being added to cart. + // * `add-to-list` Items being added to a list (shopping list, favorites + // etc). + // * `category-page-view` Special pages such as sale or promotion pages + // viewed. + // * `checkout-start` User starting a checkout process. + // * `detail-page-view` Products detail page viewed. + // * `home-page-view` Homepage viewed. + // * `page-visit` Generic page visits not included in the event types above. + // * `purchase-complete` User finishing a purchase. + // * `refund` Purchased items being refunded or returned. + // * `remove-from-cart` Products being removed from cart. + // * `remove-from-list` Items being removed from a list. + // * `search` Product search. + // * `shopping-cart-page-view` User viewing a shopping cart. + // * `impression` List of items displayed. Used by Google Tag Manager. EventType string `protobuf:"bytes,1,opt,name=event_type,json=eventType,proto3" json:"event_type,omitempty"` // Required. User information. UserInfo *UserInfo `protobuf:"bytes,2,opt,name=user_info,json=userInfo,proto3" json:"user_info,omitempty"` @@ -144,9 +144,9 @@ type UserEvent struct { // // This field is optional for the following event types: // - // - `page-visit` - // - `shopping-cart-page-view` - note that 'product_event_detail' should be - // set for this unless the shopping cart is empty. + // * `page-visit` + // * `shopping-cart-page-view` - note that 'product_event_detail' should be + // set for this unless the shopping cart is empty. // // This field is not allowed for the following event types: // @@ -496,9 +496,9 @@ type ProductEventDetail struct { // // This field is optional for the following event types: // - // - `page-visit` - // - `shopping-cart-page-view` - note that 'product_details' should be set for - // this unless the shopping cart is empty. + // * `page-visit` + // * `shopping-cart-page-view` - note that 'product_details' should be set for + // this unless the shopping cart is empty. // // This field is not allowed for the following event types: // @@ -616,12 +616,9 @@ type PurchaseTransaction struct { // other costs. // // Total product cost such that - // - // profit = revenue - (sum(taxes) + sum(costs)) - // + // profit = revenue - (sum(taxes) + sum(costs)) // If product_cost is not set, then - // - // profit = revenue - tax - shipping - sum(CatalogItem.costs). + // profit = revenue - tax - shipping - sum(CatalogItem.costs). // // If CatalogItem.cost is not specified for one of the items, CatalogItem.cost // based profit *cannot* be calculated for this Transaction. diff --git a/recommendationengine/apiv1beta1/recommendationenginepb/user_event_service.pb.go b/recommendationengine/apiv1beta1/recommendationenginepb/user_event_service.pb.go index 8a15e24644a7..70a9ab2c2969 100644 --- a/recommendationengine/apiv1beta1/recommendationenginepb/user_event_service.pb.go +++ b/recommendationengine/apiv1beta1/recommendationenginepb/user_event_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/recommendationengine/v1beta1/user_event_service.proto package recommendationenginepb @@ -410,35 +410,34 @@ type ListUserEventsRequest struct { // returned events. This is a sequence of terms, where each term applies some // kind of a restriction to the returned user events. Use this expression to // restrict results to a specific time range, or filter events by eventType. + // eg: eventTime > "2012-04-23T18:25:43.511Z" eventsMissingCatalogItems + // eventTime<"2012-04-23T18:25:43.511Z" eventType=search // - // eg: eventTime > "2012-04-23T18:25:43.511Z" eventsMissingCatalogItems - // eventTime<"2012-04-23T18:25:43.511Z" eventType=search + // We expect only 3 types of fields: // - // We expect only 3 types of fields: + // * eventTime: this can be specified a maximum of 2 times, once with a + // less than operator and once with a greater than operator. The + // eventTime restrict should result in one contiguous valid eventTime + // range. // - // * eventTime: this can be specified a maximum of 2 times, once with a - // less than operator and once with a greater than operator. The - // eventTime restrict should result in one contiguous valid eventTime - // range. + // * eventType: only 1 eventType restriction can be specified. // - // * eventType: only 1 eventType restriction can be specified. + // * eventsMissingCatalogItems: specififying this will restrict results + // to events for which catalog items were not found in the catalog. The + // default behavior is to return only those events for which catalog + // items were found. // - // * eventsMissingCatalogItems: specififying this will restrict results - // to events for which catalog items were not found in the catalog. The - // default behavior is to return only those events for which catalog - // items were found. + // Some examples of valid filters expressions: // - // Some examples of valid filters expressions: - // - // * Example 1: eventTime > "2012-04-23T18:25:43.511Z" - // eventTime < "2012-04-23T18:30:43.511Z" - // * Example 2: eventTime > "2012-04-23T18:25:43.511Z" - // eventType = detail-page-view - // * Example 3: eventsMissingCatalogItems - // eventType = search eventTime < "2018-04-23T18:30:43.511Z" - // * Example 4: eventTime > "2012-04-23T18:25:43.511Z" - // * Example 5: eventType = search - // * Example 6: eventsMissingCatalogItems + // * Example 1: eventTime > "2012-04-23T18:25:43.511Z" + // eventTime < "2012-04-23T18:30:43.511Z" + // * Example 2: eventTime > "2012-04-23T18:25:43.511Z" + // eventType = detail-page-view + // * Example 3: eventsMissingCatalogItems + // eventType = search eventTime < "2018-04-23T18:30:43.511Z" + // * Example 4: eventTime > "2012-04-23T18:25:43.511Z" + // * Example 5: eventType = search + // * Example 6: eventsMissingCatalogItems Filter string `protobuf:"bytes,4,opt,name=filter,proto3" json:"filter,omitempty"` } diff --git a/recommendationengine/apiv1beta1/user_event_client.go b/recommendationengine/apiv1beta1/user_event_client.go index b02d2f8895c0..7b5b63a602ef 100644 --- a/recommendationengine/apiv1beta1/user_event_client.go +++ b/recommendationengine/apiv1beta1/user_event_client.go @@ -629,6 +629,11 @@ func (c *userEventRESTClient) WriteUserEvent(ctx context.Context, req *recommend } baseUrl.Path += fmt.Sprintf("/v1beta1/%v/userEvents:write", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -687,6 +692,7 @@ func (c *userEventRESTClient) CollectUserEvent(ctx context.Context, req *recomme baseUrl.Path += fmt.Sprintf("/v1beta1/%v/userEvents:collect", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetEts() != 0 { params.Add("ets", fmt.Sprintf("%v", req.GetEts())) } @@ -764,6 +770,7 @@ func (c *userEventRESTClient) ListUserEvents(ctx context.Context, req *recommend baseUrl.Path += fmt.Sprintf("/v1beta1/%v/userEvents", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -849,6 +856,11 @@ func (c *userEventRESTClient) PurgeUserEvents(ctx context.Context, req *recommen } baseUrl.Path += fmt.Sprintf("/v1beta1/%v/userEvents:purge", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -918,6 +930,11 @@ func (c *userEventRESTClient) ImportUserEvents(ctx context.Context, req *recomme } baseUrl.Path += fmt.Sprintf("/v1beta1/%v/userEvents:import", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) diff --git a/recommender/apiv1/doc.go b/recommender/apiv1/doc.go index efe69cc14f46..50f076064ad3 100644 --- a/recommender/apiv1/doc.go +++ b/recommender/apiv1/doc.go @@ -84,6 +84,8 @@ package recommender // import "cloud.google.com/go/recommender/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -172,3 +174,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/recommender/apiv1/gapic_metadata.json b/recommender/apiv1/gapic_metadata.json index 5a81d1f70059..1065e33e5c90 100644 --- a/recommender/apiv1/gapic_metadata.json +++ b/recommender/apiv1/gapic_metadata.json @@ -71,6 +71,71 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "GetInsight": { + "methods": [ + "GetInsight" + ] + }, + "GetInsightTypeConfig": { + "methods": [ + "GetInsightTypeConfig" + ] + }, + "GetRecommendation": { + "methods": [ + "GetRecommendation" + ] + }, + "GetRecommenderConfig": { + "methods": [ + "GetRecommenderConfig" + ] + }, + "ListInsights": { + "methods": [ + "ListInsights" + ] + }, + "ListRecommendations": { + "methods": [ + "ListRecommendations" + ] + }, + "MarkInsightAccepted": { + "methods": [ + "MarkInsightAccepted" + ] + }, + "MarkRecommendationClaimed": { + "methods": [ + "MarkRecommendationClaimed" + ] + }, + "MarkRecommendationFailed": { + "methods": [ + "MarkRecommendationFailed" + ] + }, + "MarkRecommendationSucceeded": { + "methods": [ + "MarkRecommendationSucceeded" + ] + }, + "UpdateInsightTypeConfig": { + "methods": [ + "UpdateInsightTypeConfig" + ] + }, + "UpdateRecommenderConfig": { + "methods": [ + "UpdateRecommenderConfig" + ] + } + } } } } diff --git a/recommender/apiv1/recommender_client.go b/recommender/apiv1/recommender_client.go index 5e654f25a431..727d01c4830e 100644 --- a/recommender/apiv1/recommender_client.go +++ b/recommender/apiv1/recommender_client.go @@ -17,21 +17,27 @@ package recommender import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" recommenderpb "cloud.google.com/go/recommender/apiv1/recommenderpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -126,6 +132,63 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + ListInsights: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + GetInsight: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + MarkInsightAccepted: []gax.CallOption{}, + ListRecommendations: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + GetRecommendation: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + MarkRecommendationClaimed: []gax.CallOption{}, + MarkRecommendationSucceeded: []gax.CallOption{}, + MarkRecommendationFailed: []gax.CallOption{}, + GetRecommenderConfig: []gax.CallOption{}, + UpdateRecommenderConfig: []gax.CallOption{}, + GetInsightTypeConfig: []gax.CallOption{}, + UpdateInsightTypeConfig: []gax.CallOption{}, + } +} + // internalClient is an interface that defines the methods available from Recommender API. type internalClient interface { Close() error @@ -369,6 +432,77 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new recommender rest client. +// +// Provides insights and recommendations for cloud customers for various +// categories like performance optimization, cost savings, reliability, feature +// discovery, etc. Insights and recommendations are generated automatically +// based on analysis of user resources, configuration and monitoring metrics. +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://recommender.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://recommender.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://recommender.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) ListInsights(ctx context.Context, req *recommenderpb.ListInsightsRequest, opts ...gax.CallOption) *InsightIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -659,6 +793,868 @@ func (c *gRPCClient) UpdateInsightTypeConfig(ctx context.Context, req *recommend return resp, nil } +// ListInsights lists insights for the specified Cloud Resource. Requires the +// recommender.*.list IAM permission for the specified insight type. +func (c *restClient) ListInsights(ctx context.Context, req *recommenderpb.ListInsightsRequest, opts ...gax.CallOption) *InsightIterator { + it := &InsightIterator{} + req = proto.Clone(req).(*recommenderpb.ListInsightsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*recommenderpb.Insight, string, error) { + resp := &recommenderpb.ListInsightsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/insights", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetInsights(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetInsight gets the requested insight. Requires the recommender.*.get IAM permission +// for the specified insight type. +func (c *restClient) GetInsight(ctx context.Context, req *recommenderpb.GetInsightRequest, opts ...gax.CallOption) (*recommenderpb.Insight, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetInsight[0:len((*c.CallOptions).GetInsight):len((*c.CallOptions).GetInsight)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &recommenderpb.Insight{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// MarkInsightAccepted marks the Insight State as Accepted. Users can use this method to +// indicate to the Recommender API that they have applied some action based +// on the insight. This stops the insight content from being updated. +// +// MarkInsightAccepted can be applied to insights in ACTIVE state. Requires +// the recommender.*.update IAM permission for the specified insight. +func (c *restClient) MarkInsightAccepted(ctx context.Context, req *recommenderpb.MarkInsightAcceptedRequest, opts ...gax.CallOption) (*recommenderpb.Insight, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:markAccepted", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).MarkInsightAccepted[0:len((*c.CallOptions).MarkInsightAccepted):len((*c.CallOptions).MarkInsightAccepted)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &recommenderpb.Insight{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListRecommendations lists recommendations for the specified Cloud Resource. Requires the +// recommender.*.list IAM permission for the specified recommender. +func (c *restClient) ListRecommendations(ctx context.Context, req *recommenderpb.ListRecommendationsRequest, opts ...gax.CallOption) *RecommendationIterator { + it := &RecommendationIterator{} + req = proto.Clone(req).(*recommenderpb.ListRecommendationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*recommenderpb.Recommendation, string, error) { + resp := &recommenderpb.ListRecommendationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/recommendations", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetRecommendations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetRecommendation gets the requested recommendation. Requires the recommender.*.get +// IAM permission for the specified recommender. +func (c *restClient) GetRecommendation(ctx context.Context, req *recommenderpb.GetRecommendationRequest, opts ...gax.CallOption) (*recommenderpb.Recommendation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetRecommendation[0:len((*c.CallOptions).GetRecommendation):len((*c.CallOptions).GetRecommendation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &recommenderpb.Recommendation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// MarkRecommendationClaimed marks the Recommendation State as Claimed. Users can use this method to +// indicate to the Recommender API that they are starting to apply the +// recommendation themselves. This stops the recommendation content from being +// updated. Associated insights are frozen and placed in the ACCEPTED state. +// +// MarkRecommendationClaimed can be applied to recommendations in CLAIMED, +// SUCCEEDED, FAILED, or ACTIVE state. +// +// Requires the recommender.*.update IAM permission for the specified +// recommender. +func (c *restClient) MarkRecommendationClaimed(ctx context.Context, req *recommenderpb.MarkRecommendationClaimedRequest, opts ...gax.CallOption) (*recommenderpb.Recommendation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:markClaimed", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).MarkRecommendationClaimed[0:len((*c.CallOptions).MarkRecommendationClaimed):len((*c.CallOptions).MarkRecommendationClaimed)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &recommenderpb.Recommendation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// MarkRecommendationSucceeded marks the Recommendation State as Succeeded. Users can use this method to +// indicate to the Recommender API that they have applied the recommendation +// themselves, and the operation was successful. This stops the recommendation +// content from being updated. Associated insights are frozen and placed in +// the ACCEPTED state. +// +// MarkRecommendationSucceeded can be applied to recommendations in ACTIVE, +// CLAIMED, SUCCEEDED, or FAILED state. +// +// Requires the recommender.*.update IAM permission for the specified +// recommender. +func (c *restClient) MarkRecommendationSucceeded(ctx context.Context, req *recommenderpb.MarkRecommendationSucceededRequest, opts ...gax.CallOption) (*recommenderpb.Recommendation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:markSucceeded", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).MarkRecommendationSucceeded[0:len((*c.CallOptions).MarkRecommendationSucceeded):len((*c.CallOptions).MarkRecommendationSucceeded)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &recommenderpb.Recommendation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// MarkRecommendationFailed marks the Recommendation State as Failed. Users can use this method to +// indicate to the Recommender API that they have applied the recommendation +// themselves, and the operation failed. This stops the recommendation content +// from being updated. Associated insights are frozen and placed in the +// ACCEPTED state. +// +// MarkRecommendationFailed can be applied to recommendations in ACTIVE, +// CLAIMED, SUCCEEDED, or FAILED state. +// +// Requires the recommender.*.update IAM permission for the specified +// recommender. +func (c *restClient) MarkRecommendationFailed(ctx context.Context, req *recommenderpb.MarkRecommendationFailedRequest, opts ...gax.CallOption) (*recommenderpb.Recommendation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:markFailed", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).MarkRecommendationFailed[0:len((*c.CallOptions).MarkRecommendationFailed):len((*c.CallOptions).MarkRecommendationFailed)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &recommenderpb.Recommendation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetRecommenderConfig gets the requested Recommender Config. There is only one instance of the +// config for each Recommender. +func (c *restClient) GetRecommenderConfig(ctx context.Context, req *recommenderpb.GetRecommenderConfigRequest, opts ...gax.CallOption) (*recommenderpb.RecommenderConfig, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetRecommenderConfig[0:len((*c.CallOptions).GetRecommenderConfig):len((*c.CallOptions).GetRecommenderConfig)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &recommenderpb.RecommenderConfig{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateRecommenderConfig updates a Recommender Config. This will create a new revision of the +// config. +func (c *restClient) UpdateRecommenderConfig(ctx context.Context, req *recommenderpb.UpdateRecommenderConfigRequest, opts ...gax.CallOption) (*recommenderpb.RecommenderConfig, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetRecommenderConfig() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetRecommenderConfig().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "recommender_config.name", url.QueryEscape(req.GetRecommenderConfig().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateRecommenderConfig[0:len((*c.CallOptions).UpdateRecommenderConfig):len((*c.CallOptions).UpdateRecommenderConfig)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &recommenderpb.RecommenderConfig{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetInsightTypeConfig gets the requested InsightTypeConfig. There is only one instance of the +// config for each InsightType. +func (c *restClient) GetInsightTypeConfig(ctx context.Context, req *recommenderpb.GetInsightTypeConfigRequest, opts ...gax.CallOption) (*recommenderpb.InsightTypeConfig, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetInsightTypeConfig[0:len((*c.CallOptions).GetInsightTypeConfig):len((*c.CallOptions).GetInsightTypeConfig)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &recommenderpb.InsightTypeConfig{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateInsightTypeConfig updates an InsightTypeConfig change. This will create a new revision of the +// config. +func (c *restClient) UpdateInsightTypeConfig(ctx context.Context, req *recommenderpb.UpdateInsightTypeConfigRequest, opts ...gax.CallOption) (*recommenderpb.InsightTypeConfig, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetInsightTypeConfig() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetInsightTypeConfig().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "insight_type_config.name", url.QueryEscape(req.GetInsightTypeConfig().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateInsightTypeConfig[0:len((*c.CallOptions).UpdateInsightTypeConfig):len((*c.CallOptions).UpdateInsightTypeConfig)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &recommenderpb.InsightTypeConfig{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + // InsightIterator manages a stream of *recommenderpb.Insight. type InsightIterator struct { items []*recommenderpb.Insight diff --git a/recommender/apiv1/recommender_client_example_test.go b/recommender/apiv1/recommender_client_example_test.go index 8cdf278872af..3ebbd4705bc3 100644 --- a/recommender/apiv1/recommender_client_example_test.go +++ b/recommender/apiv1/recommender_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := recommender.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_ListInsights() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/recommender/apiv1/recommenderpb/insight.pb.go b/recommender/apiv1/recommenderpb/insight.pb.go index 070160394690..bdbaaebaa62a 100644 --- a/recommender/apiv1/recommenderpb/insight.pb.go +++ b/recommender/apiv1/recommenderpb/insight.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/recommender/v1/insight.proto package recommenderpb diff --git a/recommender/apiv1/recommenderpb/insight_type_config.pb.go b/recommender/apiv1/recommenderpb/insight_type_config.pb.go index d82abf90deaa..d51d3b124c3e 100644 --- a/recommender/apiv1/recommenderpb/insight_type_config.pb.go +++ b/recommender/apiv1/recommenderpb/insight_type_config.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/recommender/v1/insight_type_config.proto package recommenderpb diff --git a/recommender/apiv1/recommenderpb/recommendation.pb.go b/recommender/apiv1/recommenderpb/recommendation.pb.go index 9c2d722b6f47..0f44bf3f4b8e 100644 --- a/recommender/apiv1/recommenderpb/recommendation.pb.go +++ b/recommender/apiv1/recommenderpb/recommendation.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/recommender/v1/recommendation.proto package recommenderpb @@ -261,9 +261,8 @@ type Recommendation struct { // to see a list of subtypes for a given Recommender. // // Examples: - // - // For recommender = "google.iam.policy.Recommender", - // recommender_subtype can be one of "REMOVE_ROLE"/"REPLACE_ROLE" + // For recommender = "google.iam.policy.Recommender", + // recommender_subtype can be one of "REMOVE_ROLE"/"REPLACE_ROLE" RecommenderSubtype string `protobuf:"bytes,12,opt,name=recommender_subtype,json=recommenderSubtype,proto3" json:"recommender_subtype,omitempty"` // Last time this recommendation was refreshed by the system that created it // in the first place. @@ -561,7 +560,6 @@ type Operation struct { // describe a value for 'path' field. // // Types that are assignable to PathValue: - // // *Operation_Value // *Operation_ValueMatcher PathValue isOperation_PathValue `protobuf_oneof:"path_value"` @@ -573,30 +571,24 @@ type Operation struct { // // * Example: // ``` - // - // { - // "/versions/*/name" : "it-123" - // "/versions/*/targetSize/percent": 20 - // } - // + // { + // "/versions/*/name" : "it-123" + // "/versions/*/targetSize/percent": 20 + // } // ``` // * Example: // ``` - // - // { - // "/bindings/*/role": "roles/owner" - // "/bindings/*/condition" : null - // } - // + // { + // "/bindings/*/role": "roles/owner" + // "/bindings/*/condition" : null + // } // ``` // * Example: // ``` - // - // { - // "/bindings/*/role": "roles/owner" - // "/bindings/*/members/*" : ["x@example.com", "y@example.com"] - // } - // + // { + // "/bindings/*/role": "roles/owner" + // "/bindings/*/members/*" : ["x@example.com", "y@example.com"] + // } // ``` // When both path_filters and path_value_matchers are set, an implicit AND // must be performed. @@ -746,7 +738,6 @@ type ValueMatcher struct { unknownFields protoimpl.UnknownFields // Types that are assignable to MatchVariant: - // // *ValueMatcher_MatchesPattern MatchVariant isValueMatcher_MatchVariant `protobuf_oneof:"match_variant"` } @@ -933,7 +924,6 @@ type Impact struct { // Contains projections (if any) for this category. // // Types that are assignable to Projection: - // // *Impact_CostProjection // *Impact_SecurityProjection Projection isImpact_Projection `protobuf_oneof:"projection"` diff --git a/recommender/apiv1/recommenderpb/recommender_config.pb.go b/recommender/apiv1/recommenderpb/recommender_config.pb.go index 6e99a1485776..80ef16cab8b8 100644 --- a/recommender/apiv1/recommenderpb/recommender_config.pb.go +++ b/recommender/apiv1/recommenderpb/recommender_config.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/recommender/v1/recommender_config.proto package recommenderpb diff --git a/recommender/apiv1/recommenderpb/recommender_service.pb.go b/recommender/apiv1/recommenderpb/recommender_service.pb.go index 8a99440a230e..25d2317971fd 100644 --- a/recommender/apiv1/recommenderpb/recommender_service.pb.go +++ b/recommender/apiv1/recommenderpb/recommender_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/recommender/v1/recommender_service.proto package recommenderpb diff --git a/recommender/apiv1beta1/recommender_client.go b/recommender/apiv1beta1/recommender_client.go index ea1c682354ad..21bca8ed6dc0 100644 --- a/recommender/apiv1beta1/recommender_client.go +++ b/recommender/apiv1beta1/recommender_client.go @@ -816,6 +816,7 @@ func (c *restClient) ListInsights(ctx context.Context, req *recommenderpb.ListIn baseUrl.Path += fmt.Sprintf("/v1beta1/%v/insights", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -893,6 +894,11 @@ func (c *restClient) GetInsight(ctx context.Context, req *recommenderpb.GetInsig } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -957,6 +963,11 @@ func (c *restClient) MarkInsightAccepted(ctx context.Context, req *recommenderpb } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:markAccepted", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1025,6 +1036,7 @@ func (c *restClient) ListRecommendations(ctx context.Context, req *recommenderpb baseUrl.Path += fmt.Sprintf("/v1beta1/%v/recommendations", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1102,6 +1114,11 @@ func (c *restClient) GetRecommendation(ctx context.Context, req *recommenderpb.G } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1170,6 +1187,11 @@ func (c *restClient) MarkRecommendationClaimed(ctx context.Context, req *recomme } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:markClaimed", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1239,6 +1261,11 @@ func (c *restClient) MarkRecommendationSucceeded(ctx context.Context, req *recom } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:markSucceeded", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1308,6 +1335,11 @@ func (c *restClient) MarkRecommendationFailed(ctx context.Context, req *recommen } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:markFailed", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1362,6 +1394,11 @@ func (c *restClient) GetRecommenderConfig(ctx context.Context, req *recommenderp } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1424,6 +1461,7 @@ func (c *restClient) UpdateRecommenderConfig(ctx context.Context, req *recommend baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetRecommenderConfig().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -1491,6 +1529,11 @@ func (c *restClient) GetInsightTypeConfig(ctx context.Context, req *recommenderp } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1553,6 +1596,7 @@ func (c *restClient) UpdateInsightTypeConfig(ctx context.Context, req *recommend baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetInsightTypeConfig().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { diff --git a/recommender/apiv1beta1/recommenderpb/insight.pb.go b/recommender/apiv1beta1/recommenderpb/insight.pb.go index 42b009c38c36..e9bedcdd8b99 100644 --- a/recommender/apiv1beta1/recommenderpb/insight.pb.go +++ b/recommender/apiv1beta1/recommenderpb/insight.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/recommender/v1beta1/insight.proto package recommenderpb diff --git a/recommender/apiv1beta1/recommenderpb/insight_type_config.pb.go b/recommender/apiv1beta1/recommenderpb/insight_type_config.pb.go index 2a39bdee7f00..1fa3d12f8215 100644 --- a/recommender/apiv1beta1/recommenderpb/insight_type_config.pb.go +++ b/recommender/apiv1beta1/recommenderpb/insight_type_config.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/recommender/v1beta1/insight_type_config.proto package recommenderpb diff --git a/recommender/apiv1beta1/recommenderpb/recommendation.pb.go b/recommender/apiv1beta1/recommenderpb/recommendation.pb.go index 0602fa13a26f..cc957c2fff22 100644 --- a/recommender/apiv1beta1/recommenderpb/recommendation.pb.go +++ b/recommender/apiv1beta1/recommenderpb/recommendation.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/recommender/v1beta1/recommendation.proto package recommenderpb @@ -265,9 +265,8 @@ type Recommendation struct { // to see a list of subtypes for a given Recommender. // // Examples: - // - // For recommender = "google.iam.policy.Recommender", - // recommender_subtype can be one of "REMOVE_ROLE"/"REPLACE_ROLE" + // For recommender = "google.iam.policy.Recommender", + // recommender_subtype can be one of "REMOVE_ROLE"/"REPLACE_ROLE" RecommenderSubtype string `protobuf:"bytes,12,opt,name=recommender_subtype,json=recommenderSubtype,proto3" json:"recommender_subtype,omitempty"` // Last time this recommendation was refreshed by the system that created it // in the first place. @@ -565,7 +564,6 @@ type Operation struct { // describe a value for 'path' field. // // Types that are assignable to PathValue: - // // *Operation_Value // *Operation_ValueMatcher PathValue isOperation_PathValue `protobuf_oneof:"path_value"` @@ -577,30 +575,24 @@ type Operation struct { // // * Example: // ``` - // - // { - // "/versions/*/name" : "it-123" - // "/versions/*/targetSize/percent": 20 - // } - // + // { + // "/versions/*/name" : "it-123" + // "/versions/*/targetSize/percent": 20 + // } // ``` // * Example: // ``` - // - // { - // "/bindings/*/role": "roles/owner" - // "/bindings/*/condition" : null - // } - // + // { + // "/bindings/*/role": "roles/owner" + // "/bindings/*/condition" : null + // } // ``` // * Example: // ``` - // - // { - // "/bindings/*/role": "roles/owner" - // "/bindings/*/members/*" : ["x@example.com", "y@example.com"] - // } - // + // { + // "/bindings/*/role": "roles/owner" + // "/bindings/*/members/*" : ["x@example.com", "y@example.com"] + // } // ``` // When both path_filters and path_value_matchers are set, an implicit AND // must be performed. @@ -750,7 +742,6 @@ type ValueMatcher struct { unknownFields protoimpl.UnknownFields // Types that are assignable to MatchVariant: - // // *ValueMatcher_MatchesPattern MatchVariant isValueMatcher_MatchVariant `protobuf_oneof:"match_variant"` } @@ -998,7 +989,6 @@ type Impact struct { // Contains projections (if any) for this category. // // Types that are assignable to Projection: - // // *Impact_CostProjection // *Impact_SecurityProjection // *Impact_SustainabilityProjection diff --git a/recommender/apiv1beta1/recommenderpb/recommender_config.pb.go b/recommender/apiv1beta1/recommenderpb/recommender_config.pb.go index 5c36f58a9f12..3e1030a1c469 100644 --- a/recommender/apiv1beta1/recommenderpb/recommender_config.pb.go +++ b/recommender/apiv1beta1/recommenderpb/recommender_config.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/recommender/v1beta1/recommender_config.proto package recommenderpb diff --git a/recommender/apiv1beta1/recommenderpb/recommender_service.pb.go b/recommender/apiv1beta1/recommenderpb/recommender_service.pb.go index 54ef30de7380..20dc30ef86c3 100644 --- a/recommender/apiv1beta1/recommenderpb/recommender_service.pb.go +++ b/recommender/apiv1beta1/recommenderpb/recommender_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/recommender/v1beta1/recommender_service.proto package recommenderpb diff --git a/redis/apiv1/cloud_redis_client.go b/redis/apiv1/cloud_redis_client.go index 5c46a08b9b6c..9b1dff6a4e78 100644 --- a/redis/apiv1/cloud_redis_client.go +++ b/redis/apiv1/cloud_redis_client.go @@ -17,9 +17,12 @@ package redis import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,13 +30,16 @@ import ( lroauto "cloud.google.com/go/longrunning/autogen" redispb "cloud.google.com/go/redis/apiv1/redispb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -82,6 +88,22 @@ func defaultCloudRedisCallOptions() *CloudRedisCallOptions { } } +func defaultCloudRedisRESTCallOptions() *CloudRedisCallOptions { + return &CloudRedisCallOptions{ + ListInstances: []gax.CallOption{}, + GetInstance: []gax.CallOption{}, + GetInstanceAuthString: []gax.CallOption{}, + CreateInstance: []gax.CallOption{}, + UpdateInstance: []gax.CallOption{}, + UpgradeInstance: []gax.CallOption{}, + ImportInstance: []gax.CallOption{}, + ExportInstance: []gax.CallOption{}, + FailoverInstance: []gax.CallOption{}, + DeleteInstance: []gax.CallOption{}, + RescheduleMaintenance: []gax.CallOption{}, + } +} + // internalCloudRedisClient is an interface that defines the methods available from Google Cloud Memorystore for Redis API. type internalCloudRedisClient interface { Close() error @@ -427,6 +449,108 @@ func (c *cloudRedisGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type cloudRedisRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing CloudRedisClient + CallOptions **CloudRedisCallOptions +} + +// NewCloudRedisRESTClient creates a new cloud redis rest client. +// +// # Configures and manages Cloud Memorystore for Redis instances +// +// # Google Cloud Memorystore for Redis v1 +// +// The redis.googleapis.com service implements the Google Cloud Memorystore +// for Redis API and defines the following resource model for managing Redis +// instances: +// +// The service works with a collection of cloud projects, named: /projects/* +// +// Each project has a collection of available locations, named: /locations/* +// +// Each location has a collection of Redis instances, named: /instances/* +// +// As such, Redis instances are resources of the form: +// /projects/{project_id}/locations/{location_id}/instances/{instance_id} +// +// Note that location_id must be referring to a GCP region; for example: +// +// projects/redpepper-1290/locations/us-central1/instances/my-redis +func NewCloudRedisRESTClient(ctx context.Context, opts ...option.ClientOption) (*CloudRedisClient, error) { + clientOpts := append(defaultCloudRedisRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultCloudRedisRESTCallOptions() + c := &cloudRedisRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &CloudRedisClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultCloudRedisRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://redis.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://redis.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://redis.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *cloudRedisRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *cloudRedisRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *cloudRedisRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *cloudRedisGRPCClient) ListInstances(ctx context.Context, req *redispb.ListInstancesRequest, opts ...gax.CallOption) *InstanceIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -708,105 +832,924 @@ func (c *cloudRedisGRPCClient) RescheduleMaintenance(ctx context.Context, req *r }, nil } -// CreateInstanceOperation manages a long-running operation from CreateInstance. -type CreateInstanceOperation struct { - lro *longrunning.Operation -} +// ListInstances lists all Redis instances owned by a project in either the specified +// location (region) or all locations. +// +// The location should have the following format: +// +// projects/{project_id}/locations/{location_id} +// +// If location_id is specified as - (wildcard), then all regions +// available to the project are queried, and the results are aggregated. +func (c *cloudRedisRESTClient) ListInstances(ctx context.Context, req *redispb.ListInstancesRequest, opts ...gax.CallOption) *InstanceIterator { + it := &InstanceIterator{} + req = proto.Clone(req).(*redispb.ListInstancesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*redispb.Instance, string, error) { + resp := &redispb.ListInstancesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/instances", req.GetParent()) -// CreateInstanceOperation returns a new CreateInstanceOperation from a given name. -// The name must be that of a previously created CreateInstanceOperation, possibly from a different process. -func (c *cloudRedisGRPCClient) CreateInstanceOperation(name string) *CreateInstanceOperation { - return &CreateInstanceOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetInstances(), resp.GetNextPageToken(), nil } -} -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *CreateInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*redispb.Instance, error) { - var resp redispb.Instance - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { - return nil, err + 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 } - return &resp, nil + + it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it } -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *CreateInstanceOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*redispb.Instance, error) { - var resp redispb.Instance - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { +// GetInstance gets the details of a specific Redis instance. +func (c *cloudRedisRESTClient) GetInstance(ctx context.Context, req *redispb.GetInstanceRequest, opts ...gax.CallOption) (*redispb.Instance, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - if !op.Done() { - return nil, nil + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetInstance[0:len((*c.CallOptions).GetInstance):len((*c.CallOptions).GetInstance)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &redispb.Instance{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e } - return &resp, nil + return resp, nil } -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *CreateInstanceOperation) Metadata() (*redispb.OperationMetadata, error) { - var meta redispb.OperationMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { +// GetInstanceAuthString gets the AUTH string for a Redis instance. If AUTH is not enabled for the +// instance the response will be empty. This information is not included in +// the details returned to GetInstance. +func (c *cloudRedisRESTClient) GetInstanceAuthString(ctx context.Context, req *redispb.GetInstanceAuthStringRequest, opts ...gax.CallOption) (*redispb.InstanceAuthString, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - return &meta, nil -} + baseUrl.Path += fmt.Sprintf("/v1/%v/authString", req.GetName()) -// Done reports whether the long-running operation has completed. -func (op *CreateInstanceOperation) Done() bool { - return op.lro.Done() -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") -// 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 *CreateInstanceOperation) Name() string { - return op.lro.Name() -} + baseUrl.RawQuery = params.Encode() -// DeleteInstanceOperation manages a long-running operation from DeleteInstance. -type DeleteInstanceOperation struct { - lro *longrunning.Operation -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) -// DeleteInstanceOperation returns a new DeleteInstanceOperation from a given name. -// The name must be that of a previously created DeleteInstanceOperation, possibly from a different process. -func (c *cloudRedisGRPCClient) DeleteInstanceOperation(name string) *DeleteInstanceOperation { - return &DeleteInstanceOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetInstanceAuthString[0:len((*c.CallOptions).GetInstanceAuthString):len((*c.CallOptions).GetInstanceAuthString)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &redispb.InstanceAuthString{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *DeleteInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { - return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil } -// Poll fetches the latest state of the long-running operation. +// CreateInstance creates a Redis instance based on the specified tier and memory size. // -// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// By default, the instance is accessible from the project’s +// default network (at https://cloud.google.com/vpc/docs/vpc). // -// If Poll fails, the error is returned and op is unmodified. If Poll succeeds and +// The creation is executed asynchronously and callers may check the returned +// operation to track its progress. Once the operation is completed the Redis +// instance will be fully functional. Completed longrunning.Operation will +// contain the new instance object in the response field. +// +// The returned operation is automatically deleted after a few hours, so there +// is no need to call DeleteOperation. +func (c *cloudRedisRESTClient) CreateInstance(ctx context.Context, req *redispb.CreateInstanceRequest, opts ...gax.CallOption) (*CreateInstanceOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetInstance() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/instances", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("instanceId", fmt.Sprintf("%v", req.GetInstanceId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateInstance updates the metadata and configuration of a specific Redis instance. +// +// Completed longrunning.Operation will contain the new instance object +// in the response field. The returned operation is automatically deleted +// after a few hours, so there is no need to call DeleteOperation. +func (c *cloudRedisRESTClient) UpdateInstance(ctx context.Context, req *redispb.UpdateInstanceRequest, opts ...gax.CallOption) (*UpdateInstanceOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetInstance() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetInstance().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "instance.name", url.QueryEscape(req.GetInstance().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpgradeInstance upgrades Redis instance to the newer Redis version specified in the +// request. +func (c *cloudRedisRESTClient) UpgradeInstance(ctx context.Context, req *redispb.UpgradeInstanceRequest, opts ...gax.CallOption) (*UpgradeInstanceOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:upgrade", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpgradeInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ImportInstance import a Redis RDB snapshot file from Cloud Storage into a Redis instance. +// +// Redis may stop serving during this operation. Instance state will be +// IMPORTING for entire operation. When complete, the instance will contain +// only data from the imported file. +// +// The returned operation is automatically deleted after a few hours, so +// there is no need to call DeleteOperation. +func (c *cloudRedisRESTClient) ImportInstance(ctx context.Context, req *redispb.ImportInstanceRequest, opts ...gax.CallOption) (*ImportInstanceOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:import", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &ImportInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ExportInstance export Redis instance data into a Redis RDB format file in Cloud Storage. +// +// Redis will continue serving during this operation. +// +// The returned operation is automatically deleted after a few hours, so +// there is no need to call DeleteOperation. +func (c *cloudRedisRESTClient) ExportInstance(ctx context.Context, req *redispb.ExportInstanceRequest, opts ...gax.CallOption) (*ExportInstanceOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:export", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &ExportInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// FailoverInstance initiates a failover of the primary node to current replica node for a +// specific STANDARD tier Cloud Memorystore for Redis instance. +func (c *cloudRedisRESTClient) FailoverInstance(ctx context.Context, req *redispb.FailoverInstanceRequest, opts ...gax.CallOption) (*FailoverInstanceOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:failover", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &FailoverInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteInstance deletes a specific Redis instance. Instance stops serving and data is +// deleted. +func (c *cloudRedisRESTClient) DeleteInstance(ctx context.Context, req *redispb.DeleteInstanceRequest, opts ...gax.CallOption) (*DeleteInstanceOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// RescheduleMaintenance reschedule maintenance for a given instance in a given project and +// location. +func (c *cloudRedisRESTClient) RescheduleMaintenance(ctx context.Context, req *redispb.RescheduleMaintenanceRequest, opts ...gax.CallOption) (*RescheduleMaintenanceOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:rescheduleMaintenance", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &RescheduleMaintenanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// CreateInstanceOperation manages a long-running operation from CreateInstance. +type CreateInstanceOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateInstanceOperation returns a new CreateInstanceOperation from a given name. +// The name must be that of a previously created CreateInstanceOperation, possibly from a different process. +func (c *cloudRedisGRPCClient) CreateInstanceOperation(name string) *CreateInstanceOperation { + return &CreateInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateInstanceOperation returns a new CreateInstanceOperation from a given name. +// The name must be that of a previously created CreateInstanceOperation, possibly from a different process. +func (c *cloudRedisRESTClient) CreateInstanceOperation(name string) *CreateInstanceOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CreateInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*redispb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp redispb.Instance + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *CreateInstanceOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*redispb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp redispb.Instance + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *CreateInstanceOperation) Metadata() (*redispb.OperationMetadata, error) { + var meta redispb.OperationMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *CreateInstanceOperation) Done() bool { + return op.lro.Done() +} + +// 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 *CreateInstanceOperation) Name() string { + return op.lro.Name() +} + +// DeleteInstanceOperation manages a long-running operation from DeleteInstance. +type DeleteInstanceOperation struct { + lro *longrunning.Operation + pollPath string +} + +// DeleteInstanceOperation returns a new DeleteInstanceOperation from a given name. +// The name must be that of a previously created DeleteInstanceOperation, possibly from a different process. +func (c *cloudRedisGRPCClient) DeleteInstanceOperation(name string) *DeleteInstanceOperation { + return &DeleteInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// DeleteInstanceOperation returns a new DeleteInstanceOperation from a given name. +// The name must be that of a previously created DeleteInstanceOperation, possibly from a different process. +func (c *cloudRedisRESTClient) DeleteInstanceOperation(name string) *DeleteInstanceOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *DeleteInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteInstanceOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -837,7 +1780,8 @@ func (op *DeleteInstanceOperation) Name() string { // ExportInstanceOperation manages a long-running operation from ExportInstance. type ExportInstanceOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // ExportInstanceOperation returns a new ExportInstanceOperation from a given name. @@ -848,10 +1792,21 @@ func (c *cloudRedisGRPCClient) ExportInstanceOperation(name string) *ExportInsta } } +// ExportInstanceOperation returns a new ExportInstanceOperation from a given name. +// The name must be that of a previously created ExportInstanceOperation, possibly from a different process. +func (c *cloudRedisRESTClient) ExportInstanceOperation(name string) *ExportInstanceOperation { + override := fmt.Sprintf("/v1/%s", name) + return &ExportInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *ExportInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*redispb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp redispb.Instance if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -869,6 +1824,7 @@ func (op *ExportInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOpt // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *ExportInstanceOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*redispb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp redispb.Instance if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -906,7 +1862,8 @@ func (op *ExportInstanceOperation) Name() string { // FailoverInstanceOperation manages a long-running operation from FailoverInstance. type FailoverInstanceOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // FailoverInstanceOperation returns a new FailoverInstanceOperation from a given name. @@ -917,10 +1874,21 @@ func (c *cloudRedisGRPCClient) FailoverInstanceOperation(name string) *FailoverI } } +// FailoverInstanceOperation returns a new FailoverInstanceOperation from a given name. +// The name must be that of a previously created FailoverInstanceOperation, possibly from a different process. +func (c *cloudRedisRESTClient) FailoverInstanceOperation(name string) *FailoverInstanceOperation { + override := fmt.Sprintf("/v1/%s", name) + return &FailoverInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *FailoverInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*redispb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp redispb.Instance if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -938,6 +1906,7 @@ func (op *FailoverInstanceOperation) Wait(ctx context.Context, opts ...gax.CallO // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *FailoverInstanceOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*redispb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp redispb.Instance if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -975,7 +1944,8 @@ func (op *FailoverInstanceOperation) Name() string { // ImportInstanceOperation manages a long-running operation from ImportInstance. type ImportInstanceOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // ImportInstanceOperation returns a new ImportInstanceOperation from a given name. @@ -986,10 +1956,21 @@ func (c *cloudRedisGRPCClient) ImportInstanceOperation(name string) *ImportInsta } } +// ImportInstanceOperation returns a new ImportInstanceOperation from a given name. +// The name must be that of a previously created ImportInstanceOperation, possibly from a different process. +func (c *cloudRedisRESTClient) ImportInstanceOperation(name string) *ImportInstanceOperation { + override := fmt.Sprintf("/v1/%s", name) + return &ImportInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *ImportInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*redispb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp redispb.Instance if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1007,6 +1988,7 @@ func (op *ImportInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOpt // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *ImportInstanceOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*redispb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp redispb.Instance if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1044,7 +2026,8 @@ func (op *ImportInstanceOperation) Name() string { // RescheduleMaintenanceOperation manages a long-running operation from RescheduleMaintenance. type RescheduleMaintenanceOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // RescheduleMaintenanceOperation returns a new RescheduleMaintenanceOperation from a given name. @@ -1055,10 +2038,21 @@ func (c *cloudRedisGRPCClient) RescheduleMaintenanceOperation(name string) *Resc } } +// RescheduleMaintenanceOperation returns a new RescheduleMaintenanceOperation from a given name. +// The name must be that of a previously created RescheduleMaintenanceOperation, possibly from a different process. +func (c *cloudRedisRESTClient) RescheduleMaintenanceOperation(name string) *RescheduleMaintenanceOperation { + override := fmt.Sprintf("/v1/%s", name) + return &RescheduleMaintenanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *RescheduleMaintenanceOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*redispb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp redispb.Instance if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1076,6 +2070,7 @@ func (op *RescheduleMaintenanceOperation) Wait(ctx context.Context, opts ...gax. // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *RescheduleMaintenanceOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*redispb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp redispb.Instance if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1113,7 +2108,8 @@ func (op *RescheduleMaintenanceOperation) Name() string { // UpdateInstanceOperation manages a long-running operation from UpdateInstance. type UpdateInstanceOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateInstanceOperation returns a new UpdateInstanceOperation from a given name. @@ -1124,10 +2120,21 @@ func (c *cloudRedisGRPCClient) UpdateInstanceOperation(name string) *UpdateInsta } } +// UpdateInstanceOperation returns a new UpdateInstanceOperation from a given name. +// The name must be that of a previously created UpdateInstanceOperation, possibly from a different process. +func (c *cloudRedisRESTClient) UpdateInstanceOperation(name string) *UpdateInstanceOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*redispb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp redispb.Instance if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1145,6 +2152,7 @@ func (op *UpdateInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOpt // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateInstanceOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*redispb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp redispb.Instance if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1182,7 +2190,8 @@ func (op *UpdateInstanceOperation) Name() string { // UpgradeInstanceOperation manages a long-running operation from UpgradeInstance. type UpgradeInstanceOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpgradeInstanceOperation returns a new UpgradeInstanceOperation from a given name. @@ -1193,10 +2202,21 @@ func (c *cloudRedisGRPCClient) UpgradeInstanceOperation(name string) *UpgradeIns } } +// UpgradeInstanceOperation returns a new UpgradeInstanceOperation from a given name. +// The name must be that of a previously created UpgradeInstanceOperation, possibly from a different process. +func (c *cloudRedisRESTClient) UpgradeInstanceOperation(name string) *UpgradeInstanceOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpgradeInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpgradeInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*redispb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp redispb.Instance if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1214,6 +2234,7 @@ func (op *UpgradeInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOp // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpgradeInstanceOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*redispb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp redispb.Instance if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/redis/apiv1/cloud_redis_client_example_test.go b/redis/apiv1/cloud_redis_client_example_test.go index 7d3bc89b2849..3f81bb41e48e 100644 --- a/redis/apiv1/cloud_redis_client_example_test.go +++ b/redis/apiv1/cloud_redis_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewCloudRedisClient() { _ = c } +func ExampleNewCloudRedisRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := redis.NewCloudRedisRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleCloudRedisClient_ListInstances() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/redis/apiv1/doc.go b/redis/apiv1/doc.go index fc4d789cb529..112a6336828d 100644 --- a/redis/apiv1/doc.go +++ b/redis/apiv1/doc.go @@ -86,6 +86,8 @@ package redis // import "cloud.google.com/go/redis/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -174,3 +176,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/redis/apiv1/gapic_metadata.json b/redis/apiv1/gapic_metadata.json index 4e47c10042a7..5c5bf65e127b 100644 --- a/redis/apiv1/gapic_metadata.json +++ b/redis/apiv1/gapic_metadata.json @@ -66,6 +66,66 @@ ] } } + }, + "rest": { + "libraryClient": "CloudRedisClient", + "rpcs": { + "CreateInstance": { + "methods": [ + "CreateInstance" + ] + }, + "DeleteInstance": { + "methods": [ + "DeleteInstance" + ] + }, + "ExportInstance": { + "methods": [ + "ExportInstance" + ] + }, + "FailoverInstance": { + "methods": [ + "FailoverInstance" + ] + }, + "GetInstance": { + "methods": [ + "GetInstance" + ] + }, + "GetInstanceAuthString": { + "methods": [ + "GetInstanceAuthString" + ] + }, + "ImportInstance": { + "methods": [ + "ImportInstance" + ] + }, + "ListInstances": { + "methods": [ + "ListInstances" + ] + }, + "RescheduleMaintenance": { + "methods": [ + "RescheduleMaintenance" + ] + }, + "UpdateInstance": { + "methods": [ + "UpdateInstance" + ] + }, + "UpgradeInstance": { + "methods": [ + "UpgradeInstance" + ] + } + } } } } diff --git a/redis/apiv1/redispb/cloud_redis.pb.go b/redis/apiv1/redispb/cloud_redis.pb.go index 711c90596358..4c10556625c6 100644 --- a/redis/apiv1/redispb/cloud_redis.pb.go +++ b/redis/apiv1/redispb/cloud_redis.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/redis/v1/cloud_redis.proto package redispb @@ -523,8 +523,7 @@ type Instance struct { // Required. Unique name of the resource in this scope including project and // location using the form: - // - // `projects/{project_id}/locations/{location_id}/instances/{instance_id}` + // `projects/{project_id}/locations/{location_id}/instances/{instance_id}` // // Note: Redis instances are managed and addressed at regional level so // location_id here refers to a GCP region; however, users may choose which @@ -552,10 +551,10 @@ type Instance struct { // If not provided, latest supported version will be used. Currently, the // supported values are: // - // - `REDIS_3_2` for Redis 3.2 compatibility - // - `REDIS_4_0` for Redis 4.0 compatibility (default) - // - `REDIS_5_0` for Redis 5.0 compatibility - // - `REDIS_6_X` for Redis 6.x compatibility + // * `REDIS_3_2` for Redis 3.2 compatibility + // * `REDIS_4_0` for Redis 4.0 compatibility (default) + // * `REDIS_5_0` for Redis 5.0 compatibility + // * `REDIS_6_X` for Redis 6.x compatibility RedisVersion string `protobuf:"bytes,7,opt,name=redis_version,json=redisVersion,proto3" json:"redis_version,omitempty"` // Optional. For DIRECT_PEERING mode, the CIDR range of internal addresses // that are reserved for this instance. Range must @@ -592,22 +591,22 @@ type Instance struct { // http://redis.io/topics/config. Currently, the only supported parameters // are: // - // Redis version 3.2 and newer: + // Redis version 3.2 and newer: // - // * maxmemory-policy - // * notify-keyspace-events + // * maxmemory-policy + // * notify-keyspace-events // - // Redis version 4.0 and newer: + // Redis version 4.0 and newer: // - // * activedefrag - // * lfu-decay-time - // * lfu-log-factor - // * maxmemory-gb + // * activedefrag + // * lfu-decay-time + // * lfu-log-factor + // * maxmemory-gb // - // Redis version 5.0 and newer: + // Redis version 5.0 and newer: // - // * stream-node-max-bytes - // * stream-node-max-entries + // * stream-node-max-bytes + // * stream-node-max-entries RedisConfigs map[string]string `protobuf:"bytes,16,rep,name=redis_configs,json=redisConfigs,proto3" json:"redis_configs,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` // Required. The service tier of the instance. Tier Instance_Tier `protobuf:"varint,17,opt,name=tier,proto3,enum=google.cloud.redis.v1.Instance_Tier" json:"tier,omitempty"` @@ -911,9 +910,7 @@ type RescheduleMaintenanceRequest struct { unknownFields protoimpl.UnknownFields // Required. Redis instance resource name using the form: - // - // `projects/{project_id}/locations/{location_id}/instances/{instance_id}` - // + // `projects/{project_id}/locations/{location_id}/instances/{instance_id}` // where `location_id` refers to a GCP region. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Required. If reschedule type is SPECIFIC_TIME, must set up schedule_time as well. @@ -1107,7 +1104,7 @@ func (x *WeeklyMaintenanceWindow) GetDay() dayofweek.DayOfWeek { if x != nil { return x.Day } - return dayofweek.DayOfWeek_DAY_OF_WEEK_UNSPECIFIED + return dayofweek.DayOfWeek(0) } func (x *WeeklyMaintenanceWindow) GetStartTime() *timeofday.TimeOfDay { @@ -1212,9 +1209,7 @@ type ListInstancesRequest struct { unknownFields protoimpl.UnknownFields // Required. The resource name of the instance location using the form: - // - // `projects/{project_id}/locations/{location_id}` - // + // `projects/{project_id}/locations/{location_id}` // where `location_id` refers to a GCP region. Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // The maximum number of items to return. @@ -1368,9 +1363,7 @@ type GetInstanceRequest struct { unknownFields protoimpl.UnknownFields // Required. Redis instance resource name using the form: - // - // `projects/{project_id}/locations/{location_id}/instances/{instance_id}` - // + // `projects/{project_id}/locations/{location_id}/instances/{instance_id}` // where `location_id` refers to a GCP region. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` } @@ -1421,9 +1414,7 @@ type GetInstanceAuthStringRequest struct { unknownFields protoimpl.UnknownFields // Required. Redis instance resource name using the form: - // - // `projects/{project_id}/locations/{location_id}/instances/{instance_id}` - // + // `projects/{project_id}/locations/{location_id}/instances/{instance_id}` // where `location_id` refers to a GCP region. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` } @@ -1523,9 +1514,7 @@ type CreateInstanceRequest struct { unknownFields protoimpl.UnknownFields // Required. The resource name of the instance location using the form: - // - // `projects/{project_id}/locations/{location_id}` - // + // `projects/{project_id}/locations/{location_id}` // where `location_id` refers to a GCP region. Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // Required. The logical name of the Redis instance in the customer project @@ -1604,11 +1593,11 @@ type UpdateInstanceRequest struct { // this field. The elements of the repeated paths field may only include these // fields from [Instance][google.cloud.redis.v1.Instance]: // - // - `displayName` - // - `labels` - // - `memorySizeGb` - // - `redisConfig` - // - `replica_count` + // * `displayName` + // * `labels` + // * `memorySizeGb` + // * `redisConfig` + // * `replica_count` UpdateMask *fieldmaskpb.FieldMask `protobuf:"bytes,1,opt,name=update_mask,json=updateMask,proto3" json:"update_mask,omitempty"` // Required. Update description. // Only fields specified in update_mask are updated. @@ -1668,9 +1657,7 @@ type UpgradeInstanceRequest struct { unknownFields protoimpl.UnknownFields // Required. Redis instance resource name using the form: - // - // `projects/{project_id}/locations/{location_id}/instances/{instance_id}` - // + // `projects/{project_id}/locations/{location_id}/instances/{instance_id}` // where `location_id` refers to a GCP region. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Required. Specifies the target version of Redis software to upgrade to. @@ -1730,9 +1717,7 @@ type DeleteInstanceRequest struct { unknownFields protoimpl.UnknownFields // Required. Redis instance resource name using the form: - // - // `projects/{project_id}/locations/{location_id}/instances/{instance_id}` - // + // `projects/{project_id}/locations/{location_id}/instances/{instance_id}` // where `location_id` refers to a GCP region. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` } @@ -1834,7 +1819,6 @@ type InputConfig struct { // Required. Specify source location of input data // // Types that are assignable to Source: - // // *InputConfig_GcsSource Source isInputConfig_Source `protobuf_oneof:"source"` } @@ -1903,9 +1887,7 @@ type ImportInstanceRequest struct { unknownFields protoimpl.UnknownFields // Required. Redis instance resource name using the form: - // - // `projects/{project_id}/locations/{location_id}/instances/{instance_id}` - // + // `projects/{project_id}/locations/{location_id}/instances/{instance_id}` // where `location_id` refers to a GCP region. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Required. Specify data to be imported. @@ -2017,7 +1999,6 @@ type OutputConfig struct { // Required. Specify destination location of output data // // Types that are assignable to Destination: - // // *OutputConfig_GcsDestination Destination isOutputConfig_Destination `protobuf_oneof:"destination"` } @@ -2086,9 +2067,7 @@ type ExportInstanceRequest struct { unknownFields protoimpl.UnknownFields // Required. Redis instance resource name using the form: - // - // `projects/{project_id}/locations/{location_id}/instances/{instance_id}` - // + // `projects/{project_id}/locations/{location_id}/instances/{instance_id}` // where `location_id` refers to a GCP region. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Required. Specify data to be exported. @@ -2148,9 +2127,7 @@ type FailoverInstanceRequest struct { unknownFields protoimpl.UnknownFields // Required. Redis instance resource name using the form: - // - // `projects/{project_id}/locations/{location_id}/instances/{instance_id}` - // + // `projects/{project_id}/locations/{location_id}/instances/{instance_id}` // where `location_id` refers to a GCP region. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Optional. Available data protection modes that the user can choose. If it's diff --git a/redis/apiv1beta1/cloud_redis_client.go b/redis/apiv1beta1/cloud_redis_client.go index 998d5aaf843c..6f12df02bcc1 100644 --- a/redis/apiv1beta1/cloud_redis_client.go +++ b/redis/apiv1beta1/cloud_redis_client.go @@ -858,6 +858,7 @@ func (c *cloudRedisRESTClient) ListInstances(ctx context.Context, req *redispb.L baseUrl.Path += fmt.Sprintf("/v1beta1/%v/instances", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -931,6 +932,11 @@ func (c *cloudRedisRESTClient) GetInstance(ctx context.Context, req *redispb.Get } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -986,6 +992,11 @@ func (c *cloudRedisRESTClient) GetInstanceAuthString(ctx context.Context, req *r } baseUrl.Path += fmt.Sprintf("/v1beta1/%v/authString", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1058,6 +1069,7 @@ func (c *cloudRedisRESTClient) CreateInstance(ctx context.Context, req *redispb. baseUrl.Path += fmt.Sprintf("/v1beta1/%v/instances", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("instanceId", fmt.Sprintf("%v", req.GetInstanceId())) baseUrl.RawQuery = params.Encode() @@ -1131,6 +1143,7 @@ func (c *cloudRedisRESTClient) UpdateInstance(ctx context.Context, req *redispb. baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetInstance().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -1205,6 +1218,11 @@ func (c *cloudRedisRESTClient) UpgradeInstance(ctx context.Context, req *redispb } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:upgrade", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1275,6 +1293,11 @@ func (c *cloudRedisRESTClient) ImportInstance(ctx context.Context, req *redispb. } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:import", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1343,6 +1366,11 @@ func (c *cloudRedisRESTClient) ExportInstance(ctx context.Context, req *redispb. } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:export", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1407,6 +1435,11 @@ func (c *cloudRedisRESTClient) FailoverInstance(ctx context.Context, req *redisp } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:failover", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1465,6 +1498,11 @@ func (c *cloudRedisRESTClient) DeleteInstance(ctx context.Context, req *redispb. } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1529,6 +1567,11 @@ func (c *cloudRedisRESTClient) RescheduleMaintenance(ctx context.Context, req *r } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:rescheduleMaintenance", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) diff --git a/redis/apiv1beta1/redispb/cloud_redis.pb.go b/redis/apiv1beta1/redispb/cloud_redis.pb.go index 593b83b8324f..486deabc6e99 100644 --- a/redis/apiv1beta1/redispb/cloud_redis.pb.go +++ b/redis/apiv1beta1/redispb/cloud_redis.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/redis/v1beta1/cloud_redis.proto package redispb @@ -638,8 +638,7 @@ type Instance struct { // Required. Unique name of the resource in this scope including project and // location using the form: - // - // `projects/{project_id}/locations/{location_id}/instances/{instance_id}` + // `projects/{project_id}/locations/{location_id}/instances/{instance_id}` // // Note: Redis instances are managed and addressed at regional level so // location_id here refers to a GCP region; however, users may choose which @@ -667,10 +666,10 @@ type Instance struct { // If not provided, latest supported version will be used. Currently, the // supported values are: // - // - `REDIS_3_2` for Redis 3.2 compatibility - // - `REDIS_4_0` for Redis 4.0 compatibility (default) - // - `REDIS_5_0` for Redis 5.0 compatibility - // - `REDIS_6_X` for Redis 6.x compatibility + // * `REDIS_3_2` for Redis 3.2 compatibility + // * `REDIS_4_0` for Redis 4.0 compatibility (default) + // * `REDIS_5_0` for Redis 5.0 compatibility + // * `REDIS_6_X` for Redis 6.x compatibility RedisVersion string `protobuf:"bytes,7,opt,name=redis_version,json=redisVersion,proto3" json:"redis_version,omitempty"` // Optional. For DIRECT_PEERING mode, the CIDR range of internal addresses // that are reserved for this instance. Range must @@ -688,8 +687,7 @@ type Instance struct { // service access connection, or "auto". SecondaryIpRange string `protobuf:"bytes,30,opt,name=secondary_ip_range,json=secondaryIpRange,proto3" json:"secondary_ip_range,omitempty"` // Output only. Hostname or IP address of the exposed Redis endpoint used by - // - // clients to connect to the service. + // clients to connect to the service. Host string `protobuf:"bytes,10,opt,name=host,proto3" json:"host,omitempty"` // Output only. The port number of the exposed Redis endpoint. Port int32 `protobuf:"varint,11,opt,name=port,proto3" json:"port,omitempty"` @@ -708,22 +706,22 @@ type Instance struct { // http://redis.io/topics/config. Currently, the only supported parameters // are: // - // Redis version 3.2 and newer: + // Redis version 3.2 and newer: // - // * maxmemory-policy - // * notify-keyspace-events + // * maxmemory-policy + // * notify-keyspace-events // - // Redis version 4.0 and newer: + // Redis version 4.0 and newer: // - // * activedefrag - // * lfu-decay-time - // * lfu-log-factor - // * maxmemory-gb + // * activedefrag + // * lfu-decay-time + // * lfu-log-factor + // * maxmemory-gb // - // Redis version 5.0 and newer: + // Redis version 5.0 and newer: // - // * stream-node-max-bytes - // * stream-node-max-entries + // * stream-node-max-bytes + // * stream-node-max-entries RedisConfigs map[string]string `protobuf:"bytes,16,rep,name=redis_configs,json=redisConfigs,proto3" json:"redis_configs,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` // Required. The service tier of the instance. Tier Instance_Tier `protobuf:"varint,17,opt,name=tier,proto3,enum=google.cloud.redis.v1beta1.Instance_Tier" json:"tier,omitempty"` @@ -1120,9 +1118,7 @@ type RescheduleMaintenanceRequest struct { unknownFields protoimpl.UnknownFields // Required. Redis instance resource name using the form: - // - // `projects/{project_id}/locations/{location_id}/instances/{instance_id}` - // + // `projects/{project_id}/locations/{location_id}/instances/{instance_id}` // where `location_id` refers to a GCP region. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Required. If reschedule type is SPECIFIC_TIME, must set up schedule_time as well. @@ -1316,7 +1312,7 @@ func (x *WeeklyMaintenanceWindow) GetDay() dayofweek.DayOfWeek { if x != nil { return x.Day } - return dayofweek.DayOfWeek_DAY_OF_WEEK_UNSPECIFIED + return dayofweek.DayOfWeek(0) } func (x *WeeklyMaintenanceWindow) GetStartTime() *timeofday.TimeOfDay { @@ -1421,9 +1417,7 @@ type ListInstancesRequest struct { unknownFields protoimpl.UnknownFields // Required. The resource name of the instance location using the form: - // - // `projects/{project_id}/locations/{location_id}` - // + // `projects/{project_id}/locations/{location_id}` // where `location_id` refers to a GCP region. Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // The maximum number of items to return. @@ -1577,9 +1571,7 @@ type GetInstanceRequest struct { unknownFields protoimpl.UnknownFields // Required. Redis instance resource name using the form: - // - // `projects/{project_id}/locations/{location_id}/instances/{instance_id}` - // + // `projects/{project_id}/locations/{location_id}/instances/{instance_id}` // where `location_id` refers to a GCP region. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` } @@ -1630,9 +1622,7 @@ type GetInstanceAuthStringRequest struct { unknownFields protoimpl.UnknownFields // Required. Redis instance resource name using the form: - // - // `projects/{project_id}/locations/{location_id}/instances/{instance_id}` - // + // `projects/{project_id}/locations/{location_id}/instances/{instance_id}` // where `location_id` refers to a GCP region. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` } @@ -1732,9 +1722,7 @@ type CreateInstanceRequest struct { unknownFields protoimpl.UnknownFields // Required. The resource name of the instance location using the form: - // - // `projects/{project_id}/locations/{location_id}` - // + // `projects/{project_id}/locations/{location_id}` // where `location_id` refers to a GCP region. Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // Required. The logical name of the Redis instance in the customer project @@ -1813,11 +1801,11 @@ type UpdateInstanceRequest struct { // this field. The elements of the repeated paths field may only include these // fields from [Instance][google.cloud.redis.v1beta1.Instance]: // - // - `displayName` - // - `labels` - // - `memorySizeGb` - // - `redisConfig` - // - `replica_count` + // * `displayName` + // * `labels` + // * `memorySizeGb` + // * `redisConfig` + // * `replica_count` UpdateMask *fieldmaskpb.FieldMask `protobuf:"bytes,1,opt,name=update_mask,json=updateMask,proto3" json:"update_mask,omitempty"` // Required. Update description. // Only fields specified in update_mask are updated. @@ -1877,9 +1865,7 @@ type UpgradeInstanceRequest struct { unknownFields protoimpl.UnknownFields // Required. Redis instance resource name using the form: - // - // `projects/{project_id}/locations/{location_id}/instances/{instance_id}` - // + // `projects/{project_id}/locations/{location_id}/instances/{instance_id}` // where `location_id` refers to a GCP region. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Required. Specifies the target version of Redis software to upgrade to. @@ -1939,9 +1925,7 @@ type DeleteInstanceRequest struct { unknownFields protoimpl.UnknownFields // Required. Redis instance resource name using the form: - // - // `projects/{project_id}/locations/{location_id}/instances/{instance_id}` - // + // `projects/{project_id}/locations/{location_id}/instances/{instance_id}` // where `location_id` refers to a GCP region. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` } @@ -2043,7 +2027,6 @@ type InputConfig struct { // Required. Specify source location of input data // // Types that are assignable to Source: - // // *InputConfig_GcsSource Source isInputConfig_Source `protobuf_oneof:"source"` } @@ -2112,9 +2095,7 @@ type ImportInstanceRequest struct { unknownFields protoimpl.UnknownFields // Required. Redis instance resource name using the form: - // - // `projects/{project_id}/locations/{location_id}/instances/{instance_id}` - // + // `projects/{project_id}/locations/{location_id}/instances/{instance_id}` // where `location_id` refers to a GCP region. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Required. Specify data to be imported. @@ -2226,7 +2207,6 @@ type OutputConfig struct { // Required. Specify destination location of output data // // Types that are assignable to Destination: - // // *OutputConfig_GcsDestination Destination isOutputConfig_Destination `protobuf_oneof:"destination"` } @@ -2295,9 +2275,7 @@ type ExportInstanceRequest struct { unknownFields protoimpl.UnknownFields // Required. Redis instance resource name using the form: - // - // `projects/{project_id}/locations/{location_id}/instances/{instance_id}` - // + // `projects/{project_id}/locations/{location_id}/instances/{instance_id}` // where `location_id` refers to a GCP region. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Required. Specify data to be exported. @@ -2357,9 +2335,7 @@ type FailoverInstanceRequest struct { unknownFields protoimpl.UnknownFields // Required. Redis instance resource name using the form: - // - // `projects/{project_id}/locations/{location_id}/instances/{instance_id}` - // + // `projects/{project_id}/locations/{location_id}/instances/{instance_id}` // where `location_id` refers to a GCP region. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Optional. Available data protection modes that the user can choose. If it's diff --git a/resourcemanager/apiv2/doc.go b/resourcemanager/apiv2/doc.go index 2db1bb11ef19..711af3fd3e0d 100644 --- a/resourcemanager/apiv2/doc.go +++ b/resourcemanager/apiv2/doc.go @@ -87,6 +87,8 @@ package resourcemanager // import "cloud.google.com/go/resourcemanager/apiv2" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -176,3 +178,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/resourcemanager/apiv2/folders_client.go b/resourcemanager/apiv2/folders_client.go index 402319936711..a74c84e7b991 100644 --- a/resourcemanager/apiv2/folders_client.go +++ b/resourcemanager/apiv2/folders_client.go @@ -17,9 +17,12 @@ package resourcemanager import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,14 +30,17 @@ import ( lroauto "cloud.google.com/go/longrunning/autogen" resourcemanagerpb "cloud.google.com/go/resourcemanager/apiv2/resourcemanagerpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" iampb "google.golang.org/genproto/googleapis/iam/v1" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -83,6 +89,22 @@ func defaultFoldersCallOptions() *FoldersCallOptions { } } +func defaultFoldersRESTCallOptions() *FoldersCallOptions { + return &FoldersCallOptions{ + ListFolders: []gax.CallOption{}, + SearchFolders: []gax.CallOption{}, + GetFolder: []gax.CallOption{}, + CreateFolder: []gax.CallOption{}, + UpdateFolder: []gax.CallOption{}, + MoveFolder: []gax.CallOption{}, + DeleteFolder: []gax.CallOption{}, + UndeleteFolder: []gax.CallOption{}, + GetIamPolicy: []gax.CallOption{}, + SetIamPolicy: []gax.CallOption{}, + TestIamPermissions: []gax.CallOption{}, + } +} + // internalFoldersClient is an interface that defines the methods available from Cloud Resource Manager API. type internalFoldersClient interface { Close() error @@ -413,6 +435,91 @@ func (c *foldersGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type foldersRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing FoldersClient + CallOptions **FoldersCallOptions +} + +// NewFoldersRESTClient creates a new folders rest client. +// +// Manages Cloud Resource Folders. +// Cloud Resource Folders can be used to organize the resources under an +// organization and to control the IAM policies applied to groups of resources. +func NewFoldersRESTClient(ctx context.Context, opts ...option.ClientOption) (*FoldersClient, error) { + clientOpts := append(defaultFoldersRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultFoldersRESTCallOptions() + c := &foldersRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &FoldersClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultFoldersRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://cloudresourcemanager.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://cloudresourcemanager.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://cloudresourcemanager.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *foldersRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *foldersRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *foldersRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *foldersGRPCClient) ListFolders(ctx context.Context, req *resourcemanagerpb.ListFoldersRequest, opts ...gax.CallOption) *FolderIterator { ctx = insertMetadata(ctx, c.xGoogMetadata) opts = append((*c.CallOptions).ListFolders[0:len((*c.CallOptions).ListFolders):len((*c.CallOptions).ListFolders)], opts...) @@ -654,85 +761,974 @@ func (c *foldersGRPCClient) TestIamPermissions(ctx context.Context, req *iampb.T return resp, nil } -// CreateFolderOperation manages a long-running operation from CreateFolder. -type CreateFolderOperation struct { - lro *longrunning.Operation -} +// ListFolders lists the Folders that are direct descendants of supplied parent resource. +// List provides a strongly consistent view of the Folders underneath +// the specified parent resource. +// List returns Folders sorted based upon the (ascending) lexical ordering +// of their display_name. +// The caller must have resourcemanager.folders.list permission on the +// identified parent. +func (c *foldersRESTClient) ListFolders(ctx context.Context, req *resourcemanagerpb.ListFoldersRequest, opts ...gax.CallOption) *FolderIterator { + it := &FolderIterator{} + req = proto.Clone(req).(*resourcemanagerpb.ListFoldersRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*resourcemanagerpb.Folder, string, error) { + resp := &resourcemanagerpb.ListFoldersResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/folders") -// CreateFolderOperation returns a new CreateFolderOperation from a given name. -// The name must be that of a previously created CreateFolderOperation, possibly from a different process. -func (c *foldersGRPCClient) CreateFolderOperation(name string) *CreateFolderOperation { - return &CreateFolderOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + params.Add("parent", fmt.Sprintf("%v", req.GetParent())) + if req.GetShowDeleted() { + params.Add("showDeleted", fmt.Sprintf("%v", req.GetShowDeleted())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetFolders(), resp.GetNextPageToken(), nil } -} -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *CreateFolderOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*resourcemanagerpb.Folder, error) { - var resp resourcemanagerpb.Folder - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { - return nil, err + 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 } - return &resp, nil + + it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it } -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// SearchFolders search for folders that match specific filter criteria. +// Search provides an eventually consistent view of the folders a user has +// access to which meet the specified filter criteria. // -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *CreateFolderOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*resourcemanagerpb.Folder, error) { - var resp resourcemanagerpb.Folder - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { - return nil, err +// This will only return folders on which the caller has the +// permission resourcemanager.folders.get. +func (c *foldersRESTClient) SearchFolders(ctx context.Context, req *resourcemanagerpb.SearchFoldersRequest, opts ...gax.CallOption) *FolderIterator { + it := &FolderIterator{} + req = proto.Clone(req).(*resourcemanagerpb.SearchFoldersRequest) + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*resourcemanagerpb.Folder, string, error) { + resp := &resourcemanagerpb.SearchFoldersResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, "", err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/folders:search") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetFolders(), resp.GetNextPageToken(), nil } - if !op.Done() { - return nil, 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 } - return &resp, nil + + it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it } -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *CreateFolderOperation) Metadata() (*resourcemanagerpb.FolderOperation, error) { - var meta resourcemanagerpb.FolderOperation - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { +// GetFolder retrieves a Folder identified by the supplied resource name. +// Valid Folder resource names have the format folders/{folder_id} +// (for example, folders/1234). +// The caller must have resourcemanager.folders.get permission on the +// identified folder. +func (c *foldersRESTClient) GetFolder(ctx context.Context, req *resourcemanagerpb.GetFolderRequest, opts ...gax.CallOption) (*resourcemanagerpb.Folder, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - return &meta, nil -} + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) -// Done reports whether the long-running operation has completed. -func (op *CreateFolderOperation) Done() bool { - return op.lro.Done() -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") -// 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 *CreateFolderOperation) Name() string { - return op.lro.Name() -} + baseUrl.RawQuery = params.Encode() -// MoveFolderOperation manages a long-running operation from MoveFolder. -type MoveFolderOperation struct { - lro *longrunning.Operation + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetFolder[0:len((*c.CallOptions).GetFolder):len((*c.CallOptions).GetFolder)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &resourcemanagerpb.Folder{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil } -// MoveFolderOperation returns a new MoveFolderOperation from a given name. -// The name must be that of a previously created MoveFolderOperation, possibly from a different process. -func (c *foldersGRPCClient) MoveFolderOperation(name string) *MoveFolderOperation { - return &MoveFolderOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), +// CreateFolder creates a Folder in the resource hierarchy. +// Returns an Operation which can be used to track the progress of the +// folder creation workflow. +// Upon success the Operation.response field will be populated with the +// created Folder. +// +// In order to succeed, the addition of this new Folder must not violate +// the Folder naming, height or fanout constraints. +// +// The Folder’s display_name must be distinct from all other Folder’s that +// share its parent. +// +// The addition of the Folder must not cause the active Folder hierarchy +// to exceed a height of 4. Note, the full active + deleted Folder hierarchy +// is allowed to reach a height of 8; this provides additional headroom when +// moving folders that contain deleted folders. +// +// The addition of the Folder must not cause the total number of Folders +// under its parent to exceed 100. +// +// If the operation fails due to a folder constraint violation, some errors +// may be returned by the CreateFolder request, with status code +// FAILED_PRECONDITION and an error description. Other folder constraint +// violations will be communicated in the Operation, with the specific +// PreconditionFailure returned via the details list in the Operation.error +// field. +// +// The caller must have resourcemanager.folders.create permission on the +// identified parent. +func (c *foldersRESTClient) CreateFolder(ctx context.Context, req *resourcemanagerpb.CreateFolderRequest, opts ...gax.CallOption) (*CreateFolderOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetFolder() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/folders") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("parent", fmt.Sprintf("%v", req.GetParent())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &CreateFolderOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateFolder updates a Folder, changing its display_name. +// Changes to the folder display_name will be rejected if they violate either +// the display_name formatting rules or naming constraints described in +// the CreateFolder documentation. +// +// The Folder’s display name must start and end with a letter or digit, +// may contain letters, digits, spaces, hyphens and underscores and can be +// no longer than 30 characters. This is captured by the regular expression: +// [\p{L}\p{N}]([\p{L}\p{N}_- ]{0,28}[\p{L}\p{N}])?. +// The caller must have resourcemanager.folders.update permission on the +// identified folder. +// +// If the update fails due to the unique name constraint then a +// PreconditionFailure explaining this violation will be returned +// in the Status.details field. +func (c *foldersRESTClient) UpdateFolder(ctx context.Context, req *resourcemanagerpb.UpdateFolderRequest, opts ...gax.CallOption) (*resourcemanagerpb.Folder, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetFolder() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetFolder().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "folder.name", url.QueryEscape(req.GetFolder().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateFolder[0:len((*c.CallOptions).UpdateFolder):len((*c.CallOptions).UpdateFolder)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &resourcemanagerpb.Folder{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// MoveFolder moves a Folder under a new resource parent. +// Returns an Operation which can be used to track the progress of the +// folder move workflow. +// Upon success the Operation.response field will be populated with the +// moved Folder. +// Upon failure, a FolderOperationError categorizing the failure cause will +// be returned - if the failure occurs synchronously then the +// FolderOperationError will be returned via the Status.details field +// and if it occurs asynchronously then the FolderOperation will be returned +// via the Operation.error field. +// In addition, the Operation.metadata field will be populated with a +// FolderOperation message as an aid to stateless clients. +// Folder moves will be rejected if they violate either the naming, height +// or fanout constraints described in the +// CreateFolder documentation. +// The caller must have resourcemanager.folders.move permission on the +// folder’s current and proposed new parent. +func (c *foldersRESTClient) MoveFolder(ctx context.Context, req *resourcemanagerpb.MoveFolderRequest, opts ...gax.CallOption) (*MoveFolderOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:move", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &MoveFolderOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteFolder requests deletion of a Folder. The Folder is moved into the +// DELETE_REQUESTED state +// immediately, and is deleted approximately 30 days later. This method may +// only be called on an empty Folder in the +// [ACTIVE][google.cloud.resourcemanager.v2.Folder.LifecycleState.ACTIVE (at http://google.cloud.resourcemanager.v2.Folder.LifecycleState.ACTIVE)] state, where a Folder is empty if +// it doesn’t contain any Folders or Projects in the +// [ACTIVE][google.cloud.resourcemanager.v2.Folder.LifecycleState.ACTIVE (at http://google.cloud.resourcemanager.v2.Folder.LifecycleState.ACTIVE)] state. +// The caller must have resourcemanager.folders.delete permission on the +// identified folder. +func (c *foldersRESTClient) DeleteFolder(ctx context.Context, req *resourcemanagerpb.DeleteFolderRequest, opts ...gax.CallOption) (*resourcemanagerpb.Folder, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRecursiveDelete() { + params.Add("recursiveDelete", fmt.Sprintf("%v", req.GetRecursiveDelete())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).DeleteFolder[0:len((*c.CallOptions).DeleteFolder):len((*c.CallOptions).DeleteFolder)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &resourcemanagerpb.Folder{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UndeleteFolder cancels the deletion request for a Folder. This method may only be +// called on a Folder in the +// DELETE_REQUESTED state. +// In order to succeed, the Folder’s parent must be in the +// [ACTIVE][google.cloud.resourcemanager.v2.Folder.LifecycleState.ACTIVE (at http://google.cloud.resourcemanager.v2.Folder.LifecycleState.ACTIVE)] state. +// In addition, reintroducing the folder into the tree must not violate +// folder naming, height and fanout constraints described in the +// CreateFolder documentation. +// The caller must have resourcemanager.folders.undelete permission on the +// identified folder. +func (c *foldersRESTClient) UndeleteFolder(ctx context.Context, req *resourcemanagerpb.UndeleteFolderRequest, opts ...gax.CallOption) (*resourcemanagerpb.Folder, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:undelete", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UndeleteFolder[0:len((*c.CallOptions).UndeleteFolder):len((*c.CallOptions).UndeleteFolder)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &resourcemanagerpb.Folder{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetIamPolicy gets the access control policy for a Folder. The returned policy may be +// empty if no such policy or resource exists. The resource field should +// be the Folder’s resource name, e.g. “folders/1234”. +// The caller must have resourcemanager.folders.getIamPolicy permission +// on the identified folder. +func (c *foldersRESTClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:getIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SetIamPolicy sets the access control policy on a Folder, replacing any existing policy. +// The resource field should be the Folder’s resource name, e.g. +// “folders/1234”. +// The caller must have resourcemanager.folders.setIamPolicy permission +// on the identified folder. +func (c *foldersRESTClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:setIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// TestIamPermissions returns permissions that a caller has on the specified Folder. +// The resource field should be the Folder’s resource name, +// e.g. “folders/1234”. +// +// There are no permissions required for making this API call. +func (c *foldersRESTClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:testIamPermissions", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.TestIamPermissionsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateFolderOperation manages a long-running operation from CreateFolder. +type CreateFolderOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateFolderOperation returns a new CreateFolderOperation from a given name. +// The name must be that of a previously created CreateFolderOperation, possibly from a different process. +func (c *foldersGRPCClient) CreateFolderOperation(name string) *CreateFolderOperation { + return &CreateFolderOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateFolderOperation returns a new CreateFolderOperation from a given name. +// The name must be that of a previously created CreateFolderOperation, possibly from a different process. +func (c *foldersRESTClient) CreateFolderOperation(name string) *CreateFolderOperation { + override := fmt.Sprintf("/v2/%s", name) + return &CreateFolderOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CreateFolderOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*resourcemanagerpb.Folder, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp resourcemanagerpb.Folder + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *CreateFolderOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*resourcemanagerpb.Folder, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp resourcemanagerpb.Folder + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *CreateFolderOperation) Metadata() (*resourcemanagerpb.FolderOperation, error) { + var meta resourcemanagerpb.FolderOperation + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *CreateFolderOperation) Done() bool { + return op.lro.Done() +} + +// 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 *CreateFolderOperation) Name() string { + return op.lro.Name() +} + +// MoveFolderOperation manages a long-running operation from MoveFolder. +type MoveFolderOperation struct { + lro *longrunning.Operation + pollPath string +} + +// MoveFolderOperation returns a new MoveFolderOperation from a given name. +// The name must be that of a previously created MoveFolderOperation, possibly from a different process. +func (c *foldersGRPCClient) MoveFolderOperation(name string) *MoveFolderOperation { + return &MoveFolderOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// MoveFolderOperation returns a new MoveFolderOperation from a given name. +// The name must be that of a previously created MoveFolderOperation, possibly from a different process. +func (c *foldersRESTClient) MoveFolderOperation(name string) *MoveFolderOperation { + override := fmt.Sprintf("/v2/%s", name) + return &MoveFolderOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, } } @@ -740,6 +1736,7 @@ func (c *foldersGRPCClient) MoveFolderOperation(name string) *MoveFolderOperatio // // See documentation of Poll for error-handling information. func (op *MoveFolderOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*resourcemanagerpb.Folder, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp resourcemanagerpb.Folder if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -757,6 +1754,7 @@ func (op *MoveFolderOperation) Wait(ctx context.Context, opts ...gax.CallOption) // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *MoveFolderOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*resourcemanagerpb.Folder, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp resourcemanagerpb.Folder if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/resourcemanager/apiv2/folders_client_example_test.go b/resourcemanager/apiv2/folders_client_example_test.go index a6df37e5eb2f..b9f12386c306 100644 --- a/resourcemanager/apiv2/folders_client_example_test.go +++ b/resourcemanager/apiv2/folders_client_example_test.go @@ -42,6 +42,23 @@ func ExampleNewFoldersClient() { _ = c } +func ExampleNewFoldersRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := resourcemanager.NewFoldersRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleFoldersClient_ListFolders() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/resourcemanager/apiv2/gapic_metadata.json b/resourcemanager/apiv2/gapic_metadata.json index 6f709286f1f4..2aefc73ff0fa 100644 --- a/resourcemanager/apiv2/gapic_metadata.json +++ b/resourcemanager/apiv2/gapic_metadata.json @@ -66,6 +66,66 @@ ] } } + }, + "rest": { + "libraryClient": "FoldersClient", + "rpcs": { + "CreateFolder": { + "methods": [ + "CreateFolder" + ] + }, + "DeleteFolder": { + "methods": [ + "DeleteFolder" + ] + }, + "GetFolder": { + "methods": [ + "GetFolder" + ] + }, + "GetIamPolicy": { + "methods": [ + "GetIamPolicy" + ] + }, + "ListFolders": { + "methods": [ + "ListFolders" + ] + }, + "MoveFolder": { + "methods": [ + "MoveFolder" + ] + }, + "SearchFolders": { + "methods": [ + "SearchFolders" + ] + }, + "SetIamPolicy": { + "methods": [ + "SetIamPolicy" + ] + }, + "TestIamPermissions": { + "methods": [ + "TestIamPermissions" + ] + }, + "UndeleteFolder": { + "methods": [ + "UndeleteFolder" + ] + }, + "UpdateFolder": { + "methods": [ + "UpdateFolder" + ] + } + } } } } diff --git a/resourcemanager/apiv2/resourcemanagerpb/folders.pb.go b/resourcemanager/apiv2/resourcemanagerpb/folders.pb.go index abff4db4e770..f67c42298f90 100644 --- a/resourcemanager/apiv2/resourcemanagerpb/folders.pb.go +++ b/resourcemanager/apiv2/resourcemanagerpb/folders.pb.go @@ -15,8 +15,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/resourcemanager/v2/folders.proto package resourcemanagerpb diff --git a/resourcemanager/apiv3/doc.go b/resourcemanager/apiv3/doc.go index 2fd178c615c8..6bd219f95306 100644 --- a/resourcemanager/apiv3/doc.go +++ b/resourcemanager/apiv3/doc.go @@ -83,6 +83,8 @@ package resourcemanager // import "cloud.google.com/go/resourcemanager/apiv3" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -172,3 +174,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/resourcemanager/apiv3/folders_client.go b/resourcemanager/apiv3/folders_client.go index 815f64f78cbb..1a18a939de53 100644 --- a/resourcemanager/apiv3/folders_client.go +++ b/resourcemanager/apiv3/folders_client.go @@ -17,9 +17,12 @@ package resourcemanager import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,15 +30,18 @@ import ( lroauto "cloud.google.com/go/longrunning/autogen" resourcemanagerpb "cloud.google.com/go/resourcemanager/apiv3/resourcemanagerpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" iampb "google.golang.org/genproto/googleapis/iam/v1" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -114,6 +120,49 @@ func defaultFoldersCallOptions() *FoldersCallOptions { } } +func defaultFoldersRESTCallOptions() *FoldersCallOptions { + return &FoldersCallOptions{ + GetFolder: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListFolders: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + SearchFolders: []gax.CallOption{}, + CreateFolder: []gax.CallOption{}, + UpdateFolder: []gax.CallOption{}, + MoveFolder: []gax.CallOption{}, + DeleteFolder: []gax.CallOption{}, + UndeleteFolder: []gax.CallOption{}, + GetIamPolicy: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + SetIamPolicy: []gax.CallOption{}, + TestIamPermissions: []gax.CallOption{}, + } +} + // internalFoldersClient is an interface that defines the methods available from Cloud Resource Manager API. type internalFoldersClient interface { Close() error @@ -464,6 +513,91 @@ func (c *foldersGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type foldersRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing FoldersClient + CallOptions **FoldersCallOptions +} + +// NewFoldersRESTClient creates a new folders rest client. +// +// Manages Cloud Platform folder resources. +// Folders can be used to organize the resources under an +// organization and to control the policies applied to groups of resources. +func NewFoldersRESTClient(ctx context.Context, opts ...option.ClientOption) (*FoldersClient, error) { + clientOpts := append(defaultFoldersRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultFoldersRESTCallOptions() + c := &foldersRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &FoldersClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultFoldersRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://cloudresourcemanager.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://cloudresourcemanager.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://cloudresourcemanager.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *foldersRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *foldersRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *foldersRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *foldersGRPCClient) GetFolder(ctx context.Context, req *resourcemanagerpb.GetFolderRequest, opts ...gax.CallOption) (*resourcemanagerpb.Folder, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) @@ -751,147 +885,1049 @@ func (c *foldersGRPCClient) TestIamPermissions(ctx context.Context, req *iampb.T return resp, nil } -// CreateFolderOperation manages a long-running operation from CreateFolder. -type CreateFolderOperation struct { - lro *longrunning.Operation -} - -// CreateFolderOperation returns a new CreateFolderOperation from a given name. -// The name must be that of a previously created CreateFolderOperation, possibly from a different process. -func (c *foldersGRPCClient) CreateFolderOperation(name string) *CreateFolderOperation { - return &CreateFolderOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} - -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *CreateFolderOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*resourcemanagerpb.Folder, error) { - var resp resourcemanagerpb.Folder - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { +// GetFolder retrieves a folder identified by the supplied resource name. +// Valid folder resource names have the format folders/{folder_id} +// (for example, folders/1234). +// The caller must have resourcemanager.folders.get permission on the +// identified folder. +func (c *foldersRESTClient) GetFolder(ctx context.Context, req *resourcemanagerpb.GetFolderRequest, opts ...gax.CallOption) (*resourcemanagerpb.Folder, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - return &resp, nil -} + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *CreateFolderOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*resourcemanagerpb.Folder, error) { - var resp resourcemanagerpb.Folder - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { - return nil, err - } - if !op.Done() { - return nil, nil - } - return &resp, nil -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *CreateFolderOperation) Metadata() (*resourcemanagerpb.CreateFolderMetadata, error) { - var meta resourcemanagerpb.CreateFolderMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { - return nil, err - } - return &meta, nil -} + baseUrl.RawQuery = params.Encode() -// Done reports whether the long-running operation has completed. -func (op *CreateFolderOperation) Done() bool { - return op.lro.Done() -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) -// 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 *CreateFolderOperation) Name() string { - return op.lro.Name() -} + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetFolder[0:len((*c.CallOptions).GetFolder):len((*c.CallOptions).GetFolder)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &resourcemanagerpb.Folder{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers -// DeleteFolderOperation manages a long-running operation from DeleteFolder. -type DeleteFolderOperation struct { - lro *longrunning.Operation -} + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() -// DeleteFolderOperation returns a new DeleteFolderOperation from a given name. -// The name must be that of a previously created DeleteFolderOperation, possibly from a different process. -func (c *foldersGRPCClient) DeleteFolderOperation(name string) *DeleteFolderOperation { - return &DeleteFolderOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *DeleteFolderOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*resourcemanagerpb.Folder, error) { - var resp resourcemanagerpb.Folder - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { - return nil, err - } - return &resp, nil -} + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *DeleteFolderOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*resourcemanagerpb.Folder, error) { - var resp resourcemanagerpb.Folder - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { - return nil, err - } - if !op.Done() { - return nil, nil - } - return &resp, nil -} + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *DeleteFolderOperation) Metadata() (*resourcemanagerpb.DeleteFolderMetadata, error) { - var meta resourcemanagerpb.DeleteFolderMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { - return nil, err + return nil + }, opts...) + if e != nil { + return nil, e } - return &meta, nil + return resp, nil } -// Done reports whether the long-running operation has completed. -func (op *DeleteFolderOperation) Done() bool { - return op.lro.Done() -} +// ListFolders lists the folders that are direct descendants of supplied parent resource. +// list() provides a strongly consistent view of the folders underneath +// the specified parent resource. +// list() returns folders sorted based upon the (ascending) lexical ordering +// of their display_name. +// The caller must have resourcemanager.folders.list permission on the +// identified parent. +func (c *foldersRESTClient) ListFolders(ctx context.Context, req *resourcemanagerpb.ListFoldersRequest, opts ...gax.CallOption) *FolderIterator { + it := &FolderIterator{} + req = proto.Clone(req).(*resourcemanagerpb.ListFoldersRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*resourcemanagerpb.Folder, string, error) { + resp := &resourcemanagerpb.ListFoldersResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/folders") -// 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 *DeleteFolderOperation) Name() string { - return op.lro.Name() -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + params.Add("parent", fmt.Sprintf("%v", req.GetParent())) + if req.GetShowDeleted() { + params.Add("showDeleted", fmt.Sprintf("%v", req.GetShowDeleted())) + } -// MoveFolderOperation manages a long-running operation from MoveFolder. -type MoveFolderOperation struct { - lro *longrunning.Operation + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetFolders(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// SearchFolders search for folders that match specific filter criteria. +// search() provides an eventually consistent view of the folders a user has +// access to which meet the specified filter criteria. +// +// This will only return folders on which the caller has the +// permission resourcemanager.folders.get. +func (c *foldersRESTClient) SearchFolders(ctx context.Context, req *resourcemanagerpb.SearchFoldersRequest, opts ...gax.CallOption) *FolderIterator { + it := &FolderIterator{} + req = proto.Clone(req).(*resourcemanagerpb.SearchFoldersRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*resourcemanagerpb.Folder, string, error) { + resp := &resourcemanagerpb.SearchFoldersResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/folders:search") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + if req.GetQuery() != "" { + params.Add("query", fmt.Sprintf("%v", req.GetQuery())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetFolders(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CreateFolder creates a folder in the resource hierarchy. +// Returns an Operation which can be used to track the progress of the +// folder creation workflow. +// Upon success, the Operation.response field will be populated with the +// created Folder. +// +// In order to succeed, the addition of this new folder must not violate +// the folder naming, height, or fanout constraints. +// +// The folder’s display_name must be distinct from all other folders that +// share its parent. +// +// The addition of the folder must not cause the active folder hierarchy +// to exceed a height of 10. Note, the full active + deleted folder hierarchy +// is allowed to reach a height of 20; this provides additional headroom when +// moving folders that contain deleted folders. +// +// The addition of the folder must not cause the total number of folders +// under its parent to exceed 300. +// +// If the operation fails due to a folder constraint violation, some errors +// may be returned by the CreateFolder request, with status code +// FAILED_PRECONDITION and an error description. Other folder constraint +// violations will be communicated in the Operation, with the specific +// PreconditionFailure returned in the details list in the Operation.error +// field. +// +// The caller must have resourcemanager.folders.create permission on the +// identified parent. +func (c *foldersRESTClient) CreateFolder(ctx context.Context, req *resourcemanagerpb.CreateFolderRequest, opts ...gax.CallOption) (*CreateFolderOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetFolder() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/folders") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v3/%s", resp.GetName()) + return &CreateFolderOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateFolder updates a folder, changing its display_name. +// Changes to the folder display_name will be rejected if they violate +// either the display_name formatting rules or the naming constraints +// described in the CreateFolder documentation. +// +// The folder’s display_name must start and end with a letter or digit, +// may contain letters, digits, spaces, hyphens and underscores and can be +// between 3 and 30 characters. This is captured by the regular expression: +// [\p{L}\p{N}][\p{L}\p{N}_- ]{1,28}[\p{L}\p{N}]. +// The caller must have resourcemanager.folders.update permission on the +// identified folder. +// +// If the update fails due to the unique name constraint then a +// PreconditionFailure explaining this violation will be returned +// in the Status.details field. +func (c *foldersRESTClient) UpdateFolder(ctx context.Context, req *resourcemanagerpb.UpdateFolderRequest, opts ...gax.CallOption) (*UpdateFolderOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetFolder() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetFolder().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "folder.name", url.QueryEscape(req.GetFolder().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v3/%s", resp.GetName()) + return &UpdateFolderOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// MoveFolder moves a folder under a new resource parent. +// Returns an Operation which can be used to track the progress of the +// folder move workflow. +// Upon success, the Operation.response field will be populated with the +// moved folder. +// Upon failure, a FolderOperationError categorizing the failure cause will +// be returned - if the failure occurs synchronously then the +// FolderOperationError will be returned in the Status.details field. +// If it occurs asynchronously, then the FolderOperation will be returned +// in the Operation.error field. +// In addition, the Operation.metadata field will be populated with a +// FolderOperation message as an aid to stateless clients. +// Folder moves will be rejected if they violate either the naming, height, +// or fanout constraints described in the +// CreateFolder documentation. +// The caller must have resourcemanager.folders.move permission on the +// folder’s current and proposed new parent. +func (c *foldersRESTClient) MoveFolder(ctx context.Context, req *resourcemanagerpb.MoveFolderRequest, opts ...gax.CallOption) (*MoveFolderOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v:move", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v3/%s", resp.GetName()) + return &MoveFolderOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteFolder requests deletion of a folder. The folder is moved into the +// DELETE_REQUESTED state +// immediately, and is deleted approximately 30 days later. This method may +// only be called on an empty folder, where a folder is empty if it doesn’t +// contain any folders or projects in the [ACTIVE][google.cloud.resourcemanager.v3.Folder.State.ACTIVE (at http://google.cloud.resourcemanager.v3.Folder.State.ACTIVE)] state. +// If called on a folder in DELETE_REQUESTED +// state the operation will result in a no-op success. +// The caller must have resourcemanager.folders.delete permission on the +// identified folder. +func (c *foldersRESTClient) DeleteFolder(ctx context.Context, req *resourcemanagerpb.DeleteFolderRequest, opts ...gax.CallOption) (*DeleteFolderOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v3/%s", resp.GetName()) + return &DeleteFolderOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UndeleteFolder cancels the deletion request for a folder. This method may be called on a +// folder in any state. If the folder is in the [ACTIVE][google.cloud.resourcemanager.v3.Folder.State.ACTIVE (at http://google.cloud.resourcemanager.v3.Folder.State.ACTIVE)] +// state the result will be a no-op success. In order to succeed, the folder’s +// parent must be in the [ACTIVE][google.cloud.resourcemanager.v3.Folder.State.ACTIVE (at http://google.cloud.resourcemanager.v3.Folder.State.ACTIVE)] state. In addition, +// reintroducing the folder into the tree must not violate folder naming, +// height, and fanout constraints described in the +// CreateFolder documentation. +// The caller must have resourcemanager.folders.undelete permission on the +// identified folder. +func (c *foldersRESTClient) UndeleteFolder(ctx context.Context, req *resourcemanagerpb.UndeleteFolderRequest, opts ...gax.CallOption) (*UndeleteFolderOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v:undelete", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v3/%s", resp.GetName()) + return &UndeleteFolderOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetIamPolicy gets the access control policy for a folder. The returned policy may be +// empty if no such policy or resource exists. The resource field should +// be the folder’s resource name, for example: “folders/1234”. +// The caller must have resourcemanager.folders.getIamPolicy permission +// on the identified folder. +func (c *foldersRESTClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v:getIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SetIamPolicy sets the access control policy on a folder, replacing any existing policy. +// The resource field should be the folder’s resource name, for example: +// “folders/1234”. +// The caller must have resourcemanager.folders.setIamPolicy permission +// on the identified folder. +func (c *foldersRESTClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v:setIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// TestIamPermissions returns permissions that a caller has on the specified folder. +// The resource field should be the folder’s resource name, +// for example: “folders/1234”. +// +// There are no permissions required for making this API call. +func (c *foldersRESTClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v:testIamPermissions", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.TestIamPermissionsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateFolderOperation manages a long-running operation from CreateFolder. +type CreateFolderOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateFolderOperation returns a new CreateFolderOperation from a given name. +// The name must be that of a previously created CreateFolderOperation, possibly from a different process. +func (c *foldersGRPCClient) CreateFolderOperation(name string) *CreateFolderOperation { + return &CreateFolderOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateFolderOperation returns a new CreateFolderOperation from a given name. +// The name must be that of a previously created CreateFolderOperation, possibly from a different process. +func (c *foldersRESTClient) CreateFolderOperation(name string) *CreateFolderOperation { + override := fmt.Sprintf("/v3/%s", name) + return &CreateFolderOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CreateFolderOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*resourcemanagerpb.Folder, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp resourcemanagerpb.Folder + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *CreateFolderOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*resourcemanagerpb.Folder, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp resourcemanagerpb.Folder + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *CreateFolderOperation) Metadata() (*resourcemanagerpb.CreateFolderMetadata, error) { + var meta resourcemanagerpb.CreateFolderMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *CreateFolderOperation) Done() bool { + return op.lro.Done() +} + +// 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 *CreateFolderOperation) Name() string { + return op.lro.Name() +} + +// DeleteFolderOperation manages a long-running operation from DeleteFolder. +type DeleteFolderOperation struct { + lro *longrunning.Operation + pollPath string +} + +// DeleteFolderOperation returns a new DeleteFolderOperation from a given name. +// The name must be that of a previously created DeleteFolderOperation, possibly from a different process. +func (c *foldersGRPCClient) DeleteFolderOperation(name string) *DeleteFolderOperation { + return &DeleteFolderOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// DeleteFolderOperation returns a new DeleteFolderOperation from a given name. +// The name must be that of a previously created DeleteFolderOperation, possibly from a different process. +func (c *foldersRESTClient) DeleteFolderOperation(name string) *DeleteFolderOperation { + override := fmt.Sprintf("/v3/%s", name) + return &DeleteFolderOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *DeleteFolderOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*resourcemanagerpb.Folder, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp resourcemanagerpb.Folder + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *DeleteFolderOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*resourcemanagerpb.Folder, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp resourcemanagerpb.Folder + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *DeleteFolderOperation) Metadata() (*resourcemanagerpb.DeleteFolderMetadata, error) { + var meta resourcemanagerpb.DeleteFolderMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *DeleteFolderOperation) Done() bool { + return op.lro.Done() +} + +// 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 *DeleteFolderOperation) Name() string { + return op.lro.Name() +} + +// MoveFolderOperation manages a long-running operation from MoveFolder. +type MoveFolderOperation struct { + lro *longrunning.Operation + pollPath string } // MoveFolderOperation returns a new MoveFolderOperation from a given name. @@ -902,10 +1938,21 @@ func (c *foldersGRPCClient) MoveFolderOperation(name string) *MoveFolderOperatio } } +// MoveFolderOperation returns a new MoveFolderOperation from a given name. +// The name must be that of a previously created MoveFolderOperation, possibly from a different process. +func (c *foldersRESTClient) MoveFolderOperation(name string) *MoveFolderOperation { + override := fmt.Sprintf("/v3/%s", name) + return &MoveFolderOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *MoveFolderOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*resourcemanagerpb.Folder, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp resourcemanagerpb.Folder if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -923,6 +1970,7 @@ func (op *MoveFolderOperation) Wait(ctx context.Context, opts ...gax.CallOption) // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *MoveFolderOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*resourcemanagerpb.Folder, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp resourcemanagerpb.Folder if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -960,7 +2008,8 @@ func (op *MoveFolderOperation) Name() string { // UndeleteFolderOperation manages a long-running operation from UndeleteFolder. type UndeleteFolderOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UndeleteFolderOperation returns a new UndeleteFolderOperation from a given name. @@ -971,10 +2020,21 @@ func (c *foldersGRPCClient) UndeleteFolderOperation(name string) *UndeleteFolder } } +// UndeleteFolderOperation returns a new UndeleteFolderOperation from a given name. +// The name must be that of a previously created UndeleteFolderOperation, possibly from a different process. +func (c *foldersRESTClient) UndeleteFolderOperation(name string) *UndeleteFolderOperation { + override := fmt.Sprintf("/v3/%s", name) + return &UndeleteFolderOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UndeleteFolderOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*resourcemanagerpb.Folder, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp resourcemanagerpb.Folder if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -992,6 +2052,7 @@ func (op *UndeleteFolderOperation) Wait(ctx context.Context, opts ...gax.CallOpt // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UndeleteFolderOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*resourcemanagerpb.Folder, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp resourcemanagerpb.Folder if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1029,7 +2090,8 @@ func (op *UndeleteFolderOperation) Name() string { // UpdateFolderOperation manages a long-running operation from UpdateFolder. type UpdateFolderOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateFolderOperation returns a new UpdateFolderOperation from a given name. @@ -1040,10 +2102,21 @@ func (c *foldersGRPCClient) UpdateFolderOperation(name string) *UpdateFolderOper } } +// UpdateFolderOperation returns a new UpdateFolderOperation from a given name. +// The name must be that of a previously created UpdateFolderOperation, possibly from a different process. +func (c *foldersRESTClient) UpdateFolderOperation(name string) *UpdateFolderOperation { + override := fmt.Sprintf("/v3/%s", name) + return &UpdateFolderOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateFolderOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*resourcemanagerpb.Folder, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp resourcemanagerpb.Folder if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1061,6 +2134,7 @@ func (op *UpdateFolderOperation) Wait(ctx context.Context, opts ...gax.CallOptio // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateFolderOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*resourcemanagerpb.Folder, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp resourcemanagerpb.Folder if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/resourcemanager/apiv3/folders_client_example_test.go b/resourcemanager/apiv3/folders_client_example_test.go index 1d9a29208f3f..838c39a1c9b1 100644 --- a/resourcemanager/apiv3/folders_client_example_test.go +++ b/resourcemanager/apiv3/folders_client_example_test.go @@ -42,6 +42,23 @@ func ExampleNewFoldersClient() { _ = c } +func ExampleNewFoldersRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := resourcemanager.NewFoldersRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleFoldersClient_GetFolder() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/resourcemanager/apiv3/gapic_metadata.json b/resourcemanager/apiv3/gapic_metadata.json index 6dc1b4fd0bc4..71b04cabb463 100644 --- a/resourcemanager/apiv3/gapic_metadata.json +++ b/resourcemanager/apiv3/gapic_metadata.json @@ -66,6 +66,66 @@ ] } } + }, + "rest": { + "libraryClient": "FoldersClient", + "rpcs": { + "CreateFolder": { + "methods": [ + "CreateFolder" + ] + }, + "DeleteFolder": { + "methods": [ + "DeleteFolder" + ] + }, + "GetFolder": { + "methods": [ + "GetFolder" + ] + }, + "GetIamPolicy": { + "methods": [ + "GetIamPolicy" + ] + }, + "ListFolders": { + "methods": [ + "ListFolders" + ] + }, + "MoveFolder": { + "methods": [ + "MoveFolder" + ] + }, + "SearchFolders": { + "methods": [ + "SearchFolders" + ] + }, + "SetIamPolicy": { + "methods": [ + "SetIamPolicy" + ] + }, + "TestIamPermissions": { + "methods": [ + "TestIamPermissions" + ] + }, + "UndeleteFolder": { + "methods": [ + "UndeleteFolder" + ] + }, + "UpdateFolder": { + "methods": [ + "UpdateFolder" + ] + } + } } } }, @@ -100,6 +160,36 @@ ] } } + }, + "rest": { + "libraryClient": "OrganizationsClient", + "rpcs": { + "GetIamPolicy": { + "methods": [ + "GetIamPolicy" + ] + }, + "GetOrganization": { + "methods": [ + "GetOrganization" + ] + }, + "SearchOrganizations": { + "methods": [ + "SearchOrganizations" + ] + }, + "SetIamPolicy": { + "methods": [ + "SetIamPolicy" + ] + }, + "TestIamPermissions": { + "methods": [ + "TestIamPermissions" + ] + } + } } } }, @@ -164,6 +254,66 @@ ] } } + }, + "rest": { + "libraryClient": "ProjectsClient", + "rpcs": { + "CreateProject": { + "methods": [ + "CreateProject" + ] + }, + "DeleteProject": { + "methods": [ + "DeleteProject" + ] + }, + "GetIamPolicy": { + "methods": [ + "GetIamPolicy" + ] + }, + "GetProject": { + "methods": [ + "GetProject" + ] + }, + "ListProjects": { + "methods": [ + "ListProjects" + ] + }, + "MoveProject": { + "methods": [ + "MoveProject" + ] + }, + "SearchProjects": { + "methods": [ + "SearchProjects" + ] + }, + "SetIamPolicy": { + "methods": [ + "SetIamPolicy" + ] + }, + "TestIamPermissions": { + "methods": [ + "TestIamPermissions" + ] + }, + "UndeleteProject": { + "methods": [ + "UndeleteProject" + ] + }, + "UpdateProject": { + "methods": [ + "UpdateProject" + ] + } + } } } }, @@ -188,6 +338,26 @@ ] } } + }, + "rest": { + "libraryClient": "TagBindingsClient", + "rpcs": { + "CreateTagBinding": { + "methods": [ + "CreateTagBinding" + ] + }, + "DeleteTagBinding": { + "methods": [ + "DeleteTagBinding" + ] + }, + "ListTagBindings": { + "methods": [ + "ListTagBindings" + ] + } + } } } }, @@ -237,6 +407,51 @@ ] } } + }, + "rest": { + "libraryClient": "TagKeysClient", + "rpcs": { + "CreateTagKey": { + "methods": [ + "CreateTagKey" + ] + }, + "DeleteTagKey": { + "methods": [ + "DeleteTagKey" + ] + }, + "GetIamPolicy": { + "methods": [ + "GetIamPolicy" + ] + }, + "GetTagKey": { + "methods": [ + "GetTagKey" + ] + }, + "ListTagKeys": { + "methods": [ + "ListTagKeys" + ] + }, + "SetIamPolicy": { + "methods": [ + "SetIamPolicy" + ] + }, + "TestIamPermissions": { + "methods": [ + "TestIamPermissions" + ] + }, + "UpdateTagKey": { + "methods": [ + "UpdateTagKey" + ] + } + } } } }, @@ -286,6 +501,51 @@ ] } } + }, + "rest": { + "libraryClient": "TagValuesClient", + "rpcs": { + "CreateTagValue": { + "methods": [ + "CreateTagValue" + ] + }, + "DeleteTagValue": { + "methods": [ + "DeleteTagValue" + ] + }, + "GetIamPolicy": { + "methods": [ + "GetIamPolicy" + ] + }, + "GetTagValue": { + "methods": [ + "GetTagValue" + ] + }, + "ListTagValues": { + "methods": [ + "ListTagValues" + ] + }, + "SetIamPolicy": { + "methods": [ + "SetIamPolicy" + ] + }, + "TestIamPermissions": { + "methods": [ + "TestIamPermissions" + ] + }, + "UpdateTagValue": { + "methods": [ + "UpdateTagValue" + ] + } + } } } } diff --git a/resourcemanager/apiv3/organizations_client.go b/resourcemanager/apiv3/organizations_client.go index 386d1991c5c4..81ed10d7f4c1 100644 --- a/resourcemanager/apiv3/organizations_client.go +++ b/resourcemanager/apiv3/organizations_client.go @@ -17,22 +17,28 @@ package resourcemanager import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" resourcemanagerpb "cloud.google.com/go/resourcemanager/apiv3/resourcemanagerpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" iampb "google.golang.org/genproto/googleapis/iam/v1" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -89,6 +95,34 @@ func defaultOrganizationsCallOptions() *OrganizationsCallOptions { } } +func defaultOrganizationsRESTCallOptions() *OrganizationsCallOptions { + return &OrganizationsCallOptions{ + GetOrganization: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + SearchOrganizations: []gax.CallOption{}, + GetIamPolicy: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + SetIamPolicy: []gax.CallOption{}, + TestIamPermissions: []gax.CallOption{}, + } +} + // internalOrganizationsClient is an interface that defines the methods available from Cloud Resource Manager API. type internalOrganizationsClient interface { Close() error @@ -262,6 +296,74 @@ func (c *organizationsGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type organizationsRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing OrganizationsClient + CallOptions **OrganizationsCallOptions +} + +// NewOrganizationsRESTClient creates a new organizations rest client. +// +// Allows users to manage their organization resources. +func NewOrganizationsRESTClient(ctx context.Context, opts ...option.ClientOption) (*OrganizationsClient, error) { + clientOpts := append(defaultOrganizationsRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultOrganizationsRESTCallOptions() + c := &organizationsRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &OrganizationsClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultOrganizationsRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://cloudresourcemanager.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://cloudresourcemanager.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://cloudresourcemanager.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *organizationsRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *organizationsRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *organizationsRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *organizationsGRPCClient) GetOrganization(ctx context.Context, req *resourcemanagerpb.GetOrganizationRequest, opts ...gax.CallOption) (*resourcemanagerpb.Organization, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) @@ -388,6 +490,367 @@ func (c *organizationsGRPCClient) TestIamPermissions(ctx context.Context, req *i return resp, nil } +// GetOrganization fetches an organization resource identified by the specified resource name. +func (c *organizationsRESTClient) GetOrganization(ctx context.Context, req *resourcemanagerpb.GetOrganizationRequest, opts ...gax.CallOption) (*resourcemanagerpb.Organization, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOrganization[0:len((*c.CallOptions).GetOrganization):len((*c.CallOptions).GetOrganization)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &resourcemanagerpb.Organization{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SearchOrganizations searches organization resources that are visible to the user and satisfy +// the specified filter. This method returns organizations in an unspecified +// order. New organizations do not necessarily appear at the end of the +// results, and may take a small amount of time to appear. +// +// Search will only return organizations on which the user has the permission +// resourcemanager.organizations.get +func (c *organizationsRESTClient) SearchOrganizations(ctx context.Context, req *resourcemanagerpb.SearchOrganizationsRequest, opts ...gax.CallOption) *OrganizationIterator { + it := &OrganizationIterator{} + req = proto.Clone(req).(*resourcemanagerpb.SearchOrganizationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*resourcemanagerpb.Organization, string, error) { + resp := &resourcemanagerpb.SearchOrganizationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/organizations:search") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + if req.GetQuery() != "" { + params.Add("query", fmt.Sprintf("%v", req.GetQuery())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOrganizations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetIamPolicy gets the access control policy for an organization resource. The policy may +// be empty if no such policy or resource exists. The resource field should +// be the organization’s resource name, for example: “organizations/123”. +// +// Authorization requires the IAM permission +// resourcemanager.organizations.getIamPolicy on the specified organization. +func (c *organizationsRESTClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v:getIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SetIamPolicy sets the access control policy on an organization resource. Replaces any +// existing policy. The resource field should be the organization’s resource +// name, for example: “organizations/123”. +// +// Authorization requires the IAM permission +// resourcemanager.organizations.setIamPolicy on the specified organization. +func (c *organizationsRESTClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v:setIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// TestIamPermissions returns the permissions that a caller has on the specified organization. +// The resource field should be the organization’s resource name, +// for example: “organizations/123”. +// +// There are no permissions required for making this API call. +func (c *organizationsRESTClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v:testIamPermissions", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.TestIamPermissionsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + // OrganizationIterator manages a stream of *resourcemanagerpb.Organization. type OrganizationIterator struct { items []*resourcemanagerpb.Organization diff --git a/resourcemanager/apiv3/organizations_client_example_test.go b/resourcemanager/apiv3/organizations_client_example_test.go index e2f18d7ef863..23d82fe96879 100644 --- a/resourcemanager/apiv3/organizations_client_example_test.go +++ b/resourcemanager/apiv3/organizations_client_example_test.go @@ -42,6 +42,23 @@ func ExampleNewOrganizationsClient() { _ = c } +func ExampleNewOrganizationsRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := resourcemanager.NewOrganizationsRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleOrganizationsClient_GetOrganization() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/resourcemanager/apiv3/projects_client.go b/resourcemanager/apiv3/projects_client.go index 87a2a09efca5..9c00ac158ee4 100644 --- a/resourcemanager/apiv3/projects_client.go +++ b/resourcemanager/apiv3/projects_client.go @@ -17,9 +17,12 @@ package resourcemanager import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,15 +30,18 @@ import ( lroauto "cloud.google.com/go/longrunning/autogen" resourcemanagerpb "cloud.google.com/go/resourcemanager/apiv3/resourcemanagerpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" iampb "google.golang.org/genproto/googleapis/iam/v1" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -114,6 +120,49 @@ func defaultProjectsCallOptions() *ProjectsCallOptions { } } +func defaultProjectsRESTCallOptions() *ProjectsCallOptions { + return &ProjectsCallOptions{ + GetProject: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListProjects: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + SearchProjects: []gax.CallOption{}, + CreateProject: []gax.CallOption{}, + UpdateProject: []gax.CallOption{}, + MoveProject: []gax.CallOption{}, + DeleteProject: []gax.CallOption{}, + UndeleteProject: []gax.CallOption{}, + GetIamPolicy: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + SetIamPolicy: []gax.CallOption{}, + TestIamPermissions: []gax.CallOption{}, + } +} + // internalProjectsClient is an interface that defines the methods available from Cloud Resource Manager API. type internalProjectsClient interface { Close() error @@ -479,6 +528,89 @@ func (c *projectsGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type projectsRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing ProjectsClient + CallOptions **ProjectsCallOptions +} + +// NewProjectsRESTClient creates a new projects rest client. +// +// Manages Google Cloud Projects. +func NewProjectsRESTClient(ctx context.Context, opts ...option.ClientOption) (*ProjectsClient, error) { + clientOpts := append(defaultProjectsRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultProjectsRESTCallOptions() + c := &projectsRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &ProjectsClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultProjectsRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://cloudresourcemanager.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://cloudresourcemanager.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://cloudresourcemanager.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *projectsRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *projectsRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *projectsRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *projectsGRPCClient) GetProject(ctx context.Context, req *resourcemanagerpb.GetProjectRequest, opts ...gax.CallOption) (*resourcemanagerpb.Project, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) @@ -766,161 +898,1093 @@ func (c *projectsGRPCClient) TestIamPermissions(ctx context.Context, req *iampb. return resp, nil } -// CreateProjectOperation manages a long-running operation from CreateProject. -type CreateProjectOperation struct { - lro *longrunning.Operation -} - -// CreateProjectOperation returns a new CreateProjectOperation from a given name. -// The name must be that of a previously created CreateProjectOperation, possibly from a different process. -func (c *projectsGRPCClient) CreateProjectOperation(name string) *CreateProjectOperation { - return &CreateProjectOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} - -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// GetProject retrieves the project identified by the specified name (for example, +// projects/415104041262). // -// See documentation of Poll for error-handling information. -func (op *CreateProjectOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*resourcemanagerpb.Project, error) { - var resp resourcemanagerpb.Project - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { +// The caller must have resourcemanager.projects.get permission +// for this project. +func (c *projectsRESTClient) GetProject(ctx context.Context, req *resourcemanagerpb.GetProjectRequest, opts ...gax.CallOption) (*resourcemanagerpb.Project, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - return &resp, nil -} + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *CreateProjectOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*resourcemanagerpb.Project, error) { - var resp resourcemanagerpb.Project - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { - return nil, err - } - if !op.Done() { - return nil, nil - } - return &resp, nil -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *CreateProjectOperation) Metadata() (*resourcemanagerpb.CreateProjectMetadata, error) { - var meta resourcemanagerpb.CreateProjectMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { - return nil, err - } - return &meta, nil -} + baseUrl.RawQuery = params.Encode() -// Done reports whether the long-running operation has completed. -func (op *CreateProjectOperation) Done() bool { - return op.lro.Done() -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) -// 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 *CreateProjectOperation) Name() string { - return op.lro.Name() -} + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetProject[0:len((*c.CallOptions).GetProject):len((*c.CallOptions).GetProject)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &resourcemanagerpb.Project{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers -// DeleteProjectOperation manages a long-running operation from DeleteProject. -type DeleteProjectOperation struct { - lro *longrunning.Operation -} + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() -// DeleteProjectOperation returns a new DeleteProjectOperation from a given name. -// The name must be that of a previously created DeleteProjectOperation, possibly from a different process. -func (c *projectsGRPCClient) DeleteProjectOperation(name string) *DeleteProjectOperation { - return &DeleteProjectOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *DeleteProjectOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*resourcemanagerpb.Project, error) { - var resp resourcemanagerpb.Project - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { - return nil, err - } - return &resp, nil -} + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *DeleteProjectOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*resourcemanagerpb.Project, error) { - var resp resourcemanagerpb.Project - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { - return nil, err - } - if !op.Done() { - return nil, nil - } - return &resp, nil -} + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *DeleteProjectOperation) Metadata() (*resourcemanagerpb.DeleteProjectMetadata, error) { - var meta resourcemanagerpb.DeleteProjectMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { - return nil, err + return nil + }, opts...) + if e != nil { + return nil, e } - return &meta, nil -} - -// Done reports whether the long-running operation has completed. -func (op *DeleteProjectOperation) Done() bool { - return op.lro.Done() + return resp, nil } -// 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 *DeleteProjectOperation) Name() string { - return op.lro.Name() -} +// ListProjects lists projects that are direct children of the specified folder or +// organization resource. list() provides a strongly consistent view of the +// projects underneath the specified parent resource. list() returns +// projects sorted based upon the (ascending) lexical ordering of their +// display_name. The caller must have resourcemanager.projects.list +// permission on the identified parent. +func (c *projectsRESTClient) ListProjects(ctx context.Context, req *resourcemanagerpb.ListProjectsRequest, opts ...gax.CallOption) *ProjectIterator { + it := &ProjectIterator{} + req = proto.Clone(req).(*resourcemanagerpb.ListProjectsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*resourcemanagerpb.Project, string, error) { + resp := &resourcemanagerpb.ListProjectsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/projects") -// MoveProjectOperation manages a long-running operation from MoveProject. -type MoveProjectOperation struct { - lro *longrunning.Operation -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + params.Add("parent", fmt.Sprintf("%v", req.GetParent())) + if req.GetShowDeleted() { + params.Add("showDeleted", fmt.Sprintf("%v", req.GetShowDeleted())) + } -// MoveProjectOperation returns a new MoveProjectOperation from a given name. -// The name must be that of a previously created MoveProjectOperation, possibly from a different process. -func (c *projectsGRPCClient) MoveProjectOperation(name string) *MoveProjectOperation { + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetProjects(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// SearchProjects search for projects that the caller has both resourcemanager.projects.get +// permission on, and also satisfy the specified query. +// +// This method returns projects in an unspecified order. +// +// This method is eventually consistent with project mutations; this means +// that a newly created project may not appear in the results or recent +// updates to an existing project may not be reflected in the results. To +// retrieve the latest state of a project, use the +// GetProject method. +func (c *projectsRESTClient) SearchProjects(ctx context.Context, req *resourcemanagerpb.SearchProjectsRequest, opts ...gax.CallOption) *ProjectIterator { + it := &ProjectIterator{} + req = proto.Clone(req).(*resourcemanagerpb.SearchProjectsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*resourcemanagerpb.Project, string, error) { + resp := &resourcemanagerpb.SearchProjectsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/projects:search") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + if req.GetQuery() != "" { + params.Add("query", fmt.Sprintf("%v", req.GetQuery())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetProjects(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CreateProject request that a new project be created. The result is an Operation which +// can be used to track the creation process. This process usually takes a few +// seconds, but can sometimes take much longer. The tracking Operation is +// automatically deleted after a few hours, so there is no need to call +// DeleteOperation. +func (c *projectsRESTClient) CreateProject(ctx context.Context, req *resourcemanagerpb.CreateProjectRequest, opts ...gax.CallOption) (*CreateProjectOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetProject() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/projects") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v3/%s", resp.GetName()) + return &CreateProjectOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateProject updates the display_name and labels of the project identified by the +// specified name (for example, projects/415104041262). Deleting all +// labels requires an update mask for labels field. +// +// The caller must have resourcemanager.projects.update permission for this +// project. +func (c *projectsRESTClient) UpdateProject(ctx context.Context, req *resourcemanagerpb.UpdateProjectRequest, opts ...gax.CallOption) (*UpdateProjectOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetProject() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetProject().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "project.name", url.QueryEscape(req.GetProject().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v3/%s", resp.GetName()) + return &UpdateProjectOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// MoveProject move a project to another place in your resource hierarchy, under a new +// resource parent. +// +// Returns an operation which can be used to track the process of the project +// move workflow. +// Upon success, the Operation.response field will be populated with the +// moved project. +// +// The caller must have resourcemanager.projects.update permission on the +// project and have resourcemanager.projects.move permission on the +// project’s current and proposed new parent. +func (c *projectsRESTClient) MoveProject(ctx context.Context, req *resourcemanagerpb.MoveProjectRequest, opts ...gax.CallOption) (*MoveProjectOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v:move", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v3/%s", resp.GetName()) + return &MoveProjectOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteProject marks the project identified by the specified +// name (for example, projects/415104041262) for deletion. +// +// This method will only affect the project if it has a lifecycle state of +// [ACTIVE][google.cloud.resourcemanager.v3.Project.State.ACTIVE (at http://google.cloud.resourcemanager.v3.Project.State.ACTIVE)]. +// +// This method changes the Project’s lifecycle state from +// [ACTIVE][google.cloud.resourcemanager.v3.Project.State.ACTIVE (at http://google.cloud.resourcemanager.v3.Project.State.ACTIVE)] +// to DELETE_REQUESTED. +// The deletion starts at an unspecified time, +// at which point the Project is no longer accessible. +// +// Until the deletion completes, you can check the lifecycle state +// checked by retrieving the project with [GetProject] +// [google.cloud.resourcemanager.v3.Projects.GetProject], +// and the project remains visible to [ListProjects] +// [google.cloud.resourcemanager.v3.Projects.ListProjects]. +// However, you cannot update the project. +// +// After the deletion completes, the project is not retrievable by +// the [GetProject] +// [google.cloud.resourcemanager.v3.Projects.GetProject], +// [ListProjects] +// [google.cloud.resourcemanager.v3.Projects.ListProjects], and +// SearchProjects +// methods. +// +// This method behaves idempotently, such that deleting a DELETE_REQUESTED +// project will not cause an error, but also won’t do anything. +// +// The caller must have resourcemanager.projects.delete permissions for this +// project. +func (c *projectsRESTClient) DeleteProject(ctx context.Context, req *resourcemanagerpb.DeleteProjectRequest, opts ...gax.CallOption) (*DeleteProjectOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v3/%s", resp.GetName()) + return &DeleteProjectOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UndeleteProject restores the project identified by the specified +// name (for example, projects/415104041262). +// You can only use this method for a project that has a lifecycle state of +// [DELETE_REQUESTED] +// [Projects.State.DELETE_REQUESTED]. +// After deletion starts, the project cannot be restored. +// +// The caller must have resourcemanager.projects.undelete permission for +// this project. +func (c *projectsRESTClient) UndeleteProject(ctx context.Context, req *resourcemanagerpb.UndeleteProjectRequest, opts ...gax.CallOption) (*UndeleteProjectOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v:undelete", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v3/%s", resp.GetName()) + return &UndeleteProjectOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetIamPolicy returns the IAM access control policy for the specified project. +// Permission is denied if the policy or the resource do not exist. +func (c *projectsRESTClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v:getIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SetIamPolicy sets the IAM access control policy for the specified project. +// +// CAUTION: This method will replace the existing policy, and cannot be used +// to append additional IAM settings. +// +// Note: Removing service accounts from policies or changing their roles can +// render services completely inoperable. It is important to understand how +// the service account is being used before removing or updating its roles. +// +// The following constraints apply when using setIamPolicy(): +// +// Project does not support allUsers and allAuthenticatedUsers as +// members in a Binding of a Policy. +// +// The owner role can be granted to a user, serviceAccount, or a group +// that is part of an organization. For example, +// group@myownpersonaldomain.com (at mailto:group@myownpersonaldomain.com) could be added as an owner to a project in +// the myownpersonaldomain.com (at http://myownpersonaldomain.com) organization, but not the examplepetstore.com (at http://examplepetstore.com) +// organization. +// +// Service accounts can be made owners of a project directly +// without any restrictions. However, to be added as an owner, a user must be +// invited using the Cloud Platform console and must accept the invitation. +// +// A user cannot be granted the owner role using setIamPolicy(). The user +// must be granted the owner role using the Cloud Platform Console and must +// explicitly accept the invitation. +// +// Invitations to grant the owner role cannot be sent using +// setIamPolicy(); +// they must be sent only using the Cloud Platform Console. +// +// Membership changes that leave the project without any owners that have +// accepted the Terms of Service (ToS) will be rejected. +// +// If the project is not part of an organization, there must be at least +// one owner who has accepted the Terms of Service (ToS) agreement in the +// policy. Calling setIamPolicy() to remove the last ToS-accepted owner +// from the policy will fail. This restriction also applies to legacy +// projects that no longer have owners who have accepted the ToS. Edits to +// IAM policies will be rejected until the lack of a ToS-accepting owner is +// rectified. +// +// Calling this method requires enabling the App Engine Admin API. +func (c *projectsRESTClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v:setIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// TestIamPermissions returns permissions that a caller has on the specified project. +func (c *projectsRESTClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v:testIamPermissions", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.TestIamPermissionsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateProjectOperation manages a long-running operation from CreateProject. +type CreateProjectOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateProjectOperation returns a new CreateProjectOperation from a given name. +// The name must be that of a previously created CreateProjectOperation, possibly from a different process. +func (c *projectsGRPCClient) CreateProjectOperation(name string) *CreateProjectOperation { + return &CreateProjectOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateProjectOperation returns a new CreateProjectOperation from a given name. +// The name must be that of a previously created CreateProjectOperation, possibly from a different process. +func (c *projectsRESTClient) CreateProjectOperation(name string) *CreateProjectOperation { + override := fmt.Sprintf("/v3/%s", name) + return &CreateProjectOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CreateProjectOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*resourcemanagerpb.Project, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp resourcemanagerpb.Project + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *CreateProjectOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*resourcemanagerpb.Project, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp resourcemanagerpb.Project + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *CreateProjectOperation) Metadata() (*resourcemanagerpb.CreateProjectMetadata, error) { + var meta resourcemanagerpb.CreateProjectMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *CreateProjectOperation) Done() bool { + return op.lro.Done() +} + +// 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 *CreateProjectOperation) Name() string { + return op.lro.Name() +} + +// DeleteProjectOperation manages a long-running operation from DeleteProject. +type DeleteProjectOperation struct { + lro *longrunning.Operation + pollPath string +} + +// DeleteProjectOperation returns a new DeleteProjectOperation from a given name. +// The name must be that of a previously created DeleteProjectOperation, possibly from a different process. +func (c *projectsGRPCClient) DeleteProjectOperation(name string) *DeleteProjectOperation { + return &DeleteProjectOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// DeleteProjectOperation returns a new DeleteProjectOperation from a given name. +// The name must be that of a previously created DeleteProjectOperation, possibly from a different process. +func (c *projectsRESTClient) DeleteProjectOperation(name string) *DeleteProjectOperation { + override := fmt.Sprintf("/v3/%s", name) + return &DeleteProjectOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *DeleteProjectOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*resourcemanagerpb.Project, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp resourcemanagerpb.Project + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *DeleteProjectOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*resourcemanagerpb.Project, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp resourcemanagerpb.Project + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *DeleteProjectOperation) Metadata() (*resourcemanagerpb.DeleteProjectMetadata, error) { + var meta resourcemanagerpb.DeleteProjectMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *DeleteProjectOperation) Done() bool { + return op.lro.Done() +} + +// 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 *DeleteProjectOperation) Name() string { + return op.lro.Name() +} + +// MoveProjectOperation manages a long-running operation from MoveProject. +type MoveProjectOperation struct { + lro *longrunning.Operation + pollPath string +} + +// MoveProjectOperation returns a new MoveProjectOperation from a given name. +// The name must be that of a previously created MoveProjectOperation, possibly from a different process. +func (c *projectsGRPCClient) MoveProjectOperation(name string) *MoveProjectOperation { return &MoveProjectOperation{ lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } +// MoveProjectOperation returns a new MoveProjectOperation from a given name. +// The name must be that of a previously created MoveProjectOperation, possibly from a different process. +func (c *projectsRESTClient) MoveProjectOperation(name string) *MoveProjectOperation { + override := fmt.Sprintf("/v3/%s", name) + return &MoveProjectOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *MoveProjectOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*resourcemanagerpb.Project, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp resourcemanagerpb.Project if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -938,6 +2002,7 @@ func (op *MoveProjectOperation) Wait(ctx context.Context, opts ...gax.CallOption // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *MoveProjectOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*resourcemanagerpb.Project, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp resourcemanagerpb.Project if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -975,7 +2040,8 @@ func (op *MoveProjectOperation) Name() string { // UndeleteProjectOperation manages a long-running operation from UndeleteProject. type UndeleteProjectOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UndeleteProjectOperation returns a new UndeleteProjectOperation from a given name. @@ -986,10 +2052,21 @@ func (c *projectsGRPCClient) UndeleteProjectOperation(name string) *UndeleteProj } } +// UndeleteProjectOperation returns a new UndeleteProjectOperation from a given name. +// The name must be that of a previously created UndeleteProjectOperation, possibly from a different process. +func (c *projectsRESTClient) UndeleteProjectOperation(name string) *UndeleteProjectOperation { + override := fmt.Sprintf("/v3/%s", name) + return &UndeleteProjectOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UndeleteProjectOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*resourcemanagerpb.Project, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp resourcemanagerpb.Project if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1007,6 +2084,7 @@ func (op *UndeleteProjectOperation) Wait(ctx context.Context, opts ...gax.CallOp // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UndeleteProjectOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*resourcemanagerpb.Project, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp resourcemanagerpb.Project if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1044,7 +2122,8 @@ func (op *UndeleteProjectOperation) Name() string { // UpdateProjectOperation manages a long-running operation from UpdateProject. type UpdateProjectOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateProjectOperation returns a new UpdateProjectOperation from a given name. @@ -1055,10 +2134,21 @@ func (c *projectsGRPCClient) UpdateProjectOperation(name string) *UpdateProjectO } } +// UpdateProjectOperation returns a new UpdateProjectOperation from a given name. +// The name must be that of a previously created UpdateProjectOperation, possibly from a different process. +func (c *projectsRESTClient) UpdateProjectOperation(name string) *UpdateProjectOperation { + override := fmt.Sprintf("/v3/%s", name) + return &UpdateProjectOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateProjectOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*resourcemanagerpb.Project, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp resourcemanagerpb.Project if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1076,6 +2166,7 @@ func (op *UpdateProjectOperation) Wait(ctx context.Context, opts ...gax.CallOpti // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateProjectOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*resourcemanagerpb.Project, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp resourcemanagerpb.Project if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/resourcemanager/apiv3/projects_client_example_test.go b/resourcemanager/apiv3/projects_client_example_test.go index aade857a9108..515de35696ac 100644 --- a/resourcemanager/apiv3/projects_client_example_test.go +++ b/resourcemanager/apiv3/projects_client_example_test.go @@ -42,6 +42,23 @@ func ExampleNewProjectsClient() { _ = c } +func ExampleNewProjectsRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := resourcemanager.NewProjectsRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleProjectsClient_GetProject() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/resourcemanager/apiv3/resourcemanagerpb/folders.pb.go b/resourcemanager/apiv3/resourcemanagerpb/folders.pb.go index d3ad8c869af1..2177f1795537 100644 --- a/resourcemanager/apiv3/resourcemanagerpb/folders.pb.go +++ b/resourcemanager/apiv3/resourcemanagerpb/folders.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/resourcemanager/v3/folders.proto package resourcemanagerpb diff --git a/resourcemanager/apiv3/resourcemanagerpb/organizations.pb.go b/resourcemanager/apiv3/resourcemanagerpb/organizations.pb.go index ddbbf1fd16e1..6d96c37ad498 100644 --- a/resourcemanager/apiv3/resourcemanagerpb/organizations.pb.go +++ b/resourcemanager/apiv3/resourcemanagerpb/organizations.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/resourcemanager/v3/organizations.proto package resourcemanagerpb @@ -119,7 +119,6 @@ type Organization struct { // descendants will be deleted. // // Types that are assignable to Owner: - // // *Organization_DirectoryCustomerId Owner isOrganization_Owner `protobuf_oneof:"owner"` // Output only. The organization's current lifecycle state. diff --git a/resourcemanager/apiv3/resourcemanagerpb/projects.pb.go b/resourcemanager/apiv3/resourcemanagerpb/projects.pb.go index caeed7e5fd96..9c652c483d7d 100644 --- a/resourcemanager/apiv3/resourcemanagerpb/projects.pb.go +++ b/resourcemanager/apiv3/resourcemanagerpb/projects.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/resourcemanager/v3/projects.proto package resourcemanagerpb @@ -1856,6 +1856,8 @@ type ProjectsClient interface { // The caller must have `resourcemanager.projects.update` permission on the // project and have `resourcemanager.projects.move` permission on the // project's current and proposed new parent. + // + // MoveProject(ctx context.Context, in *MoveProjectRequest, opts ...grpc.CallOption) (*longrunning.Operation, error) // Marks the project identified by the specified // `name` (for example, `projects/415104041262`) for deletion. @@ -2109,6 +2111,8 @@ type ProjectsServer interface { // The caller must have `resourcemanager.projects.update` permission on the // project and have `resourcemanager.projects.move` permission on the // project's current and proposed new parent. + // + // MoveProject(context.Context, *MoveProjectRequest) (*longrunning.Operation, error) // Marks the project identified by the specified // `name` (for example, `projects/415104041262`) for deletion. diff --git a/resourcemanager/apiv3/resourcemanagerpb/tag_bindings.pb.go b/resourcemanager/apiv3/resourcemanagerpb/tag_bindings.pb.go index 6af05a6dcf38..fde81fa45c8f 100644 --- a/resourcemanager/apiv3/resourcemanagerpb/tag_bindings.pb.go +++ b/resourcemanager/apiv3/resourcemanagerpb/tag_bindings.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/resourcemanager/v3/tag_bindings.proto package resourcemanagerpb diff --git a/resourcemanager/apiv3/resourcemanagerpb/tag_keys.pb.go b/resourcemanager/apiv3/resourcemanagerpb/tag_keys.pb.go index 0e36418a9bc1..c124909b0c2a 100644 --- a/resourcemanager/apiv3/resourcemanagerpb/tag_keys.pb.go +++ b/resourcemanager/apiv3/resourcemanagerpb/tag_keys.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/resourcemanager/v3/tag_keys.proto package resourcemanagerpb diff --git a/resourcemanager/apiv3/resourcemanagerpb/tag_values.pb.go b/resourcemanager/apiv3/resourcemanagerpb/tag_values.pb.go index 3a6a6d05eb32..41a3255c4ff3 100644 --- a/resourcemanager/apiv3/resourcemanagerpb/tag_values.pb.go +++ b/resourcemanager/apiv3/resourcemanagerpb/tag_values.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/resourcemanager/v3/tag_values.proto package resourcemanagerpb diff --git a/resourcemanager/apiv3/tag_bindings_client.go b/resourcemanager/apiv3/tag_bindings_client.go index fa2496ac1365..987712f3b44f 100644 --- a/resourcemanager/apiv3/tag_bindings_client.go +++ b/resourcemanager/apiv3/tag_bindings_client.go @@ -17,9 +17,12 @@ package resourcemanager import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,14 +30,17 @@ import ( lroauto "cloud.google.com/go/longrunning/autogen" resourcemanagerpb "cloud.google.com/go/resourcemanager/apiv3/resourcemanagerpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -77,6 +83,23 @@ func defaultTagBindingsCallOptions() *TagBindingsCallOptions { } } +func defaultTagBindingsRESTCallOptions() *TagBindingsCallOptions { + return &TagBindingsCallOptions{ + ListTagBindings: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateTagBinding: []gax.CallOption{}, + DeleteTagBinding: []gax.CallOption{}, + } +} + // internalTagBindingsClient is an interface that defines the methods available from Cloud Resource Manager API. type internalTagBindingsClient interface { Close() error @@ -260,6 +283,90 @@ func (c *tagBindingsGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type tagBindingsRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing TagBindingsClient + CallOptions **TagBindingsCallOptions +} + +// NewTagBindingsRESTClient creates a new tag bindings rest client. +// +// Allow users to create and manage TagBindings between TagValues and +// different cloud resources throughout the GCP resource hierarchy. +func NewTagBindingsRESTClient(ctx context.Context, opts ...option.ClientOption) (*TagBindingsClient, error) { + clientOpts := append(defaultTagBindingsRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultTagBindingsRESTCallOptions() + c := &tagBindingsRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &TagBindingsClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultTagBindingsRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://cloudresourcemanager.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://cloudresourcemanager.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://cloudresourcemanager.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *tagBindingsRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *tagBindingsRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *tagBindingsRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *tagBindingsGRPCClient) ListTagBindings(ctx context.Context, req *resourcemanagerpb.ListTagBindingsRequest, opts ...gax.CallOption) *TagBindingIterator { ctx = insertMetadata(ctx, c.xGoogMetadata) opts = append((*c.CallOptions).ListTagBindings[0:len((*c.CallOptions).ListTagBindings):len((*c.CallOptions).ListTagBindings)], opts...) @@ -349,9 +456,236 @@ func (c *tagBindingsGRPCClient) DeleteTagBinding(ctx context.Context, req *resou }, nil } +// ListTagBindings lists the TagBindings for the given cloud resource, as specified with +// parent. +// +// NOTE: The parent field is expected to be a full resource name: +// https://cloud.google.com/apis/design/resource_names#full_resource_name (at https://cloud.google.com/apis/design/resource_names#full_resource_name) +func (c *tagBindingsRESTClient) ListTagBindings(ctx context.Context, req *resourcemanagerpb.ListTagBindingsRequest, opts ...gax.CallOption) *TagBindingIterator { + it := &TagBindingIterator{} + req = proto.Clone(req).(*resourcemanagerpb.ListTagBindingsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*resourcemanagerpb.TagBinding, string, error) { + resp := &resourcemanagerpb.ListTagBindingsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/tagBindings") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + params.Add("parent", fmt.Sprintf("%v", req.GetParent())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetTagBindings(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CreateTagBinding creates a TagBinding between a TagValue and a cloud resource +// (currently project, folder, or organization). +func (c *tagBindingsRESTClient) CreateTagBinding(ctx context.Context, req *resourcemanagerpb.CreateTagBindingRequest, opts ...gax.CallOption) (*CreateTagBindingOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetTagBinding() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/tagBindings") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v3/%s", resp.GetName()) + return &CreateTagBindingOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteTagBinding deletes a TagBinding. +func (c *tagBindingsRESTClient) DeleteTagBinding(ctx context.Context, req *resourcemanagerpb.DeleteTagBindingRequest, opts ...gax.CallOption) (*DeleteTagBindingOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v3/%s", resp.GetName()) + return &DeleteTagBindingOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + // CreateTagBindingOperation manages a long-running operation from CreateTagBinding. type CreateTagBindingOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateTagBindingOperation returns a new CreateTagBindingOperation from a given name. @@ -362,10 +696,21 @@ func (c *tagBindingsGRPCClient) CreateTagBindingOperation(name string) *CreateTa } } +// CreateTagBindingOperation returns a new CreateTagBindingOperation from a given name. +// The name must be that of a previously created CreateTagBindingOperation, possibly from a different process. +func (c *tagBindingsRESTClient) CreateTagBindingOperation(name string) *CreateTagBindingOperation { + override := fmt.Sprintf("/v3/%s", name) + return &CreateTagBindingOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateTagBindingOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*resourcemanagerpb.TagBinding, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp resourcemanagerpb.TagBinding if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -383,6 +728,7 @@ func (op *CreateTagBindingOperation) Wait(ctx context.Context, opts ...gax.CallO // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateTagBindingOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*resourcemanagerpb.TagBinding, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp resourcemanagerpb.TagBinding if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -420,7 +766,8 @@ func (op *CreateTagBindingOperation) Name() string { // DeleteTagBindingOperation manages a long-running operation from DeleteTagBinding. type DeleteTagBindingOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteTagBindingOperation returns a new DeleteTagBindingOperation from a given name. @@ -431,10 +778,21 @@ func (c *tagBindingsGRPCClient) DeleteTagBindingOperation(name string) *DeleteTa } } +// DeleteTagBindingOperation returns a new DeleteTagBindingOperation from a given name. +// The name must be that of a previously created DeleteTagBindingOperation, possibly from a different process. +func (c *tagBindingsRESTClient) DeleteTagBindingOperation(name string) *DeleteTagBindingOperation { + override := fmt.Sprintf("/v3/%s", name) + return &DeleteTagBindingOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteTagBindingOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -448,6 +806,7 @@ func (op *DeleteTagBindingOperation) Wait(ctx context.Context, opts ...gax.CallO // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteTagBindingOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } diff --git a/resourcemanager/apiv3/tag_bindings_client_example_test.go b/resourcemanager/apiv3/tag_bindings_client_example_test.go index 889f3dca0fc1..f2cf9b6326ae 100644 --- a/resourcemanager/apiv3/tag_bindings_client_example_test.go +++ b/resourcemanager/apiv3/tag_bindings_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewTagBindingsClient() { _ = c } +func ExampleNewTagBindingsRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := resourcemanager.NewTagBindingsRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleTagBindingsClient_ListTagBindings() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/resourcemanager/apiv3/tag_keys_client.go b/resourcemanager/apiv3/tag_keys_client.go index 5488d88e0b35..846bb279d369 100644 --- a/resourcemanager/apiv3/tag_keys_client.go +++ b/resourcemanager/apiv3/tag_keys_client.go @@ -17,9 +17,12 @@ package resourcemanager import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,15 +30,18 @@ import ( lroauto "cloud.google.com/go/longrunning/autogen" resourcemanagerpb "cloud.google.com/go/resourcemanager/apiv3/resourcemanagerpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" iampb "google.golang.org/genproto/googleapis/iam/v1" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -108,6 +114,46 @@ func defaultTagKeysCallOptions() *TagKeysCallOptions { } } +func defaultTagKeysRESTCallOptions() *TagKeysCallOptions { + return &TagKeysCallOptions{ + ListTagKeys: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetTagKey: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateTagKey: []gax.CallOption{}, + UpdateTagKey: []gax.CallOption{}, + DeleteTagKey: []gax.CallOption{}, + GetIamPolicy: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + SetIamPolicy: []gax.CallOption{}, + TestIamPermissions: []gax.CallOption{}, + } +} + // internalTagKeysClient is an interface that defines the methods available from Cloud Resource Manager API. type internalTagKeysClient interface { Close() error @@ -339,6 +385,89 @@ func (c *tagKeysGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type tagKeysRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing TagKeysClient + CallOptions **TagKeysCallOptions +} + +// NewTagKeysRESTClient creates a new tag keys rest client. +// +// Allow users to create and manage tag keys. +func NewTagKeysRESTClient(ctx context.Context, opts ...option.ClientOption) (*TagKeysClient, error) { + clientOpts := append(defaultTagKeysRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultTagKeysRESTCallOptions() + c := &tagKeysRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &TagKeysClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultTagKeysRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://cloudresourcemanager.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://cloudresourcemanager.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://cloudresourcemanager.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *tagKeysRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *tagKeysRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *tagKeysRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *tagKeysGRPCClient) ListTagKeys(ctx context.Context, req *resourcemanagerpb.ListTagKeysRequest, opts ...gax.CallOption) *TagKeyIterator { ctx = insertMetadata(ctx, c.xGoogMetadata) opts = append((*c.CallOptions).ListTagKeys[0:len((*c.CallOptions).ListTagKeys):len((*c.CallOptions).ListTagKeys)], opts...) @@ -535,9 +664,584 @@ func (c *tagKeysGRPCClient) TestIamPermissions(ctx context.Context, req *iampb.T return resp, nil } +// ListTagKeys lists all TagKeys for a parent resource. +func (c *tagKeysRESTClient) ListTagKeys(ctx context.Context, req *resourcemanagerpb.ListTagKeysRequest, opts ...gax.CallOption) *TagKeyIterator { + it := &TagKeyIterator{} + req = proto.Clone(req).(*resourcemanagerpb.ListTagKeysRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*resourcemanagerpb.TagKey, string, error) { + resp := &resourcemanagerpb.ListTagKeysResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/tagKeys") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + params.Add("parent", fmt.Sprintf("%v", req.GetParent())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetTagKeys(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetTagKey retrieves a TagKey. This method will return PERMISSION_DENIED if the +// key does not exist or the user does not have permission to view it. +func (c *tagKeysRESTClient) GetTagKey(ctx context.Context, req *resourcemanagerpb.GetTagKeyRequest, opts ...gax.CallOption) (*resourcemanagerpb.TagKey, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetTagKey[0:len((*c.CallOptions).GetTagKey):len((*c.CallOptions).GetTagKey)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &resourcemanagerpb.TagKey{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateTagKey creates a new TagKey. If another request with the same parameters is +// sent while the original request is in process, the second request +// will receive an error. A maximum of 300 TagKeys can exist under a parent at +// any given time. +func (c *tagKeysRESTClient) CreateTagKey(ctx context.Context, req *resourcemanagerpb.CreateTagKeyRequest, opts ...gax.CallOption) (*CreateTagKeyOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetTagKey() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/tagKeys") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v3/%s", resp.GetName()) + return &CreateTagKeyOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateTagKey updates the attributes of the TagKey resource. +func (c *tagKeysRESTClient) UpdateTagKey(ctx context.Context, req *resourcemanagerpb.UpdateTagKeyRequest, opts ...gax.CallOption) (*UpdateTagKeyOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetTagKey() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetTagKey().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "tag_key.name", url.QueryEscape(req.GetTagKey().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v3/%s", resp.GetName()) + return &UpdateTagKeyOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteTagKey deletes a TagKey. The TagKey cannot be deleted if it has any child +// TagValues. +func (c *tagKeysRESTClient) DeleteTagKey(ctx context.Context, req *resourcemanagerpb.DeleteTagKeyRequest, opts ...gax.CallOption) (*DeleteTagKeyOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetEtag() != "" { + params.Add("etag", fmt.Sprintf("%v", req.GetEtag())) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v3/%s", resp.GetName()) + return &DeleteTagKeyOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetIamPolicy gets the access control policy for a TagKey. The returned policy may be +// empty if no such policy or resource exists. The resource field should +// be the TagKey’s resource name. For example, “tagKeys/1234”. +// The caller must have +// cloudresourcemanager.googleapis.com/tagKeys.getIamPolicy permission on +// the specified TagKey. +func (c *tagKeysRESTClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v:getIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SetIamPolicy sets the access control policy on a TagKey, replacing any existing +// policy. The resource field should be the TagKey’s resource name. +// For example, “tagKeys/1234”. +// The caller must have resourcemanager.tagKeys.setIamPolicy permission +// on the identified tagValue. +func (c *tagKeysRESTClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v:setIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// TestIamPermissions returns permissions that a caller has on the specified TagKey. +// The resource field should be the TagKey’s resource name. +// For example, “tagKeys/1234”. +// +// There are no permissions required for making this API call. +func (c *tagKeysRESTClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v:testIamPermissions", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.TestIamPermissionsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + // CreateTagKeyOperation manages a long-running operation from CreateTagKey. type CreateTagKeyOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateTagKeyOperation returns a new CreateTagKeyOperation from a given name. @@ -548,10 +1252,21 @@ func (c *tagKeysGRPCClient) CreateTagKeyOperation(name string) *CreateTagKeyOper } } +// CreateTagKeyOperation returns a new CreateTagKeyOperation from a given name. +// The name must be that of a previously created CreateTagKeyOperation, possibly from a different process. +func (c *tagKeysRESTClient) CreateTagKeyOperation(name string) *CreateTagKeyOperation { + override := fmt.Sprintf("/v3/%s", name) + return &CreateTagKeyOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateTagKeyOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*resourcemanagerpb.TagKey, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp resourcemanagerpb.TagKey if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -569,6 +1284,7 @@ func (op *CreateTagKeyOperation) Wait(ctx context.Context, opts ...gax.CallOptio // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateTagKeyOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*resourcemanagerpb.TagKey, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp resourcemanagerpb.TagKey if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -606,7 +1322,8 @@ func (op *CreateTagKeyOperation) Name() string { // DeleteTagKeyOperation manages a long-running operation from DeleteTagKey. type DeleteTagKeyOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteTagKeyOperation returns a new DeleteTagKeyOperation from a given name. @@ -617,10 +1334,21 @@ func (c *tagKeysGRPCClient) DeleteTagKeyOperation(name string) *DeleteTagKeyOper } } +// DeleteTagKeyOperation returns a new DeleteTagKeyOperation from a given name. +// The name must be that of a previously created DeleteTagKeyOperation, possibly from a different process. +func (c *tagKeysRESTClient) DeleteTagKeyOperation(name string) *DeleteTagKeyOperation { + override := fmt.Sprintf("/v3/%s", name) + return &DeleteTagKeyOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteTagKeyOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*resourcemanagerpb.TagKey, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp resourcemanagerpb.TagKey if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -638,6 +1366,7 @@ func (op *DeleteTagKeyOperation) Wait(ctx context.Context, opts ...gax.CallOptio // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteTagKeyOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*resourcemanagerpb.TagKey, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp resourcemanagerpb.TagKey if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -675,7 +1404,8 @@ func (op *DeleteTagKeyOperation) Name() string { // UpdateTagKeyOperation manages a long-running operation from UpdateTagKey. type UpdateTagKeyOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateTagKeyOperation returns a new UpdateTagKeyOperation from a given name. @@ -686,10 +1416,21 @@ func (c *tagKeysGRPCClient) UpdateTagKeyOperation(name string) *UpdateTagKeyOper } } +// UpdateTagKeyOperation returns a new UpdateTagKeyOperation from a given name. +// The name must be that of a previously created UpdateTagKeyOperation, possibly from a different process. +func (c *tagKeysRESTClient) UpdateTagKeyOperation(name string) *UpdateTagKeyOperation { + override := fmt.Sprintf("/v3/%s", name) + return &UpdateTagKeyOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateTagKeyOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*resourcemanagerpb.TagKey, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp resourcemanagerpb.TagKey if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -707,6 +1448,7 @@ func (op *UpdateTagKeyOperation) Wait(ctx context.Context, opts ...gax.CallOptio // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateTagKeyOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*resourcemanagerpb.TagKey, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp resourcemanagerpb.TagKey if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/resourcemanager/apiv3/tag_keys_client_example_test.go b/resourcemanager/apiv3/tag_keys_client_example_test.go index ba7b4285d56b..0b513d1a5d89 100644 --- a/resourcemanager/apiv3/tag_keys_client_example_test.go +++ b/resourcemanager/apiv3/tag_keys_client_example_test.go @@ -42,6 +42,23 @@ func ExampleNewTagKeysClient() { _ = c } +func ExampleNewTagKeysRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := resourcemanager.NewTagKeysRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleTagKeysClient_ListTagKeys() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/resourcemanager/apiv3/tag_values_client.go b/resourcemanager/apiv3/tag_values_client.go index 47005ca2a4d7..3ceea610fc5f 100644 --- a/resourcemanager/apiv3/tag_values_client.go +++ b/resourcemanager/apiv3/tag_values_client.go @@ -17,9 +17,12 @@ package resourcemanager import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,15 +30,18 @@ import ( lroauto "cloud.google.com/go/longrunning/autogen" resourcemanagerpb "cloud.google.com/go/resourcemanager/apiv3/resourcemanagerpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" iampb "google.golang.org/genproto/googleapis/iam/v1" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -108,6 +114,46 @@ func defaultTagValuesCallOptions() *TagValuesCallOptions { } } +func defaultTagValuesRESTCallOptions() *TagValuesCallOptions { + return &TagValuesCallOptions{ + ListTagValues: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetTagValue: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateTagValue: []gax.CallOption{}, + UpdateTagValue: []gax.CallOption{}, + DeleteTagValue: []gax.CallOption{}, + GetIamPolicy: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + SetIamPolicy: []gax.CallOption{}, + TestIamPermissions: []gax.CallOption{}, + } +} + // internalTagValuesClient is an interface that defines the methods available from Cloud Resource Manager API. type internalTagValuesClient interface { Close() error @@ -340,6 +386,89 @@ func (c *tagValuesGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type tagValuesRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing TagValuesClient + CallOptions **TagValuesCallOptions +} + +// NewTagValuesRESTClient creates a new tag values rest client. +// +// Allow users to create and manage tag values. +func NewTagValuesRESTClient(ctx context.Context, opts ...option.ClientOption) (*TagValuesClient, error) { + clientOpts := append(defaultTagValuesRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultTagValuesRESTCallOptions() + c := &tagValuesRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &TagValuesClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultTagValuesRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://cloudresourcemanager.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://cloudresourcemanager.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://cloudresourcemanager.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *tagValuesRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *tagValuesRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *tagValuesRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *tagValuesGRPCClient) ListTagValues(ctx context.Context, req *resourcemanagerpb.ListTagValuesRequest, opts ...gax.CallOption) *TagValueIterator { ctx = insertMetadata(ctx, c.xGoogMetadata) opts = append((*c.CallOptions).ListTagValues[0:len((*c.CallOptions).ListTagValues):len((*c.CallOptions).ListTagValues)], opts...) @@ -536,9 +665,585 @@ func (c *tagValuesGRPCClient) TestIamPermissions(ctx context.Context, req *iampb return resp, nil } +// ListTagValues lists all TagValues for a specific TagKey. +func (c *tagValuesRESTClient) ListTagValues(ctx context.Context, req *resourcemanagerpb.ListTagValuesRequest, opts ...gax.CallOption) *TagValueIterator { + it := &TagValueIterator{} + req = proto.Clone(req).(*resourcemanagerpb.ListTagValuesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*resourcemanagerpb.TagValue, string, error) { + resp := &resourcemanagerpb.ListTagValuesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/tagValues") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + params.Add("parent", fmt.Sprintf("%v", req.GetParent())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetTagValues(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetTagValue retrieves TagValue. If the TagValue or namespaced name does not exist, or +// if the user does not have permission to view it, this method will return +// PERMISSION_DENIED. +func (c *tagValuesRESTClient) GetTagValue(ctx context.Context, req *resourcemanagerpb.GetTagValueRequest, opts ...gax.CallOption) (*resourcemanagerpb.TagValue, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetTagValue[0:len((*c.CallOptions).GetTagValue):len((*c.CallOptions).GetTagValue)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &resourcemanagerpb.TagValue{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateTagValue creates a TagValue as a child of the specified TagKey. If a another +// request with the same parameters is sent while the original request is in +// process the second request will receive an error. A maximum of 300 +// TagValues can exist under a TagKey at any given time. +func (c *tagValuesRESTClient) CreateTagValue(ctx context.Context, req *resourcemanagerpb.CreateTagValueRequest, opts ...gax.CallOption) (*CreateTagValueOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetTagValue() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/tagValues") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v3/%s", resp.GetName()) + return &CreateTagValueOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateTagValue updates the attributes of the TagValue resource. +func (c *tagValuesRESTClient) UpdateTagValue(ctx context.Context, req *resourcemanagerpb.UpdateTagValueRequest, opts ...gax.CallOption) (*UpdateTagValueOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetTagValue() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetTagValue().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "tag_value.name", url.QueryEscape(req.GetTagValue().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v3/%s", resp.GetName()) + return &UpdateTagValueOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteTagValue deletes a TagValue. The TagValue cannot have any bindings when it is +// deleted. +func (c *tagValuesRESTClient) DeleteTagValue(ctx context.Context, req *resourcemanagerpb.DeleteTagValueRequest, opts ...gax.CallOption) (*DeleteTagValueOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetEtag() != "" { + params.Add("etag", fmt.Sprintf("%v", req.GetEtag())) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v3/%s", resp.GetName()) + return &DeleteTagValueOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetIamPolicy gets the access control policy for a TagValue. The returned policy may be +// empty if no such policy or resource exists. The resource field should +// be the TagValue’s resource name. For example: tagValues/1234. +// The caller must have the +// cloudresourcemanager.googleapis.com/tagValues.getIamPolicy permission on +// the identified TagValue to get the access control policy. +func (c *tagValuesRESTClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v:getIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SetIamPolicy sets the access control policy on a TagValue, replacing any existing +// policy. The resource field should be the TagValue’s resource name. +// For example: tagValues/1234. +// The caller must have resourcemanager.tagValues.setIamPolicy permission +// on the identified tagValue. +func (c *tagValuesRESTClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v:setIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// TestIamPermissions returns permissions that a caller has on the specified TagValue. +// The resource field should be the TagValue’s resource name. For example: +// tagValues/1234. +// +// There are no permissions required for making this API call. +func (c *tagValuesRESTClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v:testIamPermissions", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.TestIamPermissionsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + // CreateTagValueOperation manages a long-running operation from CreateTagValue. type CreateTagValueOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateTagValueOperation returns a new CreateTagValueOperation from a given name. @@ -549,10 +1254,21 @@ func (c *tagValuesGRPCClient) CreateTagValueOperation(name string) *CreateTagVal } } +// CreateTagValueOperation returns a new CreateTagValueOperation from a given name. +// The name must be that of a previously created CreateTagValueOperation, possibly from a different process. +func (c *tagValuesRESTClient) CreateTagValueOperation(name string) *CreateTagValueOperation { + override := fmt.Sprintf("/v3/%s", name) + return &CreateTagValueOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateTagValueOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*resourcemanagerpb.TagValue, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp resourcemanagerpb.TagValue if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -570,6 +1286,7 @@ func (op *CreateTagValueOperation) Wait(ctx context.Context, opts ...gax.CallOpt // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateTagValueOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*resourcemanagerpb.TagValue, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp resourcemanagerpb.TagValue if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -607,7 +1324,8 @@ func (op *CreateTagValueOperation) Name() string { // DeleteTagValueOperation manages a long-running operation from DeleteTagValue. type DeleteTagValueOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteTagValueOperation returns a new DeleteTagValueOperation from a given name. @@ -618,10 +1336,21 @@ func (c *tagValuesGRPCClient) DeleteTagValueOperation(name string) *DeleteTagVal } } +// DeleteTagValueOperation returns a new DeleteTagValueOperation from a given name. +// The name must be that of a previously created DeleteTagValueOperation, possibly from a different process. +func (c *tagValuesRESTClient) DeleteTagValueOperation(name string) *DeleteTagValueOperation { + override := fmt.Sprintf("/v3/%s", name) + return &DeleteTagValueOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteTagValueOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*resourcemanagerpb.TagValue, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp resourcemanagerpb.TagValue if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -639,6 +1368,7 @@ func (op *DeleteTagValueOperation) Wait(ctx context.Context, opts ...gax.CallOpt // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteTagValueOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*resourcemanagerpb.TagValue, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp resourcemanagerpb.TagValue if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -676,7 +1406,8 @@ func (op *DeleteTagValueOperation) Name() string { // UpdateTagValueOperation manages a long-running operation from UpdateTagValue. type UpdateTagValueOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateTagValueOperation returns a new UpdateTagValueOperation from a given name. @@ -687,10 +1418,21 @@ func (c *tagValuesGRPCClient) UpdateTagValueOperation(name string) *UpdateTagVal } } +// UpdateTagValueOperation returns a new UpdateTagValueOperation from a given name. +// The name must be that of a previously created UpdateTagValueOperation, possibly from a different process. +func (c *tagValuesRESTClient) UpdateTagValueOperation(name string) *UpdateTagValueOperation { + override := fmt.Sprintf("/v3/%s", name) + return &UpdateTagValueOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateTagValueOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*resourcemanagerpb.TagValue, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp resourcemanagerpb.TagValue if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -708,6 +1450,7 @@ func (op *UpdateTagValueOperation) Wait(ctx context.Context, opts ...gax.CallOpt // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateTagValueOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*resourcemanagerpb.TagValue, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp resourcemanagerpb.TagValue if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/resourcemanager/apiv3/tag_values_client_example_test.go b/resourcemanager/apiv3/tag_values_client_example_test.go index 5d0bf4bc7425..99e8bfe3d111 100644 --- a/resourcemanager/apiv3/tag_values_client_example_test.go +++ b/resourcemanager/apiv3/tag_values_client_example_test.go @@ -42,6 +42,23 @@ func ExampleNewTagValuesClient() { _ = c } +func ExampleNewTagValuesRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := resourcemanager.NewTagValuesRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleTagValuesClient_ListTagValues() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/resourcesettings/apiv1/doc.go b/resourcesettings/apiv1/doc.go index 8436f662d641..22bdd6365da2 100644 --- a/resourcesettings/apiv1/doc.go +++ b/resourcesettings/apiv1/doc.go @@ -88,6 +88,8 @@ package resourcesettings // import "cloud.google.com/go/resourcesettings/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -176,3 +178,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/resourcesettings/apiv1/gapic_metadata.json b/resourcesettings/apiv1/gapic_metadata.json index a07edb31e640..a5af1d011de9 100644 --- a/resourcesettings/apiv1/gapic_metadata.json +++ b/resourcesettings/apiv1/gapic_metadata.json @@ -26,6 +26,26 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "GetSetting": { + "methods": [ + "GetSetting" + ] + }, + "ListSettings": { + "methods": [ + "ListSettings" + ] + }, + "UpdateSetting": { + "methods": [ + "UpdateSetting" + ] + } + } } } } diff --git a/resourcesettings/apiv1/resource_settings_client.go b/resourcesettings/apiv1/resource_settings_client.go index c2a665fd8327..5b77ac40792d 100644 --- a/resourcesettings/apiv1/resource_settings_client.go +++ b/resourcesettings/apiv1/resource_settings_client.go @@ -17,21 +17,27 @@ package resourcesettings import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" resourcesettingspb "cloud.google.com/go/resourcesettings/apiv1/resourcesettingspb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -97,6 +103,44 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + ListSettings: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + GetSetting: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + UpdateSetting: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + } +} + // internalClient is an interface that defines the methods available from Resource Settings API. type internalClient interface { Close() error @@ -278,6 +322,85 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new resource settings service rest client. +// +// An interface to interact with resource settings and setting values throughout +// the resource hierarchy. +// +// Services may surface a number of settings for users to control how their +// resources behave. Values of settings applied on a given Cloud resource are +// evaluated hierarchically and inherited by all descendants of that resource. +// +// For all requests, returns a google.rpc.Status with +// google.rpc.Code.PERMISSION_DENIED if the IAM check fails or the parent +// resource is not in a Cloud Organization. +// For all requests, returns a google.rpc.Status with +// google.rpc.Code.INVALID_ARGUMENT if the request is malformed. +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://resourcesettings.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://resourcesettings.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://resourcesettings.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) ListSettings(ctx context.Context, req *resourcesettingspb.ListSettingsRequest, opts ...gax.CallOption) *SettingIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -367,6 +490,241 @@ func (c *gRPCClient) UpdateSetting(ctx context.Context, req *resourcesettingspb. return resp, nil } +// ListSettings lists all the settings that are available on the Cloud resource parent. +func (c *restClient) ListSettings(ctx context.Context, req *resourcesettingspb.ListSettingsRequest, opts ...gax.CallOption) *SettingIterator { + it := &SettingIterator{} + req = proto.Clone(req).(*resourcesettingspb.ListSettingsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*resourcesettingspb.Setting, string, error) { + resp := &resourcesettingspb.ListSettingsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/settings", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + if req.GetView() != 0 { + params.Add("view", fmt.Sprintf("%v", req.GetView())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetSettings(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetSetting gets a setting. +// +// Returns a google.rpc.Status with google.rpc.Code.NOT_FOUND if the +// setting does not exist. +func (c *restClient) GetSetting(ctx context.Context, req *resourcesettingspb.GetSettingRequest, opts ...gax.CallOption) (*resourcesettingspb.Setting, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetView() != 0 { + params.Add("view", fmt.Sprintf("%v", req.GetView())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetSetting[0:len((*c.CallOptions).GetSetting):len((*c.CallOptions).GetSetting)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &resourcesettingspb.Setting{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateSetting updates a setting. +// +// Returns a google.rpc.Status with google.rpc.Code.NOT_FOUND if the +// setting does not exist. +// Returns a google.rpc.Status with google.rpc.Code.FAILED_PRECONDITION if +// the setting is flagged as read only. +// Returns a google.rpc.Status with google.rpc.Code.ABORTED if the etag +// supplied in the request does not match the persisted etag of the setting +// value. +// +// On success, the response will contain only name, local_value and +// etag. The metadata and effective_value cannot be updated through +// this API. +// +// Note: the supplied setting will perform a full overwrite of the +// local_value field. +func (c *restClient) UpdateSetting(ctx context.Context, req *resourcesettingspb.UpdateSettingRequest, opts ...gax.CallOption) (*resourcesettingspb.Setting, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetSetting() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetSetting().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "setting.name", url.QueryEscape(req.GetSetting().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateSetting[0:len((*c.CallOptions).UpdateSetting):len((*c.CallOptions).UpdateSetting)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &resourcesettingspb.Setting{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + // SettingIterator manages a stream of *resourcesettingspb.Setting. type SettingIterator struct { items []*resourcesettingspb.Setting diff --git a/resourcesettings/apiv1/resource_settings_client_example_test.go b/resourcesettings/apiv1/resource_settings_client_example_test.go index de4d09003612..94d1554d9b8a 100644 --- a/resourcesettings/apiv1/resource_settings_client_example_test.go +++ b/resourcesettings/apiv1/resource_settings_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := resourcesettings.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_ListSettings() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/resourcesettings/apiv1/resourcesettingspb/resource_settings.pb.go b/resourcesettings/apiv1/resourcesettingspb/resource_settings.pb.go index 8e4fa768d601..59291a79fbda 100644 --- a/resourcesettings/apiv1/resourcesettingspb/resource_settings.pb.go +++ b/resourcesettings/apiv1/resourcesettingspb/resource_settings.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/resourcesettings/v1/resource_settings.proto package resourcesettingspb @@ -187,11 +187,11 @@ type Setting struct { // The effective value evaluates to one of the following options in the given // order (the next option is used if the previous one does not exist): // - // 1. the local setting value on the given resource: [Setting.local_value][google.cloud.resourcesettings.v1.Setting.local_value] - // 2. if one of the given resource's ancestors have a local setting value, - // the local value at the nearest such ancestor - // 3. the setting's default value: [SettingMetadata.default_value][google.cloud.resourcesettings.v1.SettingMetadata.default_value] - // 4. an empty value (defined as a `Value` with all fields unset) + // 1. the local setting value on the given resource: [Setting.local_value][google.cloud.resourcesettings.v1.Setting.local_value] + // 2. if one of the given resource's ancestors have a local setting value, + // the local value at the nearest such ancestor + // 3. the setting's default value: [SettingMetadata.default_value][google.cloud.resourcesettings.v1.SettingMetadata.default_value] + // 4. an empty value (defined as a `Value` with all fields unset) // // The data type of [Value][google.cloud.resourcesettings.v1.Value] must always be // consistent with the data type defined in [Setting.metadata][google.cloud.resourcesettings.v1.Setting.metadata]. @@ -367,7 +367,6 @@ type Value struct { // Selects the data type and associated value. // // Types that are assignable to Value: - // // *Value_BooleanValue // *Value_StringValue // *Value_StringSetValue diff --git a/retail/apiv2/catalog_client.go b/retail/apiv2/catalog_client.go index fd9289316ce1..2f41eeb889e5 100644 --- a/retail/apiv2/catalog_client.go +++ b/retail/apiv2/catalog_client.go @@ -17,22 +17,28 @@ package retail import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" retailpb "cloud.google.com/go/retail/apiv2/retailpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -217,6 +223,144 @@ func defaultCatalogCallOptions() *CatalogCallOptions { } } +func defaultCatalogRESTCallOptions() *CatalogCallOptions { + return &CatalogCallOptions{ + ListCatalogs: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 5000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + UpdateCatalog: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 5000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + SetDefaultBranch: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 5000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + GetDefaultBranch: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 5000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + GetCompletionConfig: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 5000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + UpdateCompletionConfig: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 5000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + GetAttributesConfig: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 5000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + UpdateAttributesConfig: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 5000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + AddCatalogAttribute: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 5000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + RemoveCatalogAttribute: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 5000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + ReplaceCatalogAttribute: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 5000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 300000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + } +} + // internalCatalogClient is an interface that defines the methods available from Retail API. type internalCatalogClient interface { Close() error @@ -482,6 +626,74 @@ func (c *catalogGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type catalogRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing CatalogClient + CallOptions **CatalogCallOptions +} + +// NewCatalogRESTClient creates a new catalog service rest client. +// +// Service for managing catalog configuration. +func NewCatalogRESTClient(ctx context.Context, opts ...option.ClientOption) (*CatalogClient, error) { + clientOpts := append(defaultCatalogRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultCatalogRESTCallOptions() + c := &catalogRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &CatalogClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultCatalogRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://retail.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://retail.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://retail.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *catalogRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *catalogRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *catalogRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *catalogGRPCClient) ListCatalogs(ctx context.Context, req *retailpb.ListCatalogsRequest, opts ...gax.CallOption) *CatalogIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -805,6 +1017,932 @@ func (c *catalogGRPCClient) ListOperations(ctx context.Context, req *longrunning return it } +// ListCatalogs lists all the Catalogs associated with +// the project. +func (c *catalogRESTClient) ListCatalogs(ctx context.Context, req *retailpb.ListCatalogsRequest, opts ...gax.CallOption) *CatalogIterator { + it := &CatalogIterator{} + req = proto.Clone(req).(*retailpb.ListCatalogsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*retailpb.Catalog, string, error) { + resp := &retailpb.ListCatalogsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/catalogs", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetCatalogs(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// UpdateCatalog updates the Catalogs. +func (c *catalogRESTClient) UpdateCatalog(ctx context.Context, req *retailpb.UpdateCatalogRequest, opts ...gax.CallOption) (*retailpb.Catalog, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetCatalog() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetCatalog().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "catalog.name", url.QueryEscape(req.GetCatalog().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateCatalog[0:len((*c.CallOptions).UpdateCatalog):len((*c.CallOptions).UpdateCatalog)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &retailpb.Catalog{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SetDefaultBranch set a specified branch id as default branch. API methods such as +// SearchService.Search, +// ProductService.GetProduct, +// ProductService.ListProducts +// will treat requests using “default_branch” to the actual branch id set as +// default. +// +// For example, if projects/*/locations/*/catalogs/*/branches/1 is set as +// default, setting +// SearchRequest.branch to +// projects/*/locations/*/catalogs/*/branches/default_branch is equivalent +// to setting +// SearchRequest.branch to +// projects/*/locations/*/catalogs/*/branches/1. +// +// Using multiple branches can be useful when developers would like +// to have a staging branch to test and verify for future usage. When it +// becomes ready, developers switch on the staging branch using this API while +// keeping using projects/*/locations/*/catalogs/*/branches/default_branch +// as SearchRequest.branch to +// route the traffic to this staging branch. +// +// CAUTION: If you have live predict/search traffic, switching the default +// branch could potentially cause outages if the ID space of the new branch is +// very different from the old one. +// +// More specifically: +// +// PredictionService will only return product IDs from branch {newBranch}. +// +// SearchService will only return product IDs from branch {newBranch} +// (if branch is not explicitly set). +// +// UserEventService will only join events with products from branch +// {newBranch}. +func (c *catalogRESTClient) SetDefaultBranch(ctx context.Context, req *retailpb.SetDefaultBranchRequest, opts ...gax.CallOption) error { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:setDefaultBranch", req.GetCatalog()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "catalog", url.QueryEscape(req.GetCatalog()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetDefaultBranch get which branch is currently default branch set by +// CatalogService.SetDefaultBranch +// method under a specified parent catalog. +func (c *catalogRESTClient) GetDefaultBranch(ctx context.Context, req *retailpb.GetDefaultBranchRequest, opts ...gax.CallOption) (*retailpb.GetDefaultBranchResponse, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:getDefaultBranch", req.GetCatalog()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "catalog", url.QueryEscape(req.GetCatalog()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetDefaultBranch[0:len((*c.CallOptions).GetDefaultBranch):len((*c.CallOptions).GetDefaultBranch)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &retailpb.GetDefaultBranchResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetCompletionConfig gets a CompletionConfig. +func (c *catalogRESTClient) GetCompletionConfig(ctx context.Context, req *retailpb.GetCompletionConfigRequest, opts ...gax.CallOption) (*retailpb.CompletionConfig, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetCompletionConfig[0:len((*c.CallOptions).GetCompletionConfig):len((*c.CallOptions).GetCompletionConfig)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &retailpb.CompletionConfig{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateCompletionConfig updates the CompletionConfigs. +func (c *catalogRESTClient) UpdateCompletionConfig(ctx context.Context, req *retailpb.UpdateCompletionConfigRequest, opts ...gax.CallOption) (*retailpb.CompletionConfig, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetCompletionConfig() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetCompletionConfig().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "completion_config.name", url.QueryEscape(req.GetCompletionConfig().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateCompletionConfig[0:len((*c.CallOptions).UpdateCompletionConfig):len((*c.CallOptions).UpdateCompletionConfig)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &retailpb.CompletionConfig{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetAttributesConfig gets an AttributesConfig. +func (c *catalogRESTClient) GetAttributesConfig(ctx context.Context, req *retailpb.GetAttributesConfigRequest, opts ...gax.CallOption) (*retailpb.AttributesConfig, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetAttributesConfig[0:len((*c.CallOptions).GetAttributesConfig):len((*c.CallOptions).GetAttributesConfig)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &retailpb.AttributesConfig{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateAttributesConfig updates the AttributesConfig. +// +// The catalog attributes in the request will be updated in the catalog, or +// inserted if they do not exist. Existing catalog attributes not included in +// the request will remain unchanged. Attributes that are assigned to +// products, but do not exist at the catalog level, are always included in the +// response. The product attribute is assigned default values for missing +// catalog attribute fields, e.g., searchable and dynamic facetable options. +func (c *catalogRESTClient) UpdateAttributesConfig(ctx context.Context, req *retailpb.UpdateAttributesConfigRequest, opts ...gax.CallOption) (*retailpb.AttributesConfig, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetAttributesConfig() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetAttributesConfig().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "attributes_config.name", url.QueryEscape(req.GetAttributesConfig().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateAttributesConfig[0:len((*c.CallOptions).UpdateAttributesConfig):len((*c.CallOptions).UpdateAttributesConfig)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &retailpb.AttributesConfig{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// AddCatalogAttribute adds the specified +// CatalogAttribute to the +// AttributesConfig. +// +// If the CatalogAttribute to add +// already exists, an ALREADY_EXISTS error is returned. +func (c *catalogRESTClient) AddCatalogAttribute(ctx context.Context, req *retailpb.AddCatalogAttributeRequest, opts ...gax.CallOption) (*retailpb.AttributesConfig, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:addCatalogAttribute", req.GetAttributesConfig()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "attributes_config", url.QueryEscape(req.GetAttributesConfig()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).AddCatalogAttribute[0:len((*c.CallOptions).AddCatalogAttribute):len((*c.CallOptions).AddCatalogAttribute)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &retailpb.AttributesConfig{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// RemoveCatalogAttribute removes the specified +// CatalogAttribute from the +// AttributesConfig. +// +// If the CatalogAttribute to +// remove does not exist, a NOT_FOUND error is returned. +func (c *catalogRESTClient) RemoveCatalogAttribute(ctx context.Context, req *retailpb.RemoveCatalogAttributeRequest, opts ...gax.CallOption) (*retailpb.AttributesConfig, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:removeCatalogAttribute", req.GetAttributesConfig()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "attributes_config", url.QueryEscape(req.GetAttributesConfig()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).RemoveCatalogAttribute[0:len((*c.CallOptions).RemoveCatalogAttribute):len((*c.CallOptions).RemoveCatalogAttribute)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &retailpb.AttributesConfig{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ReplaceCatalogAttribute replaces the specified +// CatalogAttribute in the +// AttributesConfig by updating the +// catalog attribute with the same +// CatalogAttribute.key. +// +// If the CatalogAttribute to +// replace does not exist, a NOT_FOUND error is returned. +func (c *catalogRESTClient) ReplaceCatalogAttribute(ctx context.Context, req *retailpb.ReplaceCatalogAttributeRequest, opts ...gax.CallOption) (*retailpb.AttributesConfig, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:replaceCatalogAttribute", req.GetAttributesConfig()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "attributes_config", url.QueryEscape(req.GetAttributesConfig()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).ReplaceCatalogAttribute[0:len((*c.CallOptions).ReplaceCatalogAttribute):len((*c.CallOptions).ReplaceCatalogAttribute)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &retailpb.AttributesConfig{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *catalogRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *catalogRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + // CatalogIterator manages a stream of *retailpb.Catalog. type CatalogIterator struct { items []*retailpb.Catalog diff --git a/retail/apiv2/catalog_client_example_test.go b/retail/apiv2/catalog_client_example_test.go index 2e06f2fc2d2c..2a4d310c9595 100644 --- a/retail/apiv2/catalog_client_example_test.go +++ b/retail/apiv2/catalog_client_example_test.go @@ -42,6 +42,23 @@ func ExampleNewCatalogClient() { _ = c } +func ExampleNewCatalogRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := retail.NewCatalogRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleCatalogClient_ListCatalogs() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/retail/apiv2/completion_client.go b/retail/apiv2/completion_client.go index 65fd071b164d..202481405783 100644 --- a/retail/apiv2/completion_client.go +++ b/retail/apiv2/completion_client.go @@ -17,9 +17,12 @@ package retail import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,14 +30,17 @@ import ( lroauto "cloud.google.com/go/longrunning/autogen" retailpb "cloud.google.com/go/retail/apiv2/retailpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -102,6 +108,45 @@ func defaultCompletionCallOptions() *CompletionCallOptions { } } +func defaultCompletionRESTCallOptions() *CompletionCallOptions { + return &CompletionCallOptions{ + CompleteQuery: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 5000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + ImportCompletionData: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 5000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 300000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + } +} + // internalCompletionClient is an interface that defines the methods available from Retail API. type internalCompletionClient interface { Close() error @@ -297,6 +342,92 @@ func (c *completionGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type completionRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing CompletionClient + CallOptions **CompletionCallOptions +} + +// NewCompletionRESTClient creates a new completion service rest client. +// +// Auto-completion service for retail. +// +// This feature is only available for users who have Retail Search enabled. +// Please enable Retail Search on Cloud Console before using this feature. +func NewCompletionRESTClient(ctx context.Context, opts ...option.ClientOption) (*CompletionClient, error) { + clientOpts := append(defaultCompletionRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultCompletionRESTCallOptions() + c := &completionRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &CompletionClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultCompletionRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://retail.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://retail.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://retail.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *completionRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *completionRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *completionRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *completionGRPCClient) CompleteQuery(ctx context.Context, req *retailpb.CompleteQueryRequest, opts ...gax.CallOption) (*retailpb.CompleteQueryResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 5000*time.Millisecond) @@ -405,9 +536,314 @@ func (c *completionGRPCClient) ListOperations(ctx context.Context, req *longrunn return it } +// CompleteQuery completes the specified prefix with keyword suggestions. +// +// This feature is only available for users who have Retail Search enabled. +// Please enable Retail Search on Cloud Console before using this feature. +func (c *completionRESTClient) CompleteQuery(ctx context.Context, req *retailpb.CompleteQueryRequest, opts ...gax.CallOption) (*retailpb.CompleteQueryResponse, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:completeQuery", req.GetCatalog()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetDataset() != "" { + params.Add("dataset", fmt.Sprintf("%v", req.GetDataset())) + } + if req.GetDeviceType() != "" { + params.Add("deviceType", fmt.Sprintf("%v", req.GetDeviceType())) + } + if items := req.GetLanguageCodes(); len(items) > 0 { + for _, item := range items { + params.Add("languageCodes", fmt.Sprintf("%v", item)) + } + } + if req.GetMaxSuggestions() != 0 { + params.Add("maxSuggestions", fmt.Sprintf("%v", req.GetMaxSuggestions())) + } + params.Add("query", fmt.Sprintf("%v", req.GetQuery())) + if req.GetVisitorId() != "" { + params.Add("visitorId", fmt.Sprintf("%v", req.GetVisitorId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "catalog", url.QueryEscape(req.GetCatalog()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CompleteQuery[0:len((*c.CallOptions).CompleteQuery):len((*c.CallOptions).CompleteQuery)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &retailpb.CompleteQueryResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ImportCompletionData bulk import of processed completion dataset. +// +// Request processing is asynchronous. Partial updating is not supported. +// +// The operation is successfully finished only after the imported suggestions +// are indexed successfully and ready for serving. The process takes hours. +// +// This feature is only available for users who have Retail Search enabled. +// Please enable Retail Search on Cloud Console before using this feature. +func (c *completionRESTClient) ImportCompletionData(ctx context.Context, req *retailpb.ImportCompletionDataRequest, opts ...gax.CallOption) (*ImportCompletionDataOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/completionData:import", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &ImportCompletionDataOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *completionRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *completionRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + // ImportCompletionDataOperation manages a long-running operation from ImportCompletionData. type ImportCompletionDataOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // ImportCompletionDataOperation returns a new ImportCompletionDataOperation from a given name. @@ -418,10 +854,21 @@ func (c *completionGRPCClient) ImportCompletionDataOperation(name string) *Impor } } +// ImportCompletionDataOperation returns a new ImportCompletionDataOperation from a given name. +// The name must be that of a previously created ImportCompletionDataOperation, possibly from a different process. +func (c *completionRESTClient) ImportCompletionDataOperation(name string) *ImportCompletionDataOperation { + override := fmt.Sprintf("/v2/%s", name) + return &ImportCompletionDataOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *ImportCompletionDataOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*retailpb.ImportCompletionDataResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp retailpb.ImportCompletionDataResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -439,6 +886,7 @@ func (op *ImportCompletionDataOperation) Wait(ctx context.Context, opts ...gax.C // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *ImportCompletionDataOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*retailpb.ImportCompletionDataResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp retailpb.ImportCompletionDataResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/retail/apiv2/completion_client_example_test.go b/retail/apiv2/completion_client_example_test.go index 06436b77f14b..688df4231ce7 100644 --- a/retail/apiv2/completion_client_example_test.go +++ b/retail/apiv2/completion_client_example_test.go @@ -42,6 +42,23 @@ func ExampleNewCompletionClient() { _ = c } +func ExampleNewCompletionRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := retail.NewCompletionRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleCompletionClient_CompleteQuery() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/retail/apiv2/control_client.go b/retail/apiv2/control_client.go index 45ed913ae5ec..7f0988eb74f2 100644 --- a/retail/apiv2/control_client.go +++ b/retail/apiv2/control_client.go @@ -17,22 +17,28 @@ package retail import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" retailpb "cloud.google.com/go/retail/apiv2/retailpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -84,6 +90,28 @@ func defaultControlCallOptions() *ControlCallOptions { } } +func defaultControlRESTCallOptions() *ControlCallOptions { + return &ControlCallOptions{ + CreateControl: []gax.CallOption{}, + DeleteControl: []gax.CallOption{}, + UpdateControl: []gax.CallOption{}, + GetControl: []gax.CallOption{}, + ListControls: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 300000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + } +} + // internalControlClient is an interface that defines the methods available from Retail API. type internalControlClient interface { Close() error @@ -264,6 +292,74 @@ func (c *controlGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type controlRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing ControlClient + CallOptions **ControlCallOptions +} + +// NewControlRESTClient creates a new control service rest client. +// +// Service for modifying Control. +func NewControlRESTClient(ctx context.Context, opts ...option.ClientOption) (*ControlClient, error) { + clientOpts := append(defaultControlRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultControlRESTCallOptions() + c := &controlRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &ControlClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultControlRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://retail.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://retail.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://retail.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *controlRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *controlRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *controlRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *controlGRPCClient) CreateControl(ctx context.Context, req *retailpb.CreateControlRequest, opts ...gax.CallOption) (*retailpb.Control, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -435,6 +531,494 @@ func (c *controlGRPCClient) ListOperations(ctx context.Context, req *longrunning return it } +// CreateControl creates a Control. +// +// If the Control to create already exists, +// an ALREADY_EXISTS error is returned. +func (c *controlRESTClient) CreateControl(ctx context.Context, req *retailpb.CreateControlRequest, opts ...gax.CallOption) (*retailpb.Control, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetControl() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/controls", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("controlId", fmt.Sprintf("%v", req.GetControlId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateControl[0:len((*c.CallOptions).CreateControl):len((*c.CallOptions).CreateControl)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &retailpb.Control{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteControl deletes a Control. +// +// If the Control to delete does not exist, +// a NOT_FOUND error is returned. +func (c *controlRESTClient) DeleteControl(ctx context.Context, req *retailpb.DeleteControlRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// UpdateControl updates a Control. +// +// Control cannot be set to a different +// oneof field, if so an INVALID_ARGUMENT is returned. If the +// Control to update does not exist, a +// NOT_FOUND error is returned. +func (c *controlRESTClient) UpdateControl(ctx context.Context, req *retailpb.UpdateControlRequest, opts ...gax.CallOption) (*retailpb.Control, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetControl() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetControl().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "control.name", url.QueryEscape(req.GetControl().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateControl[0:len((*c.CallOptions).UpdateControl):len((*c.CallOptions).UpdateControl)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &retailpb.Control{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetControl gets a Control. +func (c *controlRESTClient) GetControl(ctx context.Context, req *retailpb.GetControlRequest, opts ...gax.CallOption) (*retailpb.Control, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetControl[0:len((*c.CallOptions).GetControl):len((*c.CallOptions).GetControl)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &retailpb.Control{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListControls lists all Controls by their parent +// Catalog. +func (c *controlRESTClient) ListControls(ctx context.Context, req *retailpb.ListControlsRequest, opts ...gax.CallOption) *ControlIterator { + it := &ControlIterator{} + req = proto.Clone(req).(*retailpb.ListControlsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*retailpb.Control, string, error) { + resp := &retailpb.ListControlsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/controls", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetControls(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *controlRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *controlRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + // ControlIterator manages a stream of *retailpb.Control. type ControlIterator struct { items []*retailpb.Control diff --git a/retail/apiv2/control_client_example_test.go b/retail/apiv2/control_client_example_test.go index 1a63d64a25fe..8698970e1b2c 100644 --- a/retail/apiv2/control_client_example_test.go +++ b/retail/apiv2/control_client_example_test.go @@ -42,6 +42,23 @@ func ExampleNewControlClient() { _ = c } +func ExampleNewControlRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := retail.NewControlRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleControlClient_CreateControl() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/retail/apiv2/doc.go b/retail/apiv2/doc.go index 0386fb9f5467..f33dcc03dc44 100644 --- a/retail/apiv2/doc.go +++ b/retail/apiv2/doc.go @@ -88,6 +88,8 @@ package retail // import "cloud.google.com/go/retail/apiv2" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -176,3 +178,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/retail/apiv2/gapic_metadata.json b/retail/apiv2/gapic_metadata.json index 03b46e048fee..f668ee6b3158 100644 --- a/retail/apiv2/gapic_metadata.json +++ b/retail/apiv2/gapic_metadata.json @@ -76,6 +76,76 @@ ] } } + }, + "rest": { + "libraryClient": "CatalogClient", + "rpcs": { + "AddCatalogAttribute": { + "methods": [ + "AddCatalogAttribute" + ] + }, + "GetAttributesConfig": { + "methods": [ + "GetAttributesConfig" + ] + }, + "GetCompletionConfig": { + "methods": [ + "GetCompletionConfig" + ] + }, + "GetDefaultBranch": { + "methods": [ + "GetDefaultBranch" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ListCatalogs": { + "methods": [ + "ListCatalogs" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "RemoveCatalogAttribute": { + "methods": [ + "RemoveCatalogAttribute" + ] + }, + "ReplaceCatalogAttribute": { + "methods": [ + "ReplaceCatalogAttribute" + ] + }, + "SetDefaultBranch": { + "methods": [ + "SetDefaultBranch" + ] + }, + "UpdateAttributesConfig": { + "methods": [ + "UpdateAttributesConfig" + ] + }, + "UpdateCatalog": { + "methods": [ + "UpdateCatalog" + ] + }, + "UpdateCompletionConfig": { + "methods": [ + "UpdateCompletionConfig" + ] + } + } } } }, @@ -105,6 +175,31 @@ ] } } + }, + "rest": { + "libraryClient": "CompletionClient", + "rpcs": { + "CompleteQuery": { + "methods": [ + "CompleteQuery" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ImportCompletionData": { + "methods": [ + "ImportCompletionData" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + } + } } } }, @@ -149,6 +244,46 @@ ] } } + }, + "rest": { + "libraryClient": "ControlClient", + "rpcs": { + "CreateControl": { + "methods": [ + "CreateControl" + ] + }, + "DeleteControl": { + "methods": [ + "DeleteControl" + ] + }, + "GetControl": { + "methods": [ + "GetControl" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ListControls": { + "methods": [ + "ListControls" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "UpdateControl": { + "methods": [ + "UpdateControl" + ] + } + } } } }, @@ -173,6 +308,26 @@ ] } } + }, + "rest": { + "libraryClient": "PredictionClient", + "rpcs": { + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "Predict": { + "methods": [ + "Predict" + ] + } + } } } }, @@ -247,6 +402,76 @@ ] } } + }, + "rest": { + "libraryClient": "ProductClient", + "rpcs": { + "AddFulfillmentPlaces": { + "methods": [ + "AddFulfillmentPlaces" + ] + }, + "AddLocalInventories": { + "methods": [ + "AddLocalInventories" + ] + }, + "CreateProduct": { + "methods": [ + "CreateProduct" + ] + }, + "DeleteProduct": { + "methods": [ + "DeleteProduct" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "GetProduct": { + "methods": [ + "GetProduct" + ] + }, + "ImportProducts": { + "methods": [ + "ImportProducts" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "ListProducts": { + "methods": [ + "ListProducts" + ] + }, + "RemoveFulfillmentPlaces": { + "methods": [ + "RemoveFulfillmentPlaces" + ] + }, + "RemoveLocalInventories": { + "methods": [ + "RemoveLocalInventories" + ] + }, + "SetInventory": { + "methods": [ + "SetInventory" + ] + }, + "UpdateProduct": { + "methods": [ + "UpdateProduct" + ] + } + } } } }, @@ -271,6 +496,26 @@ ] } } + }, + "rest": { + "libraryClient": "SearchClient", + "rpcs": { + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "Search": { + "methods": [ + "Search" + ] + } + } } } }, @@ -325,6 +570,56 @@ ] } } + }, + "rest": { + "libraryClient": "ServingConfigClient", + "rpcs": { + "AddControl": { + "methods": [ + "AddControl" + ] + }, + "CreateServingConfig": { + "methods": [ + "CreateServingConfig" + ] + }, + "DeleteServingConfig": { + "methods": [ + "DeleteServingConfig" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "GetServingConfig": { + "methods": [ + "GetServingConfig" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "ListServingConfigs": { + "methods": [ + "ListServingConfigs" + ] + }, + "RemoveControl": { + "methods": [ + "RemoveControl" + ] + }, + "UpdateServingConfig": { + "methods": [ + "UpdateServingConfig" + ] + } + } } } }, @@ -369,6 +664,46 @@ ] } } + }, + "rest": { + "libraryClient": "UserEventClient", + "rpcs": { + "CollectUserEvent": { + "methods": [ + "CollectUserEvent" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ImportUserEvents": { + "methods": [ + "ImportUserEvents" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "PurgeUserEvents": { + "methods": [ + "PurgeUserEvents" + ] + }, + "RejoinUserEvents": { + "methods": [ + "RejoinUserEvents" + ] + }, + "WriteUserEvent": { + "methods": [ + "WriteUserEvent" + ] + } + } } } } diff --git a/retail/apiv2/prediction_client.go b/retail/apiv2/prediction_client.go index e85477f6f76a..b64ce67c1ee6 100644 --- a/retail/apiv2/prediction_client.go +++ b/retail/apiv2/prediction_client.go @@ -17,22 +17,28 @@ package retail import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" retailpb "cloud.google.com/go/retail/apiv2/retailpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -87,6 +93,34 @@ func defaultPredictionCallOptions() *PredictionCallOptions { } } +func defaultPredictionRESTCallOptions() *PredictionCallOptions { + return &PredictionCallOptions{ + Predict: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 5000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 300000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + } +} + // internalPredictionClient is an interface that defines the methods available from Retail API. type internalPredictionClient interface { Close() error @@ -231,6 +265,74 @@ func (c *predictionGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type predictionRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing PredictionClient + CallOptions **PredictionCallOptions +} + +// NewPredictionRESTClient creates a new prediction service rest client. +// +// Service for making recommendation prediction. +func NewPredictionRESTClient(ctx context.Context, opts ...option.ClientOption) (*PredictionClient, error) { + clientOpts := append(defaultPredictionRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultPredictionRESTCallOptions() + c := &predictionRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &PredictionClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultPredictionRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://retail.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://retail.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://retail.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *predictionRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *predictionRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *predictionRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *predictionGRPCClient) Predict(ctx context.Context, req *retailpb.PredictRequest, opts ...gax.CallOption) (*retailpb.PredictResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 5000*time.Millisecond) @@ -314,3 +416,216 @@ func (c *predictionGRPCClient) ListOperations(ctx context.Context, req *longrunn return it } + +// Predict makes a recommendation prediction. +func (c *predictionRESTClient) Predict(ctx context.Context, req *retailpb.PredictRequest, opts ...gax.CallOption) (*retailpb.PredictResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:predict", req.GetPlacement()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "placement", url.QueryEscape(req.GetPlacement()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).Predict[0:len((*c.CallOptions).Predict):len((*c.CallOptions).Predict)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &retailpb.PredictResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *predictionRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *predictionRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} diff --git a/retail/apiv2/prediction_client_example_test.go b/retail/apiv2/prediction_client_example_test.go index c633b05d0dfa..757327c4a4e0 100644 --- a/retail/apiv2/prediction_client_example_test.go +++ b/retail/apiv2/prediction_client_example_test.go @@ -42,6 +42,23 @@ func ExampleNewPredictionClient() { _ = c } +func ExampleNewPredictionRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := retail.NewPredictionRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExamplePredictionClient_Predict() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/retail/apiv2/product_client.go b/retail/apiv2/product_client.go index 3481cc099463..0a155317d4f7 100644 --- a/retail/apiv2/product_client.go +++ b/retail/apiv2/product_client.go @@ -17,9 +17,12 @@ package retail import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,14 +30,17 @@ import ( lroauto "cloud.google.com/go/longrunning/autogen" retailpb "cloud.google.com/go/retail/apiv2/retailpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -219,6 +225,144 @@ func defaultProductCallOptions() *ProductCallOptions { } } +func defaultProductRESTCallOptions() *ProductCallOptions { + return &ProductCallOptions{ + CreateProduct: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 30000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + GetProduct: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 30000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + ListProducts: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 30000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + UpdateProduct: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 30000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + DeleteProduct: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 30000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + ImportProducts: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 300000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + SetInventory: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 30000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + AddFulfillmentPlaces: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 30000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + RemoveFulfillmentPlaces: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 30000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + AddLocalInventories: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 30000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + RemoveLocalInventories: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 30000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 300000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + } +} + // internalProductClient is an interface that defines the methods available from Retail API. type internalProductClient interface { Close() error @@ -639,6 +783,90 @@ func (c *productGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type productRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing ProductClient + CallOptions **ProductCallOptions +} + +// NewProductRESTClient creates a new product service rest client. +// +// Service for ingesting Product information +// of the customer’s website. +func NewProductRESTClient(ctx context.Context, opts ...option.ClientOption) (*ProductClient, error) { + clientOpts := append(defaultProductRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultProductRESTCallOptions() + c := &productRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &ProductClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultProductRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://retail.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://retail.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://retail.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *productRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *productRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *productRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *productGRPCClient) CreateProduct(ctx context.Context, req *retailpb.CreateProductRequest, opts ...gax.CallOption) (*retailpb.Product, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) @@ -974,114 +1202,1185 @@ func (c *productGRPCClient) ListOperations(ctx context.Context, req *longrunning return it } -// AddFulfillmentPlacesOperation manages a long-running operation from AddFulfillmentPlaces. -type AddFulfillmentPlacesOperation struct { - lro *longrunning.Operation -} - -// AddFulfillmentPlacesOperation returns a new AddFulfillmentPlacesOperation from a given name. -// The name must be that of a previously created AddFulfillmentPlacesOperation, possibly from a different process. -func (c *productGRPCClient) AddFulfillmentPlacesOperation(name string) *AddFulfillmentPlacesOperation { - return &AddFulfillmentPlacesOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} - -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *AddFulfillmentPlacesOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*retailpb.AddFulfillmentPlacesResponse, error) { - var resp retailpb.AddFulfillmentPlacesResponse - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { +// CreateProduct creates a Product. +func (c *productRESTClient) CreateProduct(ctx context.Context, req *retailpb.CreateProductRequest, opts ...gax.CallOption) (*retailpb.Product, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetProduct() + jsonReq, err := m.Marshal(body) + if err != nil { return nil, err } - return &resp, nil -} -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *AddFulfillmentPlacesOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*retailpb.AddFulfillmentPlacesResponse, error) { - var resp retailpb.AddFulfillmentPlacesResponse - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - if !op.Done() { - return nil, nil - } - return &resp, nil -} + baseUrl.Path += fmt.Sprintf("/v2/%v/products", req.GetParent()) -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *AddFulfillmentPlacesOperation) Metadata() (*retailpb.AddFulfillmentPlacesMetadata, error) { - var meta retailpb.AddFulfillmentPlacesMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { - return nil, err - } - return &meta, nil -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("productId", fmt.Sprintf("%v", req.GetProductId())) -// Done reports whether the long-running operation has completed. -func (op *AddFulfillmentPlacesOperation) Done() bool { - return op.lro.Done() -} + baseUrl.RawQuery = params.Encode() -// 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 *AddFulfillmentPlacesOperation) Name() string { - return op.lro.Name() -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) -// AddLocalInventoriesOperation manages a long-running operation from AddLocalInventories. -type AddLocalInventoriesOperation struct { - lro *longrunning.Operation -} + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateProduct[0:len((*c.CallOptions).CreateProduct):len((*c.CallOptions).CreateProduct)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &retailpb.Product{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers -// AddLocalInventoriesOperation returns a new AddLocalInventoriesOperation from a given name. -// The name must be that of a previously created AddLocalInventoriesOperation, possibly from a different process. -func (c *productGRPCClient) AddLocalInventoriesOperation(name string) *AddLocalInventoriesOperation { - return &AddLocalInventoriesOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *AddLocalInventoriesOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*retailpb.AddLocalInventoriesResponse, error) { - var resp retailpb.AddLocalInventoriesResponse - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { - return nil, err + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e } - return &resp, nil + return resp, nil } -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *AddLocalInventoriesOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*retailpb.AddLocalInventoriesResponse, error) { - var resp retailpb.AddLocalInventoriesResponse - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { +// GetProduct gets a Product. +func (c *productRESTClient) GetProduct(ctx context.Context, req *retailpb.GetProductRequest, opts ...gax.CallOption) (*retailpb.Product, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - if !op.Done() { + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetProduct[0:len((*c.CallOptions).GetProduct):len((*c.CallOptions).GetProduct)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &retailpb.Product{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListProducts gets a list of Products. +func (c *productRESTClient) ListProducts(ctx context.Context, req *retailpb.ListProductsRequest, opts ...gax.CallOption) *ProductIterator { + it := &ProductIterator{} + req = proto.Clone(req).(*retailpb.ListProductsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*retailpb.Product, string, error) { + resp := &retailpb.ListProductsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/products", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + if req.GetReadMask() != nil { + readMask, err := protojson.Marshal(req.GetReadMask()) + if err != nil { + return nil, "", err + } + params.Add("readMask", string(readMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetProducts(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// UpdateProduct updates a Product. +func (c *productRESTClient) UpdateProduct(ctx context.Context, req *retailpb.UpdateProductRequest, opts ...gax.CallOption) (*retailpb.Product, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetProduct() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetProduct().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetAllowMissing() { + params.Add("allowMissing", fmt.Sprintf("%v", req.GetAllowMissing())) + } + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "product.name", url.QueryEscape(req.GetProduct().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateProduct[0:len((*c.CallOptions).UpdateProduct):len((*c.CallOptions).UpdateProduct)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &retailpb.Product{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteProduct deletes a Product. +func (c *productRESTClient) DeleteProduct(ctx context.Context, req *retailpb.DeleteProductRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// ImportProducts bulk import of multiple Products. +// +// Request processing may be synchronous. +// Non-existing items are created. +// +// Note that it is possible for a subset of the +// Products to be successfully updated. +func (c *productRESTClient) ImportProducts(ctx context.Context, req *retailpb.ImportProductsRequest, opts ...gax.CallOption) (*ImportProductsOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/products:import", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &ImportProductsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// SetInventory updates inventory information for a +// Product while respecting the last update +// timestamps of each inventory field. +// +// This process is asynchronous and does not require the +// Product to exist before updating +// fulfillment information. If the request is valid, the update will be +// enqueued and processed downstream. As a consequence, when a response is +// returned, updates are not immediately manifested in the +// Product queried by +// ProductService.GetProduct +// or +// ProductService.ListProducts. +// +// When inventory is updated with +// ProductService.CreateProduct +// and +// ProductService.UpdateProduct, +// the specified inventory field value(s) will overwrite any existing value(s) +// while ignoring the last update time for this field. Furthermore, the last +// update time for the specified inventory fields will be overwritten to the +// time of the +// ProductService.CreateProduct +// or +// ProductService.UpdateProduct +// request. +// +// If no inventory fields are set in +// CreateProductRequest.product, +// then any pre-existing inventory information for this product will be used. +// +// If no inventory fields are set in +// SetInventoryRequest.set_mask, +// then any existing inventory information will be preserved. +// +// Pre-existing inventory information can only be updated with +// ProductService.SetInventory, +// ProductService.AddFulfillmentPlaces, +// and +// ProductService.RemoveFulfillmentPlaces. +// +// The returned Operations will be obsolete after 1 day, and +// GetOperation API will return NOT_FOUND afterwards. +// +// If conflicting updates are issued, the Operations associated with the +// stale updates will not be marked as done until being +// obsolete. +// +// This feature is only available for users who have Retail Search enabled. +// Please enable Retail Search on Cloud Console before using this feature. +func (c *productRESTClient) SetInventory(ctx context.Context, req *retailpb.SetInventoryRequest, opts ...gax.CallOption) (*SetInventoryOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:setInventory", req.GetInventory().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "inventory.name", url.QueryEscape(req.GetInventory().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &SetInventoryOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// AddFulfillmentPlaces incrementally adds place IDs to +// Product.fulfillment_info.place_ids. +// +// This process is asynchronous and does not require the +// Product to exist before updating +// fulfillment information. If the request is valid, the update will be +// enqueued and processed downstream. As a consequence, when a response is +// returned, the added place IDs are not immediately manifested in the +// Product queried by +// ProductService.GetProduct +// or +// ProductService.ListProducts. +// +// The returned Operations will be obsolete after 1 day, and +// GetOperation API will return NOT_FOUND afterwards. +// +// If conflicting updates are issued, the Operations associated with the +// stale updates will not be marked as done until being +// obsolete. +// +// This feature is only available for users who have Retail Search enabled. +// Please enable Retail Search on Cloud Console before using this feature. +func (c *productRESTClient) AddFulfillmentPlaces(ctx context.Context, req *retailpb.AddFulfillmentPlacesRequest, opts ...gax.CallOption) (*AddFulfillmentPlacesOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:addFulfillmentPlaces", req.GetProduct()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "product", url.QueryEscape(req.GetProduct()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &AddFulfillmentPlacesOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// RemoveFulfillmentPlaces incrementally removes place IDs from a +// Product.fulfillment_info.place_ids. +// +// This process is asynchronous and does not require the +// Product to exist before updating +// fulfillment information. If the request is valid, the update will be +// enqueued and processed downstream. As a consequence, when a response is +// returned, the removed place IDs are not immediately manifested in the +// Product queried by +// ProductService.GetProduct +// or +// ProductService.ListProducts. +// +// The returned Operations will be obsolete after 1 day, and +// GetOperation API will return NOT_FOUND afterwards. +// +// If conflicting updates are issued, the Operations associated with the +// stale updates will not be marked as done until being +// obsolete. +// +// This feature is only available for users who have Retail Search enabled. +// Please enable Retail Search on Cloud Console before using this feature. +func (c *productRESTClient) RemoveFulfillmentPlaces(ctx context.Context, req *retailpb.RemoveFulfillmentPlacesRequest, opts ...gax.CallOption) (*RemoveFulfillmentPlacesOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:removeFulfillmentPlaces", req.GetProduct()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "product", url.QueryEscape(req.GetProduct()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &RemoveFulfillmentPlacesOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// AddLocalInventories updates local inventory information for a +// Product at a list of places, while +// respecting the last update timestamps of each inventory field. +// +// This process is asynchronous and does not require the +// Product to exist before updating +// inventory information. If the request is valid, the update will be enqueued +// and processed downstream. As a consequence, when a response is returned, +// updates are not immediately manifested in the +// Product queried by +// ProductService.GetProduct +// or +// ProductService.ListProducts. +// +// Local inventory information can only be modified using this method. +// ProductService.CreateProduct +// and +// ProductService.UpdateProduct +// has no effect on local inventories. +// +// The returned Operations will be obsolete after 1 day, and +// GetOperation API will return NOT_FOUND afterwards. +// +// If conflicting updates are issued, the Operations associated with the +// stale updates will not be marked as done until being +// obsolete. +// +// This feature is only available for users who have Retail Search enabled. +// Please enable Retail Search on Cloud Console before using this feature. +func (c *productRESTClient) AddLocalInventories(ctx context.Context, req *retailpb.AddLocalInventoriesRequest, opts ...gax.CallOption) (*AddLocalInventoriesOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:addLocalInventories", req.GetProduct()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "product", url.QueryEscape(req.GetProduct()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &AddLocalInventoriesOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// RemoveLocalInventories remove local inventory information for a +// Product at a list of places at a removal +// timestamp. +// +// This process is asynchronous. If the request is valid, the removal will be +// enqueued and processed downstream. As a consequence, when a response is +// returned, removals are not immediately manifested in the +// Product queried by +// ProductService.GetProduct +// or +// ProductService.ListProducts. +// +// Local inventory information can only be removed using this method. +// ProductService.CreateProduct +// and +// ProductService.UpdateProduct +// has no effect on local inventories. +// +// The returned Operations will be obsolete after 1 day, and +// GetOperation API will return NOT_FOUND afterwards. +// +// If conflicting updates are issued, the Operations associated with the +// stale updates will not be marked as done until being +// obsolete. +// +// This feature is only available for users who have Retail Search enabled. +// Please enable Retail Search on Cloud Console before using this feature. +func (c *productRESTClient) RemoveLocalInventories(ctx context.Context, req *retailpb.RemoveLocalInventoriesRequest, opts ...gax.CallOption) (*RemoveLocalInventoriesOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:removeLocalInventories", req.GetProduct()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "product", url.QueryEscape(req.GetProduct()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &RemoveLocalInventoriesOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *productRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *productRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// AddFulfillmentPlacesOperation manages a long-running operation from AddFulfillmentPlaces. +type AddFulfillmentPlacesOperation struct { + lro *longrunning.Operation + pollPath string +} + +// AddFulfillmentPlacesOperation returns a new AddFulfillmentPlacesOperation from a given name. +// The name must be that of a previously created AddFulfillmentPlacesOperation, possibly from a different process. +func (c *productGRPCClient) AddFulfillmentPlacesOperation(name string) *AddFulfillmentPlacesOperation { + return &AddFulfillmentPlacesOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// AddFulfillmentPlacesOperation returns a new AddFulfillmentPlacesOperation from a given name. +// The name must be that of a previously created AddFulfillmentPlacesOperation, possibly from a different process. +func (c *productRESTClient) AddFulfillmentPlacesOperation(name string) *AddFulfillmentPlacesOperation { + override := fmt.Sprintf("/v2/%s", name) + return &AddFulfillmentPlacesOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *AddFulfillmentPlacesOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*retailpb.AddFulfillmentPlacesResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp retailpb.AddFulfillmentPlacesResponse + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *AddFulfillmentPlacesOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*retailpb.AddFulfillmentPlacesResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp retailpb.AddFulfillmentPlacesResponse + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *AddFulfillmentPlacesOperation) Metadata() (*retailpb.AddFulfillmentPlacesMetadata, error) { + var meta retailpb.AddFulfillmentPlacesMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *AddFulfillmentPlacesOperation) Done() bool { + return op.lro.Done() +} + +// 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 *AddFulfillmentPlacesOperation) Name() string { + return op.lro.Name() +} + +// AddLocalInventoriesOperation manages a long-running operation from AddLocalInventories. +type AddLocalInventoriesOperation struct { + lro *longrunning.Operation + pollPath string +} + +// AddLocalInventoriesOperation returns a new AddLocalInventoriesOperation from a given name. +// The name must be that of a previously created AddLocalInventoriesOperation, possibly from a different process. +func (c *productGRPCClient) AddLocalInventoriesOperation(name string) *AddLocalInventoriesOperation { + return &AddLocalInventoriesOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// AddLocalInventoriesOperation returns a new AddLocalInventoriesOperation from a given name. +// The name must be that of a previously created AddLocalInventoriesOperation, possibly from a different process. +func (c *productRESTClient) AddLocalInventoriesOperation(name string) *AddLocalInventoriesOperation { + override := fmt.Sprintf("/v2/%s", name) + return &AddLocalInventoriesOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *AddLocalInventoriesOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*retailpb.AddLocalInventoriesResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp retailpb.AddLocalInventoriesResponse + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *AddLocalInventoriesOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*retailpb.AddLocalInventoriesResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp retailpb.AddLocalInventoriesResponse + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { return nil, nil } return &resp, nil @@ -1114,7 +2413,8 @@ func (op *AddLocalInventoriesOperation) Name() string { // ImportProductsOperation manages a long-running operation from ImportProducts. type ImportProductsOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // ImportProductsOperation returns a new ImportProductsOperation from a given name. @@ -1125,10 +2425,21 @@ func (c *productGRPCClient) ImportProductsOperation(name string) *ImportProducts } } +// ImportProductsOperation returns a new ImportProductsOperation from a given name. +// The name must be that of a previously created ImportProductsOperation, possibly from a different process. +func (c *productRESTClient) ImportProductsOperation(name string) *ImportProductsOperation { + override := fmt.Sprintf("/v2/%s", name) + return &ImportProductsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *ImportProductsOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*retailpb.ImportProductsResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp retailpb.ImportProductsResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1146,6 +2457,7 @@ func (op *ImportProductsOperation) Wait(ctx context.Context, opts ...gax.CallOpt // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *ImportProductsOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*retailpb.ImportProductsResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp retailpb.ImportProductsResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1183,7 +2495,8 @@ func (op *ImportProductsOperation) Name() string { // RemoveFulfillmentPlacesOperation manages a long-running operation from RemoveFulfillmentPlaces. type RemoveFulfillmentPlacesOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // RemoveFulfillmentPlacesOperation returns a new RemoveFulfillmentPlacesOperation from a given name. @@ -1194,10 +2507,21 @@ func (c *productGRPCClient) RemoveFulfillmentPlacesOperation(name string) *Remov } } +// RemoveFulfillmentPlacesOperation returns a new RemoveFulfillmentPlacesOperation from a given name. +// The name must be that of a previously created RemoveFulfillmentPlacesOperation, possibly from a different process. +func (c *productRESTClient) RemoveFulfillmentPlacesOperation(name string) *RemoveFulfillmentPlacesOperation { + override := fmt.Sprintf("/v2/%s", name) + return &RemoveFulfillmentPlacesOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *RemoveFulfillmentPlacesOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*retailpb.RemoveFulfillmentPlacesResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp retailpb.RemoveFulfillmentPlacesResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1215,6 +2539,7 @@ func (op *RemoveFulfillmentPlacesOperation) Wait(ctx context.Context, opts ...ga // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *RemoveFulfillmentPlacesOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*retailpb.RemoveFulfillmentPlacesResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp retailpb.RemoveFulfillmentPlacesResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1252,7 +2577,8 @@ func (op *RemoveFulfillmentPlacesOperation) Name() string { // RemoveLocalInventoriesOperation manages a long-running operation from RemoveLocalInventories. type RemoveLocalInventoriesOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // RemoveLocalInventoriesOperation returns a new RemoveLocalInventoriesOperation from a given name. @@ -1263,10 +2589,21 @@ func (c *productGRPCClient) RemoveLocalInventoriesOperation(name string) *Remove } } +// RemoveLocalInventoriesOperation returns a new RemoveLocalInventoriesOperation from a given name. +// The name must be that of a previously created RemoveLocalInventoriesOperation, possibly from a different process. +func (c *productRESTClient) RemoveLocalInventoriesOperation(name string) *RemoveLocalInventoriesOperation { + override := fmt.Sprintf("/v2/%s", name) + return &RemoveLocalInventoriesOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *RemoveLocalInventoriesOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*retailpb.RemoveLocalInventoriesResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp retailpb.RemoveLocalInventoriesResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1284,6 +2621,7 @@ func (op *RemoveLocalInventoriesOperation) Wait(ctx context.Context, opts ...gax // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *RemoveLocalInventoriesOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*retailpb.RemoveLocalInventoriesResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp retailpb.RemoveLocalInventoriesResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1321,7 +2659,8 @@ func (op *RemoveLocalInventoriesOperation) Name() string { // SetInventoryOperation manages a long-running operation from SetInventory. type SetInventoryOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // SetInventoryOperation returns a new SetInventoryOperation from a given name. @@ -1332,10 +2671,21 @@ func (c *productGRPCClient) SetInventoryOperation(name string) *SetInventoryOper } } +// SetInventoryOperation returns a new SetInventoryOperation from a given name. +// The name must be that of a previously created SetInventoryOperation, possibly from a different process. +func (c *productRESTClient) SetInventoryOperation(name string) *SetInventoryOperation { + override := fmt.Sprintf("/v2/%s", name) + return &SetInventoryOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *SetInventoryOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*retailpb.SetInventoryResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp retailpb.SetInventoryResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1353,6 +2703,7 @@ func (op *SetInventoryOperation) Wait(ctx context.Context, opts ...gax.CallOptio // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *SetInventoryOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*retailpb.SetInventoryResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp retailpb.SetInventoryResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/retail/apiv2/product_client_example_test.go b/retail/apiv2/product_client_example_test.go index 9ef041150575..6f0c4bffa11a 100644 --- a/retail/apiv2/product_client_example_test.go +++ b/retail/apiv2/product_client_example_test.go @@ -42,6 +42,23 @@ func ExampleNewProductClient() { _ = c } +func ExampleNewProductRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := retail.NewProductRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleProductClient_CreateProduct() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/retail/apiv2/retailpb/catalog.pb.go b/retail/apiv2/retailpb/catalog.pb.go index 5d4cecf6eecd..89d4583755c5 100644 --- a/retail/apiv2/retailpb/catalog.pb.go +++ b/retail/apiv2/retailpb/catalog.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/retail/v2/catalog.proto package retailpb @@ -266,17 +266,16 @@ type ProductLevelConfig struct { // // * `primary` (default): You can ingest // [Product][google.cloud.retail.v2.Product]s of all types. When - // - // ingesting a [Product][google.cloud.retail.v2.Product], its type will - // default to - // [Product.Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] if - // unset. - // - `variant` (incompatible with Retail Search): You can only - // ingest - // [Product.Type.VARIANT][google.cloud.retail.v2.Product.Type.VARIANT] - // [Product][google.cloud.retail.v2.Product]s. This means - // [Product.primary_product_id][google.cloud.retail.v2.Product.primary_product_id] - // cannot be empty. + // ingesting a [Product][google.cloud.retail.v2.Product], its type will + // default to + // [Product.Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] if + // unset. + // * `variant` (incompatible with Retail Search): You can only + // ingest + // [Product.Type.VARIANT][google.cloud.retail.v2.Product.Type.VARIANT] + // [Product][google.cloud.retail.v2.Product]s. This means + // [Product.primary_product_id][google.cloud.retail.v2.Product.primary_product_id] + // cannot be empty. // // If this field is set to an invalid value other than these, an // INVALID_ARGUMENT error is returned. @@ -294,10 +293,10 @@ type ProductLevelConfig struct { // imported as [Product.id][google.cloud.retail.v2.Product.id]. Acceptable // values are: // - // - `offerId` (default): Import `offerId` as the product ID. - // - `itemGroupId`: Import `itemGroupId` as the product ID. Notice that Retail - // API will choose one item from the ones with the same `itemGroupId`, and - // use it to represent the item group. + // * `offerId` (default): Import `offerId` as the product ID. + // * `itemGroupId`: Import `itemGroupId` as the product ID. Notice that Retail + // API will choose one item from the ones with the same `itemGroupId`, and + // use it to represent the item group. // // If this field is set to an invalid value other than these, an // INVALID_ARGUMENT error is returned. diff --git a/retail/apiv2/retailpb/catalog_service.pb.go b/retail/apiv2/retailpb/catalog_service.pb.go index 6884004f23b6..cd18d02d864a 100644 --- a/retail/apiv2/retailpb/catalog_service.pb.go +++ b/retail/apiv2/retailpb/catalog_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/retail/v2/catalog_service.proto package retailpb @@ -1552,11 +1552,11 @@ type CatalogServiceClient interface { // // More specifically: // - // - PredictionService will only return product IDs from branch {newBranch}. - // - SearchService will only return product IDs from branch {newBranch} - // (if branch is not explicitly set). - // - UserEventService will only join events with products from branch - // {newBranch}. + // * PredictionService will only return product IDs from branch {newBranch}. + // * SearchService will only return product IDs from branch {newBranch} + // (if branch is not explicitly set). + // * UserEventService will only join events with products from branch + // {newBranch}. SetDefaultBranch(ctx context.Context, in *SetDefaultBranchRequest, opts ...grpc.CallOption) (*emptypb.Empty, error) // Get which branch is currently default branch set by // [CatalogService.SetDefaultBranch][google.cloud.retail.v2.CatalogService.SetDefaultBranch] @@ -1744,11 +1744,11 @@ type CatalogServiceServer interface { // // More specifically: // - // - PredictionService will only return product IDs from branch {newBranch}. - // - SearchService will only return product IDs from branch {newBranch} - // (if branch is not explicitly set). - // - UserEventService will only join events with products from branch - // {newBranch}. + // * PredictionService will only return product IDs from branch {newBranch}. + // * SearchService will only return product IDs from branch {newBranch} + // (if branch is not explicitly set). + // * UserEventService will only join events with products from branch + // {newBranch}. SetDefaultBranch(context.Context, *SetDefaultBranchRequest) (*emptypb.Empty, error) // Get which branch is currently default branch set by // [CatalogService.SetDefaultBranch][google.cloud.retail.v2.CatalogService.SetDefaultBranch] diff --git a/retail/apiv2/retailpb/common.pb.go b/retail/apiv2/retailpb/common.pb.go index 806fdda439c4..9065f59d454e 100644 --- a/retail/apiv2/retailpb/common.pb.go +++ b/retail/apiv2/retailpb/common.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/retail/v2/common.proto package retailpb @@ -282,7 +282,6 @@ type Rule struct { // An action must be provided. // // Types that are assignable to Action: - // // *Rule_BoostAction_ // *Rule_RedirectAction_ // *Rule_OnewaySynonymsAction_ @@ -928,7 +927,6 @@ type Interval struct { // Otherwise, an INVALID_ARGUMENT error is returned. // // Types that are assignable to Min: - // // *Interval_Minimum // *Interval_ExclusiveMinimum Min isInterval_Min `protobuf_oneof:"min"` @@ -939,7 +937,6 @@ type Interval struct { // Otherwise, an INVALID_ARGUMENT error is returned. // // Types that are assignable to Max: - // // *Interval_Maximum // *Interval_ExclusiveMaximum Max isInterval_Max `protobuf_oneof:"max"` @@ -1437,18 +1434,18 @@ type LocalInventory struct { // This field needs to pass all below criteria, otherwise an INVALID_ARGUMENT // error is returned: // - // - At most 30 attributes are allowed. - // - The key must be a UTF-8 encoded string with a length limit of 32 - // characters. - // - The key must match the pattern: `[a-zA-Z0-9][a-zA-Z0-9_]*`. For example, - // key0LikeThis or KEY_1_LIKE_THIS. - // - The attribute values must be of the same type (text or number). - // - Only 1 value is allowed for each attribute. - // - For text values, the length limit is 256 UTF-8 characters. - // - The attribute does not support search. The `searchable` field should be - // unset or set to false. - // - The max summed total bytes of custom attribute keys and values per - // product is 5MiB. + // * At most 30 attributes are allowed. + // * The key must be a UTF-8 encoded string with a length limit of 32 + // characters. + // * The key must match the pattern: `[a-zA-Z0-9][a-zA-Z0-9_]*`. For example, + // key0LikeThis or KEY_1_LIKE_THIS. + // * The attribute values must be of the same type (text or number). + // * Only 1 value is allowed for each attribute. + // * For text values, the length limit is 256 UTF-8 characters. + // * The attribute does not support search. The `searchable` field should be + // unset or set to false. + // * The max summed total bytes of custom attribute keys and values per + // product is 5MiB. Attributes map[string]*CustomAttribute `protobuf:"bytes,3,rep,name=attributes,proto3" json:"attributes,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` // Input only. Supported fulfillment types. Valid fulfillment type values // include commonly used types (such as pickup in store and same day @@ -1691,11 +1688,10 @@ type Rule_BoostAction struct { // // * To boost products with product ID "product_1" or "product_2", and // color - // - // "Red" or "Blue":
- // *(id: ANY("product_1", "product_2"))
* - // *AND
* - // *(colorFamilies: ANY("Red", "Blue"))
* + // "Red" or "Blue":
+ // *(id: ANY("product_1", "product_2"))
* + // *AND
* + // *(colorFamilies: ANY("Red", "Blue"))
* ProductsFilter string `protobuf:"bytes,2,opt,name=products_filter,json=productsFilter,proto3" json:"products_filter,omitempty"` } @@ -1771,17 +1767,14 @@ type Rule_FilterAction struct { // * Filter syntax is identical to // [SearchRequest.filter][google.cloud.retail.v2.SearchRequest.filter]. See // more - // - // details at the Retail Search - // [user guide](/retail/search/docs/filter-and-order#filter). - // + // details at the Retail Search + // [user guide](/retail/search/docs/filter-and-order#filter). // * To filter products with product ID "product_1" or "product_2", and // color - // - // "Red" or "Blue":
- // *(id: ANY("product_1", "product_2"))
* - // *AND
* - // *(colorFamilies: ANY("Red", "Blue"))
* + // "Red" or "Blue":
+ // *(id: ANY("product_1", "product_2"))
* + // *AND
* + // *(colorFamilies: ANY("Red", "Blue"))
* Filter string `protobuf:"bytes,1,opt,name=filter,proto3" json:"filter,omitempty"` } diff --git a/retail/apiv2/retailpb/completion_service.pb.go b/retail/apiv2/retailpb/completion_service.pb.go index a5e7a1b0e9a0..95e6bec6a505 100644 --- a/retail/apiv2/retailpb/completion_service.pb.go +++ b/retail/apiv2/retailpb/completion_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/retail/v2/completion_service.proto package retailpb @@ -99,9 +99,9 @@ type CompleteQueryRequest struct { // // * user-data // - // - cloud-retail: - // This option requires enabling auto-learning function first. See - // [guidelines](https://cloud.google.com/retail/docs/completion-overview#generated-completion-dataset). + // * cloud-retail: + // This option requires enabling auto-learning function first. See + // [guidelines](https://cloud.google.com/retail/docs/completion-overview#generated-completion-dataset). Dataset string `protobuf:"bytes,6,opt,name=dataset,proto3" json:"dataset,omitempty"` // Completion max suggestions. If left unset or set to 0, then will fallback // to the configured value @@ -216,15 +216,15 @@ type CompleteQueryResponse struct { // field is set and [UserEvent][google.cloud.retail.v2.UserEvent] is imported. // The recent searches satisfy the follow rules: // - // - They are ordered from latest to oldest. + // * They are ordered from latest to oldest. // - // - They are matched with - // [CompleteQueryRequest.query][google.cloud.retail.v2.CompleteQueryRequest.query] - // case insensitively. + // * They are matched with + // [CompleteQueryRequest.query][google.cloud.retail.v2.CompleteQueryRequest.query] + // case insensitively. // - // - They are transformed to lower case. + // * They are transformed to lower case. // - // - They are UTF-8 safe. + // * They are UTF-8 safe. // // Recent searches are deduplicated. More recent searches will be reserved // when duplication happens. diff --git a/retail/apiv2/retailpb/control.pb.go b/retail/apiv2/retailpb/control.pb.go index b1b904976d0a..e356eb730a60 100644 --- a/retail/apiv2/retailpb/control.pb.go +++ b/retail/apiv2/retailpb/control.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/retail/v2/control.proto package retailpb @@ -51,7 +51,6 @@ type Control struct { // INVALID_ARGUMENT will be returned if either condition is violated. // // Types that are assignable to Control: - // // *Control_Rule Control isControl_Control `protobuf_oneof:"control"` // Immutable. Fully qualified name diff --git a/retail/apiv2/retailpb/control_service.pb.go b/retail/apiv2/retailpb/control_service.pb.go index 691207488d08..8844d0bbd5fd 100644 --- a/retail/apiv2/retailpb/control_service.pb.go +++ b/retail/apiv2/retailpb/control_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/retail/v2/control_service.proto package retailpb @@ -297,7 +297,7 @@ type ListControlsRequest struct { // // * List all the products under the parent branch if // [filter][google.cloud.retail.v2.ListControlsRequest.filter] is unset. - // - List controls that are used in a single ServingConfig: + // * List controls that are used in a single ServingConfig: // 'serving_config = "boosted_home_page_cvr"' Filter string `protobuf:"bytes,4,opt,name=filter,proto3" json:"filter,omitempty"` } diff --git a/retail/apiv2/retailpb/import_config.pb.go b/retail/apiv2/retailpb/import_config.pb.go index 8b0105113079..573345fc5967 100644 --- a/retail/apiv2/retailpb/import_config.pb.go +++ b/retail/apiv2/retailpb/import_config.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/retail/v2/import_config.proto package retailpb @@ -116,17 +116,16 @@ type GcsSource struct { // // * `product` (default): One JSON [Product][google.cloud.retail.v2.Product] // per line. Each product must - // - // have a valid [Product.id][google.cloud.retail.v2.Product.id]. - // - `product_merchant_center`: See [Importing catalog data from Merchant - // Center](https://cloud.google.com/retail/recommendations-ai/docs/upload-catalog#mc). + // have a valid [Product.id][google.cloud.retail.v2.Product.id]. + // * `product_merchant_center`: See [Importing catalog data from Merchant + // Center](https://cloud.google.com/retail/recommendations-ai/docs/upload-catalog#mc). // // Supported values for user events imports: // // * `user_event` (default): One JSON // [UserEvent][google.cloud.retail.v2.UserEvent] per line. - // - `user_event_ga360`: Using - // https://support.google.com/analytics/answer/3437719. + // * `user_event_ga360`: Using + // https://support.google.com/analytics/answer/3437719. // // Supported values for control imports: // @@ -196,7 +195,6 @@ type BigQuerySource struct { // is not partitioned. // // Types that are assignable to Partition: - // // *BigQuerySource_PartitionDate Partition isBigQuerySource_Partition `protobuf_oneof:"partition"` // The project ID (can be project # or ID) that the BigQuery source is in with @@ -219,21 +217,20 @@ type BigQuerySource struct { // // * `product` (default): One JSON [Product][google.cloud.retail.v2.Product] // per line. Each product must - // - // have a valid [Product.id][google.cloud.retail.v2.Product.id]. - // - `product_merchant_center`: See [Importing catalog data from Merchant - // Center](https://cloud.google.com/retail/recommendations-ai/docs/upload-catalog#mc). + // have a valid [Product.id][google.cloud.retail.v2.Product.id]. + // * `product_merchant_center`: See [Importing catalog data from Merchant + // Center](https://cloud.google.com/retail/recommendations-ai/docs/upload-catalog#mc). // // Supported values for user events imports: // // * `user_event` (default): One JSON // [UserEvent][google.cloud.retail.v2.UserEvent] per line. - // - `user_event_ga360`: - // The schema is available here: - // https://support.google.com/analytics/answer/3437719. - // - `user_event_ga4`: - // The schema is available here: - // https://support.google.com/analytics/answer/7029846. + // * `user_event_ga360`: + // The schema is available here: + // https://support.google.com/analytics/answer/3437719. + // * `user_event_ga4`: + // The schema is available here: + // https://support.google.com/analytics/answer/7029846. // // Supported values for auto-completion imports: // @@ -447,7 +444,6 @@ type ImportErrorsConfig struct { // Required. Errors destination. // // Types that are assignable to Destination: - // // *ImportErrorsConfig_GcsPrefix Destination isImportErrorsConfig_Destination `protobuf_oneof:"destination"` } @@ -785,7 +781,6 @@ type ProductInputConfig struct { // Required. The source of the input. // // Types that are assignable to Source: - // // *ProductInputConfig_ProductInlineSource // *ProductInputConfig_GcsSource // *ProductInputConfig_BigQuerySource @@ -886,7 +881,6 @@ type UserEventInputConfig struct { // The source of the input. // // Types that are assignable to Source: - // // *UserEventInputConfig_UserEventInlineSource // *UserEventInputConfig_GcsSource // *UserEventInputConfig_BigQuerySource @@ -995,7 +989,6 @@ type CompletionDataInputConfig struct { // * `allowlist`: One JSON allow suggestion per line. // // Types that are assignable to Source: - // // *CompletionDataInputConfig_BigQuerySource Source isCompletionDataInputConfig_Source `protobuf_oneof:"source"` } diff --git a/retail/apiv2/retailpb/prediction_service.pb.go b/retail/apiv2/retailpb/prediction_service.pb.go index 2e23407d26d9..9c5169d5e16c 100644 --- a/retail/apiv2/retailpb/prediction_service.pb.go +++ b/retail/apiv2/retailpb/prediction_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/retail/v2/prediction_service.proto package retailpb @@ -89,25 +89,25 @@ type PredictRequest struct { // Filter for restricting prediction results with a length limit of 5,000 // characters. Accepts values for tags and the `filterOutOfStockItems` flag. // - // - Tag expressions. Restricts predictions to products that match all of the - // specified tags. Boolean operators `OR` and `NOT` are supported if the - // expression is enclosed in parentheses, and must be separated from the - // tag values by a space. `-"tagA"` is also supported and is equivalent to - // `NOT "tagA"`. Tag values must be double quoted UTF-8 encoded strings - // with a size limit of 1,000 characters. + // * Tag expressions. Restricts predictions to products that match all of the + // specified tags. Boolean operators `OR` and `NOT` are supported if the + // expression is enclosed in parentheses, and must be separated from the + // tag values by a space. `-"tagA"` is also supported and is equivalent to + // `NOT "tagA"`. Tag values must be double quoted UTF-8 encoded strings + // with a size limit of 1,000 characters. // - // Note: "Recently viewed" models don't support tag filtering at the - // moment. + // Note: "Recently viewed" models don't support tag filtering at the + // moment. // - // - filterOutOfStockItems. Restricts predictions to products that do not - // have a - // stockState value of OUT_OF_STOCK. + // * filterOutOfStockItems. Restricts predictions to products that do not + // have a + // stockState value of OUT_OF_STOCK. // // Examples: // - // - tag=("Red" OR "Blue") tag="New-Arrival" tag=(NOT "promotional") - // - filterOutOfStockItems tag=(-"promotional") - // - filterOutOfStockItems + // * tag=("Red" OR "Blue") tag="New-Arrival" tag=(NOT "promotional") + // * filterOutOfStockItems tag=(-"promotional") + // * filterOutOfStockItems // // If your filter blocks all prediction results, the API will return generic // (unfiltered) popular products. If you only want results strictly matching @@ -120,9 +120,9 @@ type PredictRequest struct { // attribute-based expressions are expected instead of the above described // tag-based syntax. Examples: // - // - (colors: ANY("Red", "Blue")) AND NOT (categories: ANY("Phones")) - // - (availability: ANY("IN_STOCK")) AND - // (colors: ANY("Red") OR categories: ANY("Phones")) + // * (colors: ANY("Red", "Blue")) AND NOT (categories: ANY("Phones")) + // * (availability: ANY("IN_STOCK")) AND + // (colors: ANY("Red") OR categories: ANY("Phones")) Filter string `protobuf:"bytes,5,opt,name=filter,proto3" json:"filter,omitempty"` // Use validate only mode for this prediction query. If set to true, a // dummy model will be used that returns arbitrary products. @@ -133,43 +133,43 @@ type PredictRequest struct { // // Allowed values: // - // - `returnProduct`: Boolean. If set to true, the associated product - // object will be returned in the `results.metadata` field in the - // prediction response. - // - `returnScore`: Boolean. If set to true, the prediction 'score' - // corresponding to each returned product will be set in the - // `results.metadata` field in the prediction response. The given - // 'score' indicates the probability of an product being clicked/purchased - // given the user's context and history. - // - `strictFiltering`: Boolean. True by default. If set to false, the service - // will return generic (unfiltered) popular products instead of empty if - // your filter blocks all prediction results. - // - `priceRerankLevel`: String. Default empty. If set to be non-empty, then - // it needs to be one of {'no-price-reranking', 'low-price-reranking', - // 'medium-price-reranking', 'high-price-reranking'}. This gives - // request-level control and adjusts prediction results based on product - // price. - // - `diversityLevel`: String. Default empty. If set to be non-empty, then - // it needs to be one of {'no-diversity', 'low-diversity', - // 'medium-diversity', 'high-diversity', 'auto-diversity'}. This gives - // request-level control and adjusts prediction results based on product - // category. - // - `filterSyntaxV2`: Boolean. False by default. If set to true, the `filter` - // field is interpreteted according to the new, attribute-based syntax. + // * `returnProduct`: Boolean. If set to true, the associated product + // object will be returned in the `results.metadata` field in the + // prediction response. + // * `returnScore`: Boolean. If set to true, the prediction 'score' + // corresponding to each returned product will be set in the + // `results.metadata` field in the prediction response. The given + // 'score' indicates the probability of an product being clicked/purchased + // given the user's context and history. + // * `strictFiltering`: Boolean. True by default. If set to false, the service + // will return generic (unfiltered) popular products instead of empty if + // your filter blocks all prediction results. + // * `priceRerankLevel`: String. Default empty. If set to be non-empty, then + // it needs to be one of {'no-price-reranking', 'low-price-reranking', + // 'medium-price-reranking', 'high-price-reranking'}. This gives + // request-level control and adjusts prediction results based on product + // price. + // * `diversityLevel`: String. Default empty. If set to be non-empty, then + // it needs to be one of {'no-diversity', 'low-diversity', + // 'medium-diversity', 'high-diversity', 'auto-diversity'}. This gives + // request-level control and adjusts prediction results based on product + // category. + // * `filterSyntaxV2`: Boolean. False by default. If set to true, the `filter` + // field is interpreteted according to the new, attribute-based syntax. Params map[string]*structpb.Value `protobuf:"bytes,7,rep,name=params,proto3" json:"params,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` // The labels applied to a resource must meet the following requirements: // - // - Each resource can have multiple labels, up to a maximum of 64. - // - Each label must be a key-value pair. - // - Keys have a minimum length of 1 character and a maximum length of 63 - // characters and cannot be empty. Values can be empty and have a maximum - // length of 63 characters. - // - Keys and values can contain only lowercase letters, numeric characters, - // underscores, and dashes. All characters must use UTF-8 encoding, and - // international characters are allowed. - // - The key portion of a label must be unique. However, you can use the same - // key with multiple resources. - // - Keys must start with a lowercase letter or international character. + // * Each resource can have multiple labels, up to a maximum of 64. + // * Each label must be a key-value pair. + // * Keys have a minimum length of 1 character and a maximum length of 63 + // characters and cannot be empty. Values can be empty and have a maximum + // length of 63 characters. + // * Keys and values can contain only lowercase letters, numeric characters, + // underscores, and dashes. All characters must use UTF-8 encoding, and + // international characters are allowed. + // * The key portion of a label must be unique. However, you can use the same + // key with multiple resources. + // * Keys must start with a lowercase letter or international character. // // See [Google Cloud // Document](https://cloud.google.com/resource-manager/docs/creating-managing-labels#requirements) @@ -358,10 +358,10 @@ type PredictResponse_PredictionResult struct { // // Possible values: // - // - `product`: JSON representation of the product. Is set if - // `returnProduct` is set to true in `PredictRequest.params`. - // - `score`: Prediction score in double value. Is set if - // `returnScore` is set to true in `PredictRequest.params`. + // * `product`: JSON representation of the product. Is set if + // `returnProduct` is set to true in `PredictRequest.params`. + // * `score`: Prediction score in double value. Is set if + // `returnScore` is set to true in `PredictRequest.params`. Metadata map[string]*structpb.Value `protobuf:"bytes,2,rep,name=metadata,proto3" json:"metadata,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` } diff --git a/retail/apiv2/retailpb/product.pb.go b/retail/apiv2/retailpb/product.pb.go index 68c2c36c80ef..8222c2bdc756 100644 --- a/retail/apiv2/retailpb/product.pb.go +++ b/retail/apiv2/retailpb/product.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/retail/v2/product.proto package retailpb @@ -189,7 +189,6 @@ type Product struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Expiration: - // // *Product_ExpireTime // *Product_Ttl Expiration isProduct_Expiration `protobuf_oneof:"expiration"` @@ -267,6 +266,7 @@ type Product struct { // belonging to several parallel categories. Strongly recommended using the // full path for better search / recommendation quality. // + // // To represent full path of category, use '>' sign to separate different // hierarchies. If '>' is part of the category name, please replace it with // other character(s). @@ -276,10 +276,10 @@ type Product struct { // ["Sports & Fitness" -> "Athletic Clothing" -> "Shoes"], it could be // represented as: // - // "categories": [ - // "Shoes & Accessories > Shoes", - // "Sports & Fitness > Athletic Clothing > Shoes" - // ] + // "categories": [ + // "Shoes & Accessories > Shoes", + // "Sports & Fitness > Athletic Clothing > Shoes" + // ] // // Must be set for [Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] // [Product][google.cloud.retail.v2.Product] otherwise an INVALID_ARGUMENT @@ -355,16 +355,16 @@ type Product struct { // This field needs to pass all below criteria, otherwise an INVALID_ARGUMENT // error is returned: // - // - Max entries count: 200. - // - The key must be a UTF-8 encoded string with a length limit of 128 - // characters. - // - For indexable attribute, the key must match the pattern: - // `[a-zA-Z0-9][a-zA-Z0-9_]*`. For example, `key0LikeThis` or - // `KEY_1_LIKE_THIS`. - // - For text attributes, at most 400 values are allowed. Empty values are not - // allowed. Each value must be a non-empty UTF-8 encoded string with a - // length limit of 256 characters. - // - For number attributes, at most 400 values are allowed. + // * Max entries count: 200. + // * The key must be a UTF-8 encoded string with a length limit of 128 + // characters. + // * For indexable attribute, the key must match the pattern: + // `[a-zA-Z0-9][a-zA-Z0-9_]*`. For example, `key0LikeThis` or + // `KEY_1_LIKE_THIS`. + // * For text attributes, at most 400 values are allowed. Empty values are not + // allowed. Each value must be a non-empty UTF-8 encoded string with a + // length limit of 256 characters. + // * For number attributes, at most 400 values are allowed. Attributes map[string]*CustomAttribute `protobuf:"bytes,12,rep,name=attributes,proto3" json:"attributes,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` // Custom tags associated with the product. // diff --git a/retail/apiv2/retailpb/product_service.pb.go b/retail/apiv2/retailpb/product_service.pb.go index 16c697a44750..c87fa973a52a 100644 --- a/retail/apiv2/retailpb/product_service.pb.go +++ b/retail/apiv2/retailpb/product_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/retail/v2/product_service.proto package retailpb @@ -390,24 +390,19 @@ type ListProductsRequest struct { // [filter][google.cloud.retail.v2.ListProductsRequest.filter] is unset. // * List [Product.Type.VARIANT][google.cloud.retail.v2.Product.Type.VARIANT] // [Product][google.cloud.retail.v2.Product]s sharing the same - // - // [Product.Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] - // [Product][google.cloud.retail.v2.Product]. For example: - // `primary_product_id = "some_product_id"` - // + // [Product.Type.PRIMARY][google.cloud.retail.v2.Product.Type.PRIMARY] + // [Product][google.cloud.retail.v2.Product]. For example: + // `primary_product_id = "some_product_id"` // * List [Product][google.cloud.retail.v2.Product]s bundled in a // [Product.Type.COLLECTION][google.cloud.retail.v2.Product.Type.COLLECTION] // [Product][google.cloud.retail.v2.Product]. - // - // For example: - // `collection_product_id = "some_product_id"` - // + // For example: + // `collection_product_id = "some_product_id"` // * List [Product][google.cloud.retail.v2.Product]s with a partibular type. // For example: - // - // `type = "PRIMARY"` - // `type = "VARIANT"` - // `type = "COLLECTION"` + // `type = "PRIMARY"` + // `type = "VARIANT"` + // `type = "COLLECTION"` // // If the field is unrecognizable, an INVALID_ARGUMENT error is returned. // diff --git a/retail/apiv2/retailpb/promotion.pb.go b/retail/apiv2/retailpb/promotion.pb.go index bdbc3335f7ec..af5f4587449e 100644 --- a/retail/apiv2/retailpb/promotion.pb.go +++ b/retail/apiv2/retailpb/promotion.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/retail/v2/promotion.proto package retailpb diff --git a/retail/apiv2/retailpb/purge_config.pb.go b/retail/apiv2/retailpb/purge_config.pb.go index 53585e55e004..995a13a4f9cd 100644 --- a/retail/apiv2/retailpb/purge_config.pb.go +++ b/retail/apiv2/retailpb/purge_config.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/retail/v2/purge_config.proto package retailpb @@ -92,21 +92,21 @@ type PurgeUserEventsRequest struct { // // * `eventType`: Double quoted // [UserEvent.event_type][google.cloud.retail.v2.UserEvent.event_type] string. - // - `eventTime`: in ISO 8601 "zulu" format. - // - `visitorId`: Double quoted string. Specifying this will delete all - // events associated with a visitor. - // - `userId`: Double quoted string. Specifying this will delete all events - // associated with a user. + // * `eventTime`: in ISO 8601 "zulu" format. + // * `visitorId`: Double quoted string. Specifying this will delete all + // events associated with a visitor. + // * `userId`: Double quoted string. Specifying this will delete all events + // associated with a user. // // Examples: // - // - Deleting all events in a time range: - // `eventTime > "2012-04-23T18:25:43.511Z" - // eventTime < "2012-04-23T18:30:43.511Z"` - // - Deleting specific eventType in time range: - // `eventTime > "2012-04-23T18:25:43.511Z" eventType = "detail-page-view"` - // - Deleting all events for a specific visitor: - // `visitorId = "visitor1024"` + // * Deleting all events in a time range: + // `eventTime > "2012-04-23T18:25:43.511Z" + // eventTime < "2012-04-23T18:30:43.511Z"` + // * Deleting specific eventType in time range: + // `eventTime > "2012-04-23T18:25:43.511Z" eventType = "detail-page-view"` + // * Deleting all events for a specific visitor: + // `visitorId = "visitor1024"` // // The filtering fields are assumed to have an implicit AND. Filter string `protobuf:"bytes,2,opt,name=filter,proto3" json:"filter,omitempty"` diff --git a/retail/apiv2/retailpb/search_service.pb.go b/retail/apiv2/retailpb/search_service.pb.go index b8bc11a85b9c..a60c2b8ed863 100644 --- a/retail/apiv2/retailpb/search_service.pb.go +++ b/retail/apiv2/retailpb/search_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/retail/v2/search_service.proto package retailpb @@ -478,72 +478,54 @@ type SearchRequest struct { // // Supported keys are: // - // - colorFamilies - // - price - // - originalPrice - // - discount - // - variantId - // - inventory(place_id,price) - // - inventory(place_id,original_price) - // - inventory(place_id,attributes.key), where key is any key in the - // [Product.local_inventories.attributes][google.cloud.retail.v2.LocalInventory.attributes] - // map. - // - attributes.key, where key is any key in the - // [Product.attributes][google.cloud.retail.v2.Product.attributes] map. - // - pickupInStore.id, where id is any - // + // * colorFamilies + // * price + // * originalPrice + // * discount + // * variantId + // * inventory(place_id,price) + // * inventory(place_id,original_price) + // * inventory(place_id,attributes.key), where key is any key in the + // [Product.local_inventories.attributes][google.cloud.retail.v2.LocalInventory.attributes] + // map. + // * attributes.key, where key is any key in the + // [Product.attributes][google.cloud.retail.v2.Product.attributes] map. + // * pickupInStore.id, where id is any // [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] // for [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] - // - // "pickup-in-store". - // + // "pickup-in-store". // * shipToStore.id, where id is any // [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] // for [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] - // - // "ship-to-store". - // + // "ship-to-store". // * sameDayDelivery.id, where id is any // [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] // for [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] - // - // "same-day-delivery". - // + // "same-day-delivery". // * nextDayDelivery.id, where id is any // [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] // for [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] - // - // "next-day-delivery". - // + // "next-day-delivery". // * customFulfillment1.id, where id is any // [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] // for [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] - // - // "custom-type-1". - // + // "custom-type-1". // * customFulfillment2.id, where id is any // [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] // for [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] - // - // "custom-type-2". - // + // "custom-type-2". // * customFulfillment3.id, where id is any // [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] // for [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] - // - // "custom-type-3". - // + // "custom-type-3". // * customFulfillment4.id, where id is any // [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] // for [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] - // - // "custom-type-4". - // + // "custom-type-4". // * customFulfillment5.id, where id is any // [FulfillmentInfo.place_ids][google.cloud.retail.v2.FulfillmentInfo.place_ids] // for [FulfillmentInfo.type][google.cloud.retail.v2.FulfillmentInfo.type] - // - // "custom-type-5". + // "custom-type-5". // // If this field is set to an invalid value other than these, an // INVALID_ARGUMENT error is returned. @@ -577,17 +559,17 @@ type SearchRequest struct { PersonalizationSpec *SearchRequest_PersonalizationSpec `protobuf:"bytes,32,opt,name=personalization_spec,json=personalizationSpec,proto3" json:"personalization_spec,omitempty"` // The labels applied to a resource must meet the following requirements: // - // - Each resource can have multiple labels, up to a maximum of 64. - // - Each label must be a key-value pair. - // - Keys have a minimum length of 1 character and a maximum length of 63 - // characters and cannot be empty. Values can be empty and have a maximum - // length of 63 characters. - // - Keys and values can contain only lowercase letters, numeric characters, - // underscores, and dashes. All characters must use UTF-8 encoding, and - // international characters are allowed. - // - The key portion of a label must be unique. However, you can use the same - // key with multiple resources. - // - Keys must start with a lowercase letter or international character. + // * Each resource can have multiple labels, up to a maximum of 64. + // * Each label must be a key-value pair. + // * Keys have a minimum length of 1 character and a maximum length of 63 + // characters and cannot be empty. Values can be empty and have a maximum + // length of 63 characters. + // * Keys and values can contain only lowercase letters, numeric characters, + // underscores, and dashes. All characters must use UTF-8 encoding, and + // international characters are allowed. + // * The key portion of a label must be unique. However, you can use the same + // key with multiple resources. + // * Keys must start with a lowercase letter or international character. // // See [Google Cloud // Document](https://cloud.google.com/resource-manager/docs/creating-managing-labels#requirements) @@ -943,6 +925,7 @@ type SearchRequest_FacetSpec struct { Limit int32 `protobuf:"varint,2,opt,name=limit,proto3" json:"limit,omitempty"` // List of keys to exclude when faceting. // + // // By default, // [FacetKey.key][google.cloud.retail.v2.SearchRequest.FacetSpec.FacetKey.key] // is not excluded from the filter unless it is listed in this field. @@ -1356,38 +1339,38 @@ type SearchRequest_FacetSpec_FacetKey struct { // is not specified: // // * textual_field = - // - "brands" - // - "categories" - // - "genders" - // - "ageGroups" - // - "availability" - // - "colorFamilies" - // - "colors" - // - "sizes" - // - "materials" - // - "patterns" - // - "conditions" - // - "attributes.key" - // - "pickupInStore" - // - "shipToStore" - // - "sameDayDelivery" - // - "nextDayDelivery" - // - "customFulfillment1" - // - "customFulfillment2" - // - "customFulfillment3" - // - "customFulfillment4" - // - "customFulfillment5" - // - "inventory(place_id,attributes.key)" + // * "brands" + // * "categories" + // * "genders" + // * "ageGroups" + // * "availability" + // * "colorFamilies" + // * "colors" + // * "sizes" + // * "materials" + // * "patterns" + // * "conditions" + // * "attributes.key" + // * "pickupInStore" + // * "shipToStore" + // * "sameDayDelivery" + // * "nextDayDelivery" + // * "customFulfillment1" + // * "customFulfillment2" + // * "customFulfillment3" + // * "customFulfillment4" + // * "customFulfillment5" + // * "inventory(place_id,attributes.key)" // // * numerical_field = - // - "price" - // - "discount" - // - "rating" - // - "ratingCount" - // - "attributes.key" - // - "inventory(place_id,price)" - // - "inventory(place_id,original_price)" - // - "inventory(place_id,attributes.key)" + // * "price" + // * "discount" + // * "rating" + // * "ratingCount" + // * "attributes.key" + // * "inventory(place_id,price)" + // * "inventory(place_id,original_price)" + // * "inventory(place_id,attributes.key)" Key string `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"` // Set only if values should be bucketized into intervals. Must be set // for facets with numerical values. Must not be set for facet with text @@ -1447,8 +1430,7 @@ type SearchRequest_FacetSpec_FacetKey struct { // * "value desc", which means order by // [SearchResponse.Facet.values.value][google.cloud.retail.v2.SearchResponse.Facet.FacetValue.value] // descending. - // - // Only applies to textual facets. + // Only applies to textual facets. // // If not set, textual values are sorted in [natural // order](https://en.wikipedia.org/wiki/Natural_sort_order); numerical @@ -1596,10 +1578,9 @@ type SearchRequest_BoostSpec_ConditionBoostSpec struct { // // * To boost products with product ID "product_1" or "product_2", and // color - // - // "Red" or "Blue": - // * (id: ANY("product_1", "product_2")) AND (colorFamilies: - // ANY("Red","Blue")) + // "Red" or "Blue": + // * (id: ANY("product_1", "product_2")) AND (colorFamilies: + // ANY("Red","Blue")) Condition string `protobuf:"bytes,1,opt,name=condition,proto3" json:"condition,omitempty"` // Strength of the condition boost, which should be in [-1, 1]. Negative // boost means demotion. Default is 0.0. @@ -1724,14 +1705,14 @@ type SearchResponse_SearchResult struct { // there are two variants with colors "red" and "blue", the rollup values // are // - // { key: "colorFamilies" - // value { - // list_value { - // values { string_value: "red" } - // values { string_value: "blue" } - // } - // } - // } + // { key: "colorFamilies" + // value { + // list_value { + // values { string_value: "red" } + // values { string_value: "blue" } + // } + // } + // } // // For [FulfillmentInfo][google.cloud.retail.v2.FulfillmentInfo], the rollup // values is a double value with type @@ -1968,7 +1949,6 @@ type SearchResponse_Facet_FacetValue struct { // A facet value which contains values. // // Types that are assignable to FacetValue: - // // *SearchResponse_Facet_FacetValue_Value // *SearchResponse_Facet_FacetValue_Interval FacetValue isSearchResponse_Facet_FacetValue_FacetValue `protobuf_oneof:"facet_value"` diff --git a/retail/apiv2/retailpb/serving_config.pb.go b/retail/apiv2/retailpb/serving_config.pb.go index 65450fd97518..ec4cd3e29ffd 100644 --- a/retail/apiv2/retailpb/serving_config.pb.go +++ b/retail/apiv2/retailpb/serving_config.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/retail/v2/serving_config.proto package retailpb @@ -67,8 +67,7 @@ type ServingConfig struct { // recommendation probability to be ordered by price, with the // highest-priced items first. This setting could result in a decrease in // click-through and conversion rates. - // - // Allowed values are: + // Allowed values are: // // * 'no-price-reranking' // * 'low-price-raranking' @@ -200,15 +199,14 @@ type ServingConfig struct { DiversityLevel string `protobuf:"bytes,8,opt,name=diversity_level,json=diversityLevel,proto3" json:"diversity_level,omitempty"` // Whether to add additional category filters on the 'similar-items' model. // If not specified, we enable it by default. + // Allowed values are: // - // Allowed values are: - // - // - 'no-category-match': No additional filtering of original results from - // the model and the customer's filters. - // - 'relaxed-category-match': Only keep results with categories that match - // at least one item categories in the PredictRequests's context item. - // - If customer also sends filters in the PredictRequest, then the results - // will satisfy both conditions (user given and category match). + // * 'no-category-match': No additional filtering of original results from + // the model and the customer's filters. + // * 'relaxed-category-match': Only keep results with categories that match + // at least one item categories in the PredictRequests's context item. + // * If customer also sends filters in the PredictRequest, then the results + // will satisfy both conditions (user given and category match). // // Can only be set if // [solution_types][google.cloud.retail.v2.ServingConfig.solution_types] is diff --git a/retail/apiv2/retailpb/serving_config_service.pb.go b/retail/apiv2/retailpb/serving_config_service.pb.go index 9f3e5e61bf95..25bfb03f568a 100644 --- a/retail/apiv2/retailpb/serving_config_service.pb.go +++ b/retail/apiv2/retailpb/serving_config_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/retail/v2/serving_config_service.proto package retailpb diff --git a/retail/apiv2/retailpb/user_event.pb.go b/retail/apiv2/retailpb/user_event.pb.go index 3d6a9867c5fa..047ee8626f0a 100644 --- a/retail/apiv2/retailpb/user_event.pb.go +++ b/retail/apiv2/retailpb/user_event.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/retail/v2/user_event.proto package retailpb @@ -47,16 +47,16 @@ type UserEvent struct { // Required. User event type. Allowed values are: // - // - `add-to-cart`: Products being added to cart. - // - `category-page-view`: Special pages such as sale or promotion pages - // viewed. - // - `detail-page-view`: Products detail page viewed. - // - `home-page-view`: Homepage viewed. - // - `promotion-offered`: Promotion is offered to a user. - // - `promotion-not-offered`: Promotion is not offered to a user. - // - `purchase-complete`: User finishing a purchase. - // - `search`: Product search. - // - `shopping-cart-page-view`: User viewing a shopping cart. + // * `add-to-cart`: Products being added to cart. + // * `category-page-view`: Special pages such as sale or promotion pages + // viewed. + // * `detail-page-view`: Products detail page viewed. + // * `home-page-view`: Homepage viewed. + // * `promotion-offered`: Promotion is offered to a user. + // * `promotion-not-offered`: Promotion is not offered to a user. + // * `purchase-complete`: User finishing a purchase. + // * `search`: Product search. + // * `shopping-cart-page-view`: User viewing a shopping cart. EventType string `protobuf:"bytes,1,opt,name=event_type,json=eventType,proto3" json:"event_type,omitempty"` // Required. A unique identifier for tracking visitors. // @@ -151,12 +151,12 @@ type UserEvent struct { // This field needs to pass all below criteria, otherwise an INVALID_ARGUMENT // error is returned: // - // - The key must be a UTF-8 encoded string with a length limit of 5,000 - // characters. - // - For text attributes, at most 400 values are allowed. Empty values are not - // allowed. Each value must be a UTF-8 encoded string with a length limit of - // 256 characters. - // - For number attributes, at most 400 values are allowed. + // * The key must be a UTF-8 encoded string with a length limit of 5,000 + // characters. + // * For text attributes, at most 400 values are allowed. Empty values are not + // allowed. Each value must be a UTF-8 encoded string with a length limit of + // 256 characters. + // * For number attributes, at most 400 values are allowed. // // For product recommendations, an example of extra user information is // traffic_channel, which is how a user arrives at the site. Users can arrive diff --git a/retail/apiv2/retailpb/user_event_service.pb.go b/retail/apiv2/retailpb/user_event_service.pb.go index ecbafa537156..69e2cc3a9faf 100644 --- a/retail/apiv2/retailpb/user_event_service.pb.go +++ b/retail/apiv2/retailpb/user_event_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/retail/v2/user_event_service.proto package retailpb diff --git a/retail/apiv2/search_client.go b/retail/apiv2/search_client.go index 79309cfe5a35..08870a7657b7 100644 --- a/retail/apiv2/search_client.go +++ b/retail/apiv2/search_client.go @@ -17,22 +17,28 @@ package retail import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" retailpb "cloud.google.com/go/retail/apiv2/retailpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -87,6 +93,34 @@ func defaultSearchCallOptions() *SearchCallOptions { } } +func defaultSearchRESTCallOptions() *SearchCallOptions { + return &SearchCallOptions{ + Search: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 5000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 300000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + } +} + // internalSearchClient is an interface that defines the methods available from Retail API. type internalSearchClient interface { Close() error @@ -240,6 +274,77 @@ func (c *searchGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type searchRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing SearchClient + CallOptions **SearchCallOptions +} + +// NewSearchRESTClient creates a new search service rest client. +// +// Service for search. +// +// This feature is only available for users who have Retail Search enabled. +// Please enable Retail Search on Cloud Console before using this feature. +func NewSearchRESTClient(ctx context.Context, opts ...option.ClientOption) (*SearchClient, error) { + clientOpts := append(defaultSearchRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultSearchRESTCallOptions() + c := &searchRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &SearchClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultSearchRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://retail.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://retail.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://retail.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *searchRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *searchRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *searchRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *searchGRPCClient) Search(ctx context.Context, req *retailpb.SearchRequest, opts ...gax.CallOption) *SearchResponse_SearchResultIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "placement", url.QueryEscape(req.GetPlacement()))) @@ -347,6 +452,246 @@ func (c *searchGRPCClient) ListOperations(ctx context.Context, req *longrunningp return it } +// Search performs a search. +// +// This feature is only available for users who have Retail Search enabled. +// Please enable Retail Search on Cloud Console before using this feature. +func (c *searchRESTClient) Search(ctx context.Context, req *retailpb.SearchRequest, opts ...gax.CallOption) *SearchResponse_SearchResultIterator { + it := &SearchResponse_SearchResultIterator{} + req = proto.Clone(req).(*retailpb.SearchRequest) + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*retailpb.SearchResponse_SearchResult, string, error) { + resp := &retailpb.SearchResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, "", err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:search", req.GetPlacement()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetResults(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *searchRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *searchRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + // SearchResponse_SearchResultIterator manages a stream of *retailpb.SearchResponse_SearchResult. type SearchResponse_SearchResultIterator struct { items []*retailpb.SearchResponse_SearchResult diff --git a/retail/apiv2/search_client_example_test.go b/retail/apiv2/search_client_example_test.go index ff4b1e4ba165..6c478ccfca6a 100644 --- a/retail/apiv2/search_client_example_test.go +++ b/retail/apiv2/search_client_example_test.go @@ -42,6 +42,23 @@ func ExampleNewSearchClient() { _ = c } +func ExampleNewSearchRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := retail.NewSearchRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleSearchClient_Search() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/retail/apiv2/serving_config_client.go b/retail/apiv2/serving_config_client.go index 9bf37609d182..ea77120a0e37 100644 --- a/retail/apiv2/serving_config_client.go +++ b/retail/apiv2/serving_config_client.go @@ -17,22 +17,28 @@ package retail import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" retailpb "cloud.google.com/go/retail/apiv2/retailpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -88,6 +94,30 @@ func defaultServingConfigCallOptions() *ServingConfigCallOptions { } } +func defaultServingConfigRESTCallOptions() *ServingConfigCallOptions { + return &ServingConfigCallOptions{ + CreateServingConfig: []gax.CallOption{}, + DeleteServingConfig: []gax.CallOption{}, + UpdateServingConfig: []gax.CallOption{}, + GetServingConfig: []gax.CallOption{}, + ListServingConfigs: []gax.CallOption{}, + AddControl: []gax.CallOption{}, + RemoveControl: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 300000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + } +} + // internalServingConfigClient is an interface that defines the methods available from Retail API. type internalServingConfigClient interface { Close() error @@ -285,6 +315,74 @@ func (c *servingConfigGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type servingConfigRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing ServingConfigClient + CallOptions **ServingConfigCallOptions +} + +// NewServingConfigRESTClient creates a new serving config service rest client. +// +// Service for modifying ServingConfig. +func NewServingConfigRESTClient(ctx context.Context, opts ...option.ClientOption) (*ServingConfigClient, error) { + clientOpts := append(defaultServingConfigRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultServingConfigRESTCallOptions() + c := &servingConfigRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &ServingConfigClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultServingConfigRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://retail.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://retail.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://retail.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *servingConfigRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *servingConfigRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *servingConfigRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *servingConfigGRPCClient) CreateServingConfig(ctx context.Context, req *retailpb.CreateServingConfigRequest, opts ...gax.CallOption) (*retailpb.ServingConfig, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -490,6 +588,624 @@ func (c *servingConfigGRPCClient) ListOperations(ctx context.Context, req *longr return it } +// CreateServingConfig creates a ServingConfig. +// +// A maximum of 100 ServingConfigs are +// allowed in a Catalog, otherwise a +// FAILED_PRECONDITION error is returned. +func (c *servingConfigRESTClient) CreateServingConfig(ctx context.Context, req *retailpb.CreateServingConfigRequest, opts ...gax.CallOption) (*retailpb.ServingConfig, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetServingConfig() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/servingConfigs", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("servingConfigId", fmt.Sprintf("%v", req.GetServingConfigId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateServingConfig[0:len((*c.CallOptions).CreateServingConfig):len((*c.CallOptions).CreateServingConfig)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &retailpb.ServingConfig{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteServingConfig deletes a ServingConfig. +// +// Returns a NotFound error if the ServingConfig does not exist. +func (c *servingConfigRESTClient) DeleteServingConfig(ctx context.Context, req *retailpb.DeleteServingConfigRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// UpdateServingConfig updates a ServingConfig. +func (c *servingConfigRESTClient) UpdateServingConfig(ctx context.Context, req *retailpb.UpdateServingConfigRequest, opts ...gax.CallOption) (*retailpb.ServingConfig, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetServingConfig() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetServingConfig().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "serving_config.name", url.QueryEscape(req.GetServingConfig().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateServingConfig[0:len((*c.CallOptions).UpdateServingConfig):len((*c.CallOptions).UpdateServingConfig)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &retailpb.ServingConfig{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetServingConfig gets a ServingConfig. +// +// Returns a NotFound error if the ServingConfig does not exist. +func (c *servingConfigRESTClient) GetServingConfig(ctx context.Context, req *retailpb.GetServingConfigRequest, opts ...gax.CallOption) (*retailpb.ServingConfig, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetServingConfig[0:len((*c.CallOptions).GetServingConfig):len((*c.CallOptions).GetServingConfig)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &retailpb.ServingConfig{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListServingConfigs lists all ServingConfigs linked to this catalog. +func (c *servingConfigRESTClient) ListServingConfigs(ctx context.Context, req *retailpb.ListServingConfigsRequest, opts ...gax.CallOption) *ServingConfigIterator { + it := &ServingConfigIterator{} + req = proto.Clone(req).(*retailpb.ListServingConfigsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*retailpb.ServingConfig, string, error) { + resp := &retailpb.ListServingConfigsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/servingConfigs", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetServingConfigs(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// AddControl enables a Control on the specified ServingConfig. +// The control is added in the last position of the list of controls +// it belongs to (e.g. if it’s a facet spec control it will be applied +// in the last position of servingConfig.facetSpecIds) +// Returns a ALREADY_EXISTS error if the control has already been applied. +// Returns a FAILED_PRECONDITION error if the addition could exceed maximum +// number of control allowed for that type of control. +func (c *servingConfigRESTClient) AddControl(ctx context.Context, req *retailpb.AddControlRequest, opts ...gax.CallOption) (*retailpb.ServingConfig, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:addControl", req.GetServingConfig()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "serving_config", url.QueryEscape(req.GetServingConfig()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).AddControl[0:len((*c.CallOptions).AddControl):len((*c.CallOptions).AddControl)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &retailpb.ServingConfig{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// RemoveControl disables a Control on the specified ServingConfig. +// The control is removed from the ServingConfig. +// Returns a NOT_FOUND error if the Control is not enabled for the +// ServingConfig. +func (c *servingConfigRESTClient) RemoveControl(ctx context.Context, req *retailpb.RemoveControlRequest, opts ...gax.CallOption) (*retailpb.ServingConfig, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:removeControl", req.GetServingConfig()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "serving_config", url.QueryEscape(req.GetServingConfig()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).RemoveControl[0:len((*c.CallOptions).RemoveControl):len((*c.CallOptions).RemoveControl)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &retailpb.ServingConfig{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *servingConfigRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *servingConfigRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + // ServingConfigIterator manages a stream of *retailpb.ServingConfig. type ServingConfigIterator struct { items []*retailpb.ServingConfig diff --git a/retail/apiv2/serving_config_client_example_test.go b/retail/apiv2/serving_config_client_example_test.go index 29101dee757b..c57dcd662e6b 100644 --- a/retail/apiv2/serving_config_client_example_test.go +++ b/retail/apiv2/serving_config_client_example_test.go @@ -42,6 +42,23 @@ func ExampleNewServingConfigClient() { _ = c } +func ExampleNewServingConfigRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := retail.NewServingConfigRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleServingConfigClient_CreateServingConfig() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/retail/apiv2/user_event_client.go b/retail/apiv2/user_event_client.go index 21b05d3d0ce4..75ae7543e2a7 100644 --- a/retail/apiv2/user_event_client.go +++ b/retail/apiv2/user_event_client.go @@ -17,9 +17,12 @@ package retail import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,15 +30,18 @@ import ( lroauto "cloud.google.com/go/longrunning/autogen" retailpb "cloud.google.com/go/retail/apiv2/retailpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" httpbodypb "google.golang.org/genproto/googleapis/api/httpbody" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -142,6 +148,78 @@ func defaultUserEventCallOptions() *UserEventCallOptions { } } +func defaultUserEventRESTCallOptions() *UserEventCallOptions { + return &UserEventCallOptions{ + WriteUserEvent: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 5000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + CollectUserEvent: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 5000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + PurgeUserEvents: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 30000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + ImportUserEvents: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 300000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + RejoinUserEvents: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 5000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 300000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + } +} + // internalUserEventClient is an interface that defines the methods available from Retail API. type internalUserEventClient interface { Close() error @@ -372,6 +450,89 @@ func (c *userEventGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type userEventRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing UserEventClient + CallOptions **UserEventCallOptions +} + +// NewUserEventRESTClient creates a new user event service rest client. +// +// Service for ingesting end user actions on the customer website. +func NewUserEventRESTClient(ctx context.Context, opts ...option.ClientOption) (*UserEventClient, error) { + clientOpts := append(defaultUserEventRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultUserEventRESTCallOptions() + c := &userEventRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &UserEventClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultUserEventRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://retail.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://retail.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://retail.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *userEventRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *userEventRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *userEventRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *userEventGRPCClient) WriteUserEvent(ctx context.Context, req *retailpb.WriteUserEventRequest, opts ...gax.CallOption) (*retailpb.UserEvent, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 5000*time.Millisecond) @@ -550,9 +711,513 @@ func (c *userEventGRPCClient) ListOperations(ctx context.Context, req *longrunni return it } +// WriteUserEvent writes a single user event. +func (c *userEventRESTClient) WriteUserEvent(ctx context.Context, req *retailpb.WriteUserEventRequest, opts ...gax.CallOption) (*retailpb.UserEvent, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetUserEvent() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/userEvents:write", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).WriteUserEvent[0:len((*c.CallOptions).WriteUserEvent):len((*c.CallOptions).WriteUserEvent)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &retailpb.UserEvent{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CollectUserEvent writes a single user event from the browser. This uses a GET request to +// due to browser restriction of POST-ing to a 3rd party domain. +// +// This method is used only by the Retail API JavaScript pixel and Google Tag +// Manager. Users should not call this method directly. +func (c *userEventRESTClient) CollectUserEvent(ctx context.Context, req *retailpb.CollectUserEventRequest, opts ...gax.CallOption) (*httpbodypb.HttpBody, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/userEvents:collect", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetEts() != 0 { + params.Add("ets", fmt.Sprintf("%v", req.GetEts())) + } + if req.GetUri() != "" { + params.Add("uri", fmt.Sprintf("%v", req.GetUri())) + } + params.Add("userEvent", fmt.Sprintf("%v", req.GetUserEvent())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CollectUserEvent[0:len((*c.CallOptions).CollectUserEvent):len((*c.CallOptions).CollectUserEvent)], opts...) + resp := &httpbodypb.HttpBody{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + resp.Data = buf + if headers := httpRsp.Header; len(headers["Content-Type"]) > 0 { + resp.ContentType = headers["Content-Type"][0] + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// PurgeUserEvents deletes permanently all user events specified by the filter provided. +// Depending on the number of events specified by the filter, this operation +// could take hours or days to complete. To test a filter, use the list +// command first. +func (c *userEventRESTClient) PurgeUserEvents(ctx context.Context, req *retailpb.PurgeUserEventsRequest, opts ...gax.CallOption) (*PurgeUserEventsOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/userEvents:purge", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &PurgeUserEventsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ImportUserEvents bulk import of User events. Request processing might be +// synchronous. Events that already exist are skipped. +// Use this method for backfilling historical user events. +// +// Operation.response is of type ImportResponse. Note that it is +// possible for a subset of the items to be successfully inserted. +// Operation.metadata is of type ImportMetadata. +func (c *userEventRESTClient) ImportUserEvents(ctx context.Context, req *retailpb.ImportUserEventsRequest, opts ...gax.CallOption) (*ImportUserEventsOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/userEvents:import", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &ImportUserEventsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// RejoinUserEvents starts a user event rejoin operation with latest product catalog. Events +// will not be annotated with detailed product information if product is +// missing from the catalog at the time the user event is ingested, and these +// events are stored as unjoined events with a limited usage on training and +// serving. This method can be used to start a join operation on specified +// events with latest version of product catalog. It can also be used to +// correct events joined with the wrong product catalog. A rejoin operation +// can take hours or days to complete. +func (c *userEventRESTClient) RejoinUserEvents(ctx context.Context, req *retailpb.RejoinUserEventsRequest, opts ...gax.CallOption) (*RejoinUserEventsOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/userEvents:rejoin", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &RejoinUserEventsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *userEventRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *userEventRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + // ImportUserEventsOperation manages a long-running operation from ImportUserEvents. type ImportUserEventsOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // ImportUserEventsOperation returns a new ImportUserEventsOperation from a given name. @@ -563,10 +1228,21 @@ func (c *userEventGRPCClient) ImportUserEventsOperation(name string) *ImportUser } } +// ImportUserEventsOperation returns a new ImportUserEventsOperation from a given name. +// The name must be that of a previously created ImportUserEventsOperation, possibly from a different process. +func (c *userEventRESTClient) ImportUserEventsOperation(name string) *ImportUserEventsOperation { + override := fmt.Sprintf("/v2/%s", name) + return &ImportUserEventsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *ImportUserEventsOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*retailpb.ImportUserEventsResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp retailpb.ImportUserEventsResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -584,6 +1260,7 @@ func (op *ImportUserEventsOperation) Wait(ctx context.Context, opts ...gax.CallO // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *ImportUserEventsOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*retailpb.ImportUserEventsResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp retailpb.ImportUserEventsResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -621,7 +1298,8 @@ func (op *ImportUserEventsOperation) Name() string { // PurgeUserEventsOperation manages a long-running operation from PurgeUserEvents. type PurgeUserEventsOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // PurgeUserEventsOperation returns a new PurgeUserEventsOperation from a given name. @@ -632,10 +1310,21 @@ func (c *userEventGRPCClient) PurgeUserEventsOperation(name string) *PurgeUserEv } } +// PurgeUserEventsOperation returns a new PurgeUserEventsOperation from a given name. +// The name must be that of a previously created PurgeUserEventsOperation, possibly from a different process. +func (c *userEventRESTClient) PurgeUserEventsOperation(name string) *PurgeUserEventsOperation { + override := fmt.Sprintf("/v2/%s", name) + return &PurgeUserEventsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *PurgeUserEventsOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*retailpb.PurgeUserEventsResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp retailpb.PurgeUserEventsResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -653,6 +1342,7 @@ func (op *PurgeUserEventsOperation) Wait(ctx context.Context, opts ...gax.CallOp // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *PurgeUserEventsOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*retailpb.PurgeUserEventsResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp retailpb.PurgeUserEventsResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -690,7 +1380,8 @@ func (op *PurgeUserEventsOperation) Name() string { // RejoinUserEventsOperation manages a long-running operation from RejoinUserEvents. type RejoinUserEventsOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // RejoinUserEventsOperation returns a new RejoinUserEventsOperation from a given name. @@ -701,10 +1392,21 @@ func (c *userEventGRPCClient) RejoinUserEventsOperation(name string) *RejoinUser } } +// RejoinUserEventsOperation returns a new RejoinUserEventsOperation from a given name. +// The name must be that of a previously created RejoinUserEventsOperation, possibly from a different process. +func (c *userEventRESTClient) RejoinUserEventsOperation(name string) *RejoinUserEventsOperation { + override := fmt.Sprintf("/v2/%s", name) + return &RejoinUserEventsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *RejoinUserEventsOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*retailpb.RejoinUserEventsResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp retailpb.RejoinUserEventsResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -722,6 +1424,7 @@ func (op *RejoinUserEventsOperation) Wait(ctx context.Context, opts ...gax.CallO // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *RejoinUserEventsOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*retailpb.RejoinUserEventsResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp retailpb.RejoinUserEventsResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/retail/apiv2/user_event_client_example_test.go b/retail/apiv2/user_event_client_example_test.go index fe217bfe8ee8..c2737b11cc68 100644 --- a/retail/apiv2/user_event_client_example_test.go +++ b/retail/apiv2/user_event_client_example_test.go @@ -42,6 +42,23 @@ func ExampleNewUserEventClient() { _ = c } +func ExampleNewUserEventRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := retail.NewUserEventRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleUserEventClient_WriteUserEvent() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/retail/apiv2alpha/catalog_client.go b/retail/apiv2alpha/catalog_client.go index ece81665394d..147b04a6a7b1 100644 --- a/retail/apiv2alpha/catalog_client.go +++ b/retail/apiv2alpha/catalog_client.go @@ -1042,6 +1042,7 @@ func (c *catalogRESTClient) ListCatalogs(ctx context.Context, req *retailpb.List baseUrl.Path += fmt.Sprintf("/v2alpha/%v/catalogs", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -1123,6 +1124,7 @@ func (c *catalogRESTClient) UpdateCatalog(ctx context.Context, req *retailpb.Upd baseUrl.Path += fmt.Sprintf("/v2alpha/%v", req.GetCatalog().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -1226,6 +1228,11 @@ func (c *catalogRESTClient) SetDefaultBranch(ctx context.Context, req *retailpb. } baseUrl.Path += fmt.Sprintf("/v2alpha/%v:setDefaultBranch", req.GetCatalog()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "catalog", url.QueryEscape(req.GetCatalog()))) @@ -1263,6 +1270,11 @@ func (c *catalogRESTClient) GetDefaultBranch(ctx context.Context, req *retailpb. } baseUrl.Path += fmt.Sprintf("/v2alpha/%v:getDefaultBranch", req.GetCatalog()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "catalog", url.QueryEscape(req.GetCatalog()))) @@ -1316,6 +1328,11 @@ func (c *catalogRESTClient) GetCompletionConfig(ctx context.Context, req *retail } baseUrl.Path += fmt.Sprintf("/v2alpha/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1378,6 +1395,7 @@ func (c *catalogRESTClient) UpdateCompletionConfig(ctx context.Context, req *ret baseUrl.Path += fmt.Sprintf("/v2alpha/%v", req.GetCompletionConfig().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -1441,6 +1459,11 @@ func (c *catalogRESTClient) GetAttributesConfig(ctx context.Context, req *retail } baseUrl.Path += fmt.Sprintf("/v2alpha/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1510,6 +1533,7 @@ func (c *catalogRESTClient) UpdateAttributesConfig(ctx context.Context, req *ret baseUrl.Path += fmt.Sprintf("/v2alpha/%v", req.GetAttributesConfig().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -1584,6 +1608,11 @@ func (c *catalogRESTClient) AddCatalogAttribute(ctx context.Context, req *retail } baseUrl.Path += fmt.Sprintf("/v2alpha/%v:addCatalogAttribute", req.GetAttributesConfig()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "attributes_config", url.QueryEscape(req.GetAttributesConfig()))) @@ -1648,6 +1677,11 @@ func (c *catalogRESTClient) RemoveCatalogAttribute(ctx context.Context, req *ret } baseUrl.Path += fmt.Sprintf("/v2alpha/%v:removeCatalogAttribute", req.GetAttributesConfig()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "attributes_config", url.QueryEscape(req.GetAttributesConfig()))) @@ -1714,6 +1748,11 @@ func (c *catalogRESTClient) ReplaceCatalogAttribute(ctx context.Context, req *re } baseUrl.Path += fmt.Sprintf("/v2alpha/%v:replaceCatalogAttribute", req.GetAttributesConfig()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "attributes_config", url.QueryEscape(req.GetAttributesConfig()))) @@ -1767,6 +1806,11 @@ func (c *catalogRESTClient) GetOperation(ctx context.Context, req *longrunningpb } baseUrl.Path += fmt.Sprintf("/v2alpha/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1834,6 +1878,7 @@ func (c *catalogRESTClient) ListOperations(ctx context.Context, req *longrunning baseUrl.Path += fmt.Sprintf("/v2alpha/%v/operations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/retail/apiv2alpha/completion_client.go b/retail/apiv2alpha/completion_client.go index a9882b57d57d..326c191328f0 100644 --- a/retail/apiv2alpha/completion_client.go +++ b/retail/apiv2alpha/completion_client.go @@ -548,14 +548,17 @@ func (c *completionRESTClient) CompleteQuery(ctx context.Context, req *retailpb. baseUrl.Path += fmt.Sprintf("/v2alpha/%v:completeQuery", req.GetCatalog()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetDataset() != "" { params.Add("dataset", fmt.Sprintf("%v", req.GetDataset())) } if req.GetDeviceType() != "" { params.Add("deviceType", fmt.Sprintf("%v", req.GetDeviceType())) } - if req.GetLanguageCodes() != nil { - params.Add("languageCodes", fmt.Sprintf("%v", req.GetLanguageCodes())) + if items := req.GetLanguageCodes(); len(items) > 0 { + for _, item := range items { + params.Add("languageCodes", fmt.Sprintf("%v", item)) + } } if req.GetMaxSuggestions() != 0 { params.Add("maxSuggestions", fmt.Sprintf("%v", req.GetMaxSuggestions())) @@ -634,6 +637,11 @@ func (c *completionRESTClient) ImportCompletionData(ctx context.Context, req *re } baseUrl.Path += fmt.Sprintf("/v2alpha/%v/completionData:import", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -691,6 +699,11 @@ func (c *completionRESTClient) GetOperation(ctx context.Context, req *longrunnin } baseUrl.Path += fmt.Sprintf("/v2alpha/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -758,6 +771,7 @@ func (c *completionRESTClient) ListOperations(ctx context.Context, req *longrunn baseUrl.Path += fmt.Sprintf("/v2alpha/%v/operations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/retail/apiv2alpha/control_client.go b/retail/apiv2alpha/control_client.go index 0b19c4527bd4..1809288ea932 100644 --- a/retail/apiv2alpha/control_client.go +++ b/retail/apiv2alpha/control_client.go @@ -549,6 +549,7 @@ func (c *controlRESTClient) CreateControl(ctx context.Context, req *retailpb.Cre baseUrl.Path += fmt.Sprintf("/v2alpha/%v/controls", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("controlId", fmt.Sprintf("%v", req.GetControlId())) baseUrl.RawQuery = params.Encode() @@ -609,6 +610,11 @@ func (c *controlRESTClient) DeleteControl(ctx context.Context, req *retailpb.Del } baseUrl.Path += fmt.Sprintf("/v2alpha/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -657,6 +663,7 @@ func (c *controlRESTClient) UpdateControl(ctx context.Context, req *retailpb.Upd baseUrl.Path += fmt.Sprintf("/v2alpha/%v", req.GetControl().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -720,6 +727,11 @@ func (c *controlRESTClient) GetControl(ctx context.Context, req *retailpb.GetCon } baseUrl.Path += fmt.Sprintf("/v2alpha/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -787,6 +799,7 @@ func (c *controlRESTClient) ListControls(ctx context.Context, req *retailpb.List baseUrl.Path += fmt.Sprintf("/v2alpha/%v/controls", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -863,6 +876,11 @@ func (c *controlRESTClient) GetOperation(ctx context.Context, req *longrunningpb } baseUrl.Path += fmt.Sprintf("/v2alpha/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -930,6 +948,7 @@ func (c *controlRESTClient) ListOperations(ctx context.Context, req *longrunning baseUrl.Path += fmt.Sprintf("/v2alpha/%v/operations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/retail/apiv2alpha/model_client.go b/retail/apiv2alpha/model_client.go index fd95c676da5d..b6cad73633e6 100644 --- a/retail/apiv2alpha/model_client.go +++ b/retail/apiv2alpha/model_client.go @@ -864,6 +864,7 @@ func (c *modelRESTClient) CreateModel(ctx context.Context, req *retailpb.CreateM baseUrl.Path += fmt.Sprintf("/v2alpha/%v/models", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetDryRun() { params.Add("dryRun", fmt.Sprintf("%v", req.GetDryRun())) } @@ -933,6 +934,11 @@ func (c *modelRESTClient) PauseModel(ctx context.Context, req *retailpb.PauseMod } baseUrl.Path += fmt.Sprintf("/v2alpha/%v:pause", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -992,6 +998,11 @@ func (c *modelRESTClient) ResumeModel(ctx context.Context, req *retailpb.ResumeM } baseUrl.Path += fmt.Sprintf("/v2alpha/%v:resume", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1045,6 +1056,11 @@ func (c *modelRESTClient) DeleteModel(ctx context.Context, req *retailpb.DeleteM } baseUrl.Path += fmt.Sprintf("/v2alpha/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1094,6 +1110,7 @@ func (c *modelRESTClient) ListModels(ctx context.Context, req *retailpb.ListMode baseUrl.Path += fmt.Sprintf("/v2alpha/%v/models", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -1177,6 +1194,7 @@ func (c *modelRESTClient) UpdateModel(ctx context.Context, req *retailpb.UpdateM baseUrl.Path += fmt.Sprintf("/v2alpha/%v", req.GetModel().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -1246,6 +1264,11 @@ func (c *modelRESTClient) TuneModel(ctx context.Context, req *retailpb.TuneModel } baseUrl.Path += fmt.Sprintf("/v2alpha/%v:tune", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1303,6 +1326,11 @@ func (c *modelRESTClient) GetOperation(ctx context.Context, req *longrunningpb.G } baseUrl.Path += fmt.Sprintf("/v2alpha/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1370,6 +1398,7 @@ func (c *modelRESTClient) ListOperations(ctx context.Context, req *longrunningpb baseUrl.Path += fmt.Sprintf("/v2alpha/%v/operations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/retail/apiv2alpha/prediction_client.go b/retail/apiv2alpha/prediction_client.go index 1d9f75b9383e..7c62018e4ed8 100644 --- a/retail/apiv2alpha/prediction_client.go +++ b/retail/apiv2alpha/prediction_client.go @@ -431,6 +431,11 @@ func (c *predictionRESTClient) Predict(ctx context.Context, req *retailpb.Predic } baseUrl.Path += fmt.Sprintf("/v2alpha/%v:predict", req.GetPlacement()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "placement", url.QueryEscape(req.GetPlacement()))) @@ -484,6 +489,11 @@ func (c *predictionRESTClient) GetOperation(ctx context.Context, req *longrunnin } baseUrl.Path += fmt.Sprintf("/v2alpha/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -551,6 +561,7 @@ func (c *predictionRESTClient) ListOperations(ctx context.Context, req *longrunn baseUrl.Path += fmt.Sprintf("/v2alpha/%v/operations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/retail/apiv2alpha/product_client.go b/retail/apiv2alpha/product_client.go index d90f3d7519ed..cf06d5112954 100644 --- a/retail/apiv2alpha/product_client.go +++ b/retail/apiv2alpha/product_client.go @@ -1260,6 +1260,7 @@ func (c *productRESTClient) CreateProduct(ctx context.Context, req *retailpb.Cre baseUrl.Path += fmt.Sprintf("/v2alpha/%v/products", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("productId", fmt.Sprintf("%v", req.GetProductId())) baseUrl.RawQuery = params.Encode() @@ -1317,6 +1318,11 @@ func (c *productRESTClient) GetProduct(ctx context.Context, req *retailpb.GetPro } baseUrl.Path += fmt.Sprintf("/v2alpha/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1384,6 +1390,7 @@ func (c *productRESTClient) ListProducts(ctx context.Context, req *retailpb.List baseUrl.Path += fmt.Sprintf("/v2alpha/%v/products", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1478,6 +1485,7 @@ func (c *productRESTClient) UpdateProduct(ctx context.Context, req *retailpb.Upd baseUrl.Path += fmt.Sprintf("/v2alpha/%v", req.GetProduct().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetAllowMissing() { params.Add("allowMissing", fmt.Sprintf("%v", req.GetAllowMissing())) } @@ -1544,6 +1552,11 @@ func (c *productRESTClient) DeleteProduct(ctx context.Context, req *retailpb.Del } baseUrl.Path += fmt.Sprintf("/v2alpha/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1601,6 +1614,11 @@ func (c *productRESTClient) PurgeProducts(ctx context.Context, req *retailpb.Pur } baseUrl.Path += fmt.Sprintf("/v2alpha/%v/products:purge", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1670,6 +1688,11 @@ func (c *productRESTClient) ImportProducts(ctx context.Context, req *retailpb.Im } baseUrl.Path += fmt.Sprintf("/v2alpha/%v/products:import", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1775,6 +1798,11 @@ func (c *productRESTClient) SetInventory(ctx context.Context, req *retailpb.SetI } baseUrl.Path += fmt.Sprintf("/v2alpha/%v:setInventory", req.GetInventory().GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "inventory.name", url.QueryEscape(req.GetInventory().GetName()))) @@ -1852,6 +1880,11 @@ func (c *productRESTClient) AddFulfillmentPlaces(ctx context.Context, req *retai } baseUrl.Path += fmt.Sprintf("/v2alpha/%v:addFulfillmentPlaces", req.GetProduct()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "product", url.QueryEscape(req.GetProduct()))) @@ -1929,6 +1962,11 @@ func (c *productRESTClient) RemoveFulfillmentPlaces(ctx context.Context, req *re } baseUrl.Path += fmt.Sprintf("/v2alpha/%v:removeFulfillmentPlaces", req.GetProduct()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "product", url.QueryEscape(req.GetProduct()))) @@ -2013,6 +2051,11 @@ func (c *productRESTClient) AddLocalInventories(ctx context.Context, req *retail } baseUrl.Path += fmt.Sprintf("/v2alpha/%v:addLocalInventories", req.GetProduct()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "product", url.QueryEscape(req.GetProduct()))) @@ -2095,6 +2138,11 @@ func (c *productRESTClient) RemoveLocalInventories(ctx context.Context, req *ret } baseUrl.Path += fmt.Sprintf("/v2alpha/%v:removeLocalInventories", req.GetProduct()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "product", url.QueryEscape(req.GetProduct()))) @@ -2152,6 +2200,11 @@ func (c *productRESTClient) GetOperation(ctx context.Context, req *longrunningpb } baseUrl.Path += fmt.Sprintf("/v2alpha/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2219,6 +2272,7 @@ func (c *productRESTClient) ListOperations(ctx context.Context, req *longrunning baseUrl.Path += fmt.Sprintf("/v2alpha/%v/operations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/retail/apiv2alpha/retailpb/catalog.pb.go b/retail/apiv2alpha/retailpb/catalog.pb.go index af027b3ecd39..0f9068a868cb 100644 --- a/retail/apiv2alpha/retailpb/catalog.pb.go +++ b/retail/apiv2alpha/retailpb/catalog.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/retail/v2alpha/catalog.proto package retailpb @@ -266,17 +266,16 @@ type ProductLevelConfig struct { // // * `primary` (default): You can ingest // [Product][google.cloud.retail.v2alpha.Product]s of all types. When - // - // ingesting a [Product][google.cloud.retail.v2alpha.Product], its type will - // default to - // [Product.Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] - // if unset. - // - `variant` (incompatible with Retail Search): You can only - // ingest - // [Product.Type.VARIANT][google.cloud.retail.v2alpha.Product.Type.VARIANT] - // [Product][google.cloud.retail.v2alpha.Product]s. This means - // [Product.primary_product_id][google.cloud.retail.v2alpha.Product.primary_product_id] - // cannot be empty. + // ingesting a [Product][google.cloud.retail.v2alpha.Product], its type will + // default to + // [Product.Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] + // if unset. + // * `variant` (incompatible with Retail Search): You can only + // ingest + // [Product.Type.VARIANT][google.cloud.retail.v2alpha.Product.Type.VARIANT] + // [Product][google.cloud.retail.v2alpha.Product]s. This means + // [Product.primary_product_id][google.cloud.retail.v2alpha.Product.primary_product_id] + // cannot be empty. // // If this field is set to an invalid value other than these, an // INVALID_ARGUMENT error is returned. @@ -294,10 +293,10 @@ type ProductLevelConfig struct { // imported as [Product.id][google.cloud.retail.v2alpha.Product.id]. // Acceptable values are: // - // - `offerId` (default): Import `offerId` as the product ID. - // - `itemGroupId`: Import `itemGroupId` as the product ID. Notice that Retail - // API will choose one item from the ones with the same `itemGroupId`, and - // use it to represent the item group. + // * `offerId` (default): Import `offerId` as the product ID. + // * `itemGroupId`: Import `itemGroupId` as the product ID. Notice that Retail + // API will choose one item from the ones with the same `itemGroupId`, and + // use it to represent the item group. // // If this field is set to an invalid value other than these, an // INVALID_ARGUMENT error is returned. diff --git a/retail/apiv2alpha/retailpb/catalog_service.pb.go b/retail/apiv2alpha/retailpb/catalog_service.pb.go index d14234dbeb9c..c11fecfe6bc7 100644 --- a/retail/apiv2alpha/retailpb/catalog_service.pb.go +++ b/retail/apiv2alpha/retailpb/catalog_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/retail/v2alpha/catalog_service.proto package retailpb @@ -1566,11 +1566,11 @@ type CatalogServiceClient interface { // // More specifically: // - // - PredictionService will only return product IDs from branch {newBranch}. - // - SearchService will only return product IDs from branch {newBranch} - // (if branch is not explicitly set). - // - UserEventService will only join events with products from branch - // {newBranch}. + // * PredictionService will only return product IDs from branch {newBranch}. + // * SearchService will only return product IDs from branch {newBranch} + // (if branch is not explicitly set). + // * UserEventService will only join events with products from branch + // {newBranch}. SetDefaultBranch(ctx context.Context, in *SetDefaultBranchRequest, opts ...grpc.CallOption) (*emptypb.Empty, error) // Get which branch is currently default branch set by // [CatalogService.SetDefaultBranch][google.cloud.retail.v2alpha.CatalogService.SetDefaultBranch] @@ -1760,11 +1760,11 @@ type CatalogServiceServer interface { // // More specifically: // - // - PredictionService will only return product IDs from branch {newBranch}. - // - SearchService will only return product IDs from branch {newBranch} - // (if branch is not explicitly set). - // - UserEventService will only join events with products from branch - // {newBranch}. + // * PredictionService will only return product IDs from branch {newBranch}. + // * SearchService will only return product IDs from branch {newBranch} + // (if branch is not explicitly set). + // * UserEventService will only join events with products from branch + // {newBranch}. SetDefaultBranch(context.Context, *SetDefaultBranchRequest) (*emptypb.Empty, error) // Get which branch is currently default branch set by // [CatalogService.SetDefaultBranch][google.cloud.retail.v2alpha.CatalogService.SetDefaultBranch] diff --git a/retail/apiv2alpha/retailpb/common.pb.go b/retail/apiv2alpha/retailpb/common.pb.go index a9ced4d03380..39c37ed748dc 100644 --- a/retail/apiv2alpha/retailpb/common.pb.go +++ b/retail/apiv2alpha/retailpb/common.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/retail/v2alpha/common.proto package retailpb @@ -337,7 +337,6 @@ type Rule struct { // An action must be provided. // // Types that are assignable to Action: - // // *Rule_BoostAction_ // *Rule_RedirectAction_ // *Rule_OnewaySynonymsAction_ @@ -986,7 +985,6 @@ type Interval struct { // Otherwise, an INVALID_ARGUMENT error is returned. // // Types that are assignable to Min: - // // *Interval_Minimum // *Interval_ExclusiveMinimum Min isInterval_Min `protobuf_oneof:"min"` @@ -997,7 +995,6 @@ type Interval struct { // Otherwise, an INVALID_ARGUMENT error is returned. // // Types that are assignable to Max: - // // *Interval_Maximum // *Interval_ExclusiveMaximum Max isInterval_Max `protobuf_oneof:"max"` @@ -1500,18 +1497,18 @@ type LocalInventory struct { // This field needs to pass all below criteria, otherwise an INVALID_ARGUMENT // error is returned: // - // - At most 30 attributes are allowed. - // - The key must be a UTF-8 encoded string with a length limit of 32 - // characters. - // - The key must match the pattern: `[a-zA-Z0-9][a-zA-Z0-9_]*`. For example, - // key0LikeThis or KEY_1_LIKE_THIS. - // - The attribute values must be of the same type (text or number). - // - Only 1 value is allowed for each attribute. - // - For text values, the length limit is 256 UTF-8 characters. - // - The attribute does not support search. The `searchable` field should be - // unset or set to false. - // - The max summed total bytes of custom attribute keys and values per - // product is 5MiB. + // * At most 30 attributes are allowed. + // * The key must be a UTF-8 encoded string with a length limit of 32 + // characters. + // * The key must match the pattern: `[a-zA-Z0-9][a-zA-Z0-9_]*`. For example, + // key0LikeThis or KEY_1_LIKE_THIS. + // * The attribute values must be of the same type (text or number). + // * Only 1 value is allowed for each attribute. + // * For text values, the length limit is 256 UTF-8 characters. + // * The attribute does not support search. The `searchable` field should be + // unset or set to false. + // * The max summed total bytes of custom attribute keys and values per + // product is 5MiB. Attributes map[string]*CustomAttribute `protobuf:"bytes,3,rep,name=attributes,proto3" json:"attributes,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` // Input only. Supported fulfillment types. Valid fulfillment type values // include commonly used types (such as pickup in store and same day @@ -1754,11 +1751,10 @@ type Rule_BoostAction struct { // // * To boost products with product ID "product_1" or "product_2", and // color - // - // "Red" or "Blue":
- // *(id: ANY("product_1", "product_2"))
* - // *AND
* - // *(colorFamilies: ANY("Red", "Blue"))
* + // "Red" or "Blue":
+ // *(id: ANY("product_1", "product_2"))
* + // *AND
* + // *(colorFamilies: ANY("Red", "Blue"))
* ProductsFilter string `protobuf:"bytes,2,opt,name=products_filter,json=productsFilter,proto3" json:"products_filter,omitempty"` } @@ -1835,17 +1831,14 @@ type Rule_FilterAction struct { // * Filter syntax is identical to // [SearchRequest.filter][google.cloud.retail.v2alpha.SearchRequest.filter]. // See more - // - // details at the Retail Search - // [user guide](/retail/search/docs/filter-and-order#filter). - // + // details at the Retail Search + // [user guide](/retail/search/docs/filter-and-order#filter). // * To filter products with product ID "product_1" or "product_2", and // color - // - // "Red" or "Blue":
- // *(id: ANY("product_1", "product_2"))
* - // *AND
* - // *(colorFamilies: ANY("Red", "Blue"))
* + // "Red" or "Blue":
+ // *(id: ANY("product_1", "product_2"))
* + // *AND
* + // *(colorFamilies: ANY("Red", "Blue"))
* Filter string `protobuf:"bytes,1,opt,name=filter,proto3" json:"filter,omitempty"` } diff --git a/retail/apiv2alpha/retailpb/completion_service.pb.go b/retail/apiv2alpha/retailpb/completion_service.pb.go index 0799e8904f6f..af57ef3d1576 100644 --- a/retail/apiv2alpha/retailpb/completion_service.pb.go +++ b/retail/apiv2alpha/retailpb/completion_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/retail/v2alpha/completion_service.proto package retailpb @@ -99,9 +99,9 @@ type CompleteQueryRequest struct { // // * user-data // - // - cloud-retail: - // This option requires enabling auto-learning function first. See - // [guidelines](https://cloud.google.com/retail/docs/completion-overview#generated-completion-dataset). + // * cloud-retail: + // This option requires enabling auto-learning function first. See + // [guidelines](https://cloud.google.com/retail/docs/completion-overview#generated-completion-dataset). Dataset string `protobuf:"bytes,6,opt,name=dataset,proto3" json:"dataset,omitempty"` // Completion max suggestions. If left unset or set to 0, then will fallback // to the configured value @@ -216,15 +216,15 @@ type CompleteQueryResponse struct { // field is set and [UserEvent][google.cloud.retail.v2alpha.UserEvent] is // imported. The recent searches satisfy the follow rules: // - // - They are ordered from latest to oldest. + // * They are ordered from latest to oldest. // - // - They are matched with - // [CompleteQueryRequest.query][google.cloud.retail.v2alpha.CompleteQueryRequest.query] - // case insensitively. + // * They are matched with + // [CompleteQueryRequest.query][google.cloud.retail.v2alpha.CompleteQueryRequest.query] + // case insensitively. // - // - They are transformed to lower case. + // * They are transformed to lower case. // - // - They are UTF-8 safe. + // * They are UTF-8 safe. // // Recent searches are deduplicated. More recent searches will be reserved // when duplication happens. diff --git a/retail/apiv2alpha/retailpb/control.pb.go b/retail/apiv2alpha/retailpb/control.pb.go index 224fa231b694..265ad3db9d0c 100644 --- a/retail/apiv2alpha/retailpb/control.pb.go +++ b/retail/apiv2alpha/retailpb/control.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/retail/v2alpha/control.proto package retailpb @@ -50,7 +50,6 @@ type Control struct { // INVALID_ARGUMENT will be returned if either condition is violated. // // Types that are assignable to Control: - // // *Control_FacetSpec // *Control_Rule Control isControl_Control `protobuf_oneof:"control"` diff --git a/retail/apiv2alpha/retailpb/control_service.pb.go b/retail/apiv2alpha/retailpb/control_service.pb.go index 2c1a3e44d3b9..0572f7d6b44f 100644 --- a/retail/apiv2alpha/retailpb/control_service.pb.go +++ b/retail/apiv2alpha/retailpb/control_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/retail/v2alpha/control_service.proto package retailpb @@ -297,7 +297,7 @@ type ListControlsRequest struct { // // * List all the products under the parent branch if // [filter][google.cloud.retail.v2alpha.ListControlsRequest.filter] is unset. - // - List controls that are used in a single ServingConfig: + // * List controls that are used in a single ServingConfig: // 'serving_config = "boosted_home_page_cvr"' Filter string `protobuf:"bytes,4,opt,name=filter,proto3" json:"filter,omitempty"` } diff --git a/retail/apiv2alpha/retailpb/export_config.pb.go b/retail/apiv2alpha/retailpb/export_config.pb.go index 58e373b4b9d3..ff212d29bd73 100644 --- a/retail/apiv2alpha/retailpb/export_config.pb.go +++ b/retail/apiv2alpha/retailpb/export_config.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/retail/v2alpha/export_config.proto package retailpb @@ -46,7 +46,6 @@ type ExportErrorsConfig struct { // Required. Errors destination. // // Types that are assignable to Destination: - // // *ExportErrorsConfig_GcsPrefix Destination isExportErrorsConfig_Destination `protobuf_oneof:"destination"` } diff --git a/retail/apiv2alpha/retailpb/import_config.pb.go b/retail/apiv2alpha/retailpb/import_config.pb.go index 4f9e05d756ab..2fa4d2fdd05b 100644 --- a/retail/apiv2alpha/retailpb/import_config.pb.go +++ b/retail/apiv2alpha/retailpb/import_config.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/retail/v2alpha/import_config.proto package retailpb @@ -127,17 +127,16 @@ type GcsSource struct { // // * `product` (default): One JSON // [Product][google.cloud.retail.v2alpha.Product] per line. Each product must - // - // have a valid [Product.id][google.cloud.retail.v2alpha.Product.id]. - // - `product_merchant_center`: See [Importing catalog data from Merchant - // Center](https://cloud.google.com/retail/recommendations-ai/docs/upload-catalog#mc). + // have a valid [Product.id][google.cloud.retail.v2alpha.Product.id]. + // * `product_merchant_center`: See [Importing catalog data from Merchant + // Center](https://cloud.google.com/retail/recommendations-ai/docs/upload-catalog#mc). // // Supported values for user events imports: // // * `user_event` (default): One JSON // [UserEvent][google.cloud.retail.v2alpha.UserEvent] per line. - // - `user_event_ga360`: Using - // https://support.google.com/analytics/answer/3437719. + // * `user_event_ga360`: Using + // https://support.google.com/analytics/answer/3437719. // // Supported values for control imports: // @@ -207,7 +206,6 @@ type BigQuerySource struct { // is not partitioned. // // Types that are assignable to Partition: - // // *BigQuerySource_PartitionDate Partition isBigQuerySource_Partition `protobuf_oneof:"partition"` // The project ID (can be project # or ID) that the BigQuery source is in with @@ -230,22 +228,21 @@ type BigQuerySource struct { // // * `product` (default): One JSON // [Product][google.cloud.retail.v2alpha.Product] per line. Each product must - // - // have a valid [Product.id][google.cloud.retail.v2alpha.Product.id]. - // - `product_merchant_center`: See [Importing catalog data from Merchant - // Center](https://cloud.google.com/retail/recommendations-ai/docs/upload-catalog#mc). + // have a valid [Product.id][google.cloud.retail.v2alpha.Product.id]. + // * `product_merchant_center`: See [Importing catalog data from Merchant + // Center](https://cloud.google.com/retail/recommendations-ai/docs/upload-catalog#mc). // // Supported values for user events imports: // // * `user_event` (default): One JSON // [UserEvent][google.cloud.retail.v2alpha.UserEvent] per line. - // - `user_event_ga360`: - // The schema is available here: - // https://support.google.com/analytics/answer/3437719. - // - `user_event_ga4`: This feature is in private preview. Please contact the - // support team for importing Google Analytics 4 events. - // The schema is available here: - // https://support.google.com/analytics/answer/7029846. + // * `user_event_ga360`: + // The schema is available here: + // https://support.google.com/analytics/answer/3437719. + // * `user_event_ga4`: This feature is in private preview. Please contact the + // support team for importing Google Analytics 4 events. + // The schema is available here: + // https://support.google.com/analytics/answer/7029846. // // Supported values for auto-completion imports: // @@ -460,7 +457,6 @@ type ImportErrorsConfig struct { // Required. Errors destination. // // Types that are assignable to Destination: - // // *ImportErrorsConfig_GcsPrefix Destination isImportErrorsConfig_Destination `protobuf_oneof:"destination"` } @@ -818,7 +814,6 @@ type ProductInputConfig struct { // Required. The source of the input. // // Types that are assignable to Source: - // // *ProductInputConfig_ProductInlineSource // *ProductInputConfig_GcsSource // *ProductInputConfig_BigQuerySource @@ -919,7 +914,6 @@ type UserEventInputConfig struct { // The source of the input. // // Types that are assignable to Source: - // // *UserEventInputConfig_UserEventInlineSource // *UserEventInputConfig_GcsSource // *UserEventInputConfig_BigQuerySource @@ -1028,7 +1022,6 @@ type CompletionDataInputConfig struct { // * `allowlist`: One JSON allow suggestion per line. // // Types that are assignable to Source: - // // *CompletionDataInputConfig_BigQuerySource Source isCompletionDataInputConfig_Source `protobuf_oneof:"source"` } diff --git a/retail/apiv2alpha/retailpb/model.pb.go b/retail/apiv2alpha/retailpb/model.pb.go index ca83dc067d0a..75bfcd84bf59 100644 --- a/retail/apiv2alpha/retailpb/model.pb.go +++ b/retail/apiv2alpha/retailpb/model.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/retail/v2alpha/model.proto package retailpb @@ -286,22 +286,21 @@ const ( // // `Panel2 candidates`: home_page_ctr_no_diversity, // home_page_ctr_diversity, - // - // pdp_cvr_no_diversity + // pdp_cvr_no_diversity // // `Restriction` = NO_RESTRICTION // // `Valid combinations`: // - // - (pdp_ctr, home_page_ctr_no_diversity) - // - (pdp_ctr, home_page_ctr_diversity) - // - (pdp_ctr, pdp_cvr_no_diversity) - // - (pdp_cvr, home_page_ctr_no_diversity) - // - (pdp_cvr, home_page_ctr_diversity) - // - (pdp_cvr, pdp_cvr_no_diversity) - // - (home_page_ctr_no_diversity, home_page_ctr_no_diversity) - // - (home_page_ctr_no_diversity, home_page_ctr_diversity) - // - (home_page_ctr_no_diversity, pdp_cvr_no_diversity) + // * (pdp_ctr, home_page_ctr_no_diversity) + // * (pdp_ctr, home_page_ctr_diversity) + // * (pdp_ctr, pdp_cvr_no_diversity) + // * (pdp_cvr, home_page_ctr_no_diversity) + // * (pdp_cvr, home_page_ctr_diversity) + // * (pdp_cvr, pdp_cvr_no_diversity) + // * (home_page_ctr_no_diversity, home_page_ctr_no_diversity) + // * (home_page_ctr_no_diversity, home_page_ctr_diversity) + // * (home_page_ctr_no_diversity, pdp_cvr_no_diversity) // // `Invalid combinations`: [] Model_PageOptimizationConfig_NO_RESTRICTION Model_PageOptimizationConfig_Restriction = 1 @@ -316,26 +315,25 @@ const ( // // `Panel2 candidates`: home_page_ctr_no_diversity, // home_page_ctr_diversity_low, - // - // pdp_cvr_no_diversity + // pdp_cvr_no_diversity // // `Restriction` = UNIQUE_SERVING_CONFIG_RESTRICTION // // `Valid combinations`: // - // - (pdp_ctr, home_page_ctr_no_diversity) - // - (pdp_ctr, home_page_ctr_diversity_low) - // - (pdp_ctr, pdp_cvr_no_diversity) - // - (pdp_ctr, pdp_cvr_no_diversity) - // - (pdp_cvr, home_page_ctr_no_diversity) - // - (pdp_cvr, home_page_ctr_diversity_low) - // - (pdp_cvr, pdp_cvr_no_diversity) - // - (home_page_ctr_no_diversity, home_page_ctr_diversity_low) - // - (home_page_ctr_no_diversity, pdp_cvr_no_diversity) + // * (pdp_ctr, home_page_ctr_no_diversity) + // * (pdp_ctr, home_page_ctr_diversity_low) + // * (pdp_ctr, pdp_cvr_no_diversity) + // * (pdp_ctr, pdp_cvr_no_diversity) + // * (pdp_cvr, home_page_ctr_no_diversity) + // * (pdp_cvr, home_page_ctr_diversity_low) + // * (pdp_cvr, pdp_cvr_no_diversity) + // * (home_page_ctr_no_diversity, home_page_ctr_diversity_low) + // * (home_page_ctr_no_diversity, pdp_cvr_no_diversity) // // `Invalid combinations`: // - // - (home_page_ctr_no_diversity, home_page_ctr_no_diversity) + // * (home_page_ctr_no_diversity, home_page_ctr_no_diversity) Model_PageOptimizationConfig_UNIQUE_SERVING_CONFIG_RESTRICTION Model_PageOptimizationConfig_Restriction = 2 // Do not allow multiple // [ServingConfigs][google.cloud.retail.v2alpha.ServingConfig] with same @@ -349,25 +347,24 @@ const ( // // `Panel2 candidates`: home_page_ctr_no_diversity, // home_page_ctr_diversity_low, - // - // pdp_cvr_no_diversity + // pdp_cvr_no_diversity // // `Restriction` = UNIQUE_MODEL_RESTRICTION // // `Valid combinations`: // - // - (pdp_ctr, home_page_ctr_no_diversity) - // - (pdp_ctr, home_page_ctr_diversity) - // - (pdp_ctr, pdp_cvr_no_diversity) - // - (pdp_ctr, pdp_cvr_no_diversity) - // - (pdp_cvr, home_page_ctr_no_diversity) - // - (pdp_cvr, home_page_ctr_diversity_low) - // - (home_page_ctr_no_diversity, pdp_cvr_no_diversity) + // * (pdp_ctr, home_page_ctr_no_diversity) + // * (pdp_ctr, home_page_ctr_diversity) + // * (pdp_ctr, pdp_cvr_no_diversity) + // * (pdp_ctr, pdp_cvr_no_diversity) + // * (pdp_cvr, home_page_ctr_no_diversity) + // * (pdp_cvr, home_page_ctr_diversity_low) + // * (home_page_ctr_no_diversity, pdp_cvr_no_diversity) // // `Invalid combinations`: // - // - (home_page_ctr_no_diversity, home_page_ctr_no_diversity) - // - (pdp_cvr, pdp_cvr_no_diversity) + // * (home_page_ctr_no_diversity, home_page_ctr_no_diversity) + // * (pdp_cvr, pdp_cvr_no_diversity) Model_PageOptimizationConfig_UNIQUE_MODEL_RESTRICTION Model_PageOptimizationConfig_Restriction = 3 // Do not allow multiple // [ServingConfigs][google.cloud.retail.v2alpha.ServingConfig] with same @@ -381,8 +378,7 @@ const ( // // `Panel2 candidates`: home_page_ctr_no_diversity, // home_page_ctr_diversity_low, - // - // pdp_cvr_no_diversity + // pdp_cvr_no_diversity // // `Restriction` = UNIQUE_MODEL_RESTRICTION // @@ -396,11 +392,11 @@ const ( // // `Invalid combinations`: // - // - (pdp_ctr, pdp_cvr_no_diversity) - // - (pdp_ctr, pdp_cvr_no_diversity) - // - (pdp_cvr, pdp_cvr_no_diversity) - // - (home_page_ctr_no_diversity, home_page_ctr_no_diversity) - // - (home_page_ctr_no_diversity, home_page_ctr_diversity) + // * (pdp_ctr, pdp_cvr_no_diversity) + // * (pdp_ctr, pdp_cvr_no_diversity) + // * (pdp_cvr, pdp_cvr_no_diversity) + // * (home_page_ctr_no_diversity, home_page_ctr_no_diversity) + // * (home_page_ctr_no_diversity, home_page_ctr_diversity) Model_PageOptimizationConfig_UNIQUE_MODEL_TYPE_RESTRICTION Model_PageOptimizationConfig_Restriction = 4 ) @@ -464,7 +460,6 @@ type Model struct { // page optimization. // // Types that are assignable to TrainingConfig: - // // *Model_PageOptimizationConfig_ TrainingConfig isModel_TrainingConfig `protobuf_oneof:"training_config"` // Required. The fully qualified resource name of the model. @@ -508,8 +503,7 @@ type Model struct { // Currently supported // values: `ctr`, `cvr`, `revenue-per-order`. // - // If not specified, we choose default based on model type. - // + // If not specified, we choose default based on model type. // Default depends on type of recommendation: // // `recommended-for-you` => `ctr` @@ -859,7 +853,6 @@ type Model_PageOptimizationConfig_Candidate struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Candidate: - // // *Model_PageOptimizationConfig_Candidate_ServingConfigId Candidate isModel_PageOptimizationConfig_Candidate_Candidate `protobuf_oneof:"candidate"` } diff --git a/retail/apiv2alpha/retailpb/model_service.pb.go b/retail/apiv2alpha/retailpb/model_service.pb.go index f54a4606e300..9a60da44f2ab 100644 --- a/retail/apiv2alpha/retailpb/model_service.pb.go +++ b/retail/apiv2alpha/retailpb/model_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/retail/v2alpha/model_service.proto package retailpb diff --git a/retail/apiv2alpha/retailpb/prediction_service.pb.go b/retail/apiv2alpha/retailpb/prediction_service.pb.go index 094afddbf868..e6aaad803a52 100644 --- a/retail/apiv2alpha/retailpb/prediction_service.pb.go +++ b/retail/apiv2alpha/retailpb/prediction_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/retail/v2alpha/prediction_service.proto package retailpb @@ -89,25 +89,25 @@ type PredictRequest struct { // Filter for restricting prediction results with a length limit of 5,000 // characters. Accepts values for tags and the `filterOutOfStockItems` flag. // - // - Tag expressions. Restricts predictions to products that match all of the - // specified tags. Boolean operators `OR` and `NOT` are supported if the - // expression is enclosed in parentheses, and must be separated from the - // tag values by a space. `-"tagA"` is also supported and is equivalent to - // `NOT "tagA"`. Tag values must be double quoted UTF-8 encoded strings - // with a size limit of 1,000 characters. + // * Tag expressions. Restricts predictions to products that match all of the + // specified tags. Boolean operators `OR` and `NOT` are supported if the + // expression is enclosed in parentheses, and must be separated from the + // tag values by a space. `-"tagA"` is also supported and is equivalent to + // `NOT "tagA"`. Tag values must be double quoted UTF-8 encoded strings + // with a size limit of 1,000 characters. // - // Note: "Recently viewed" models don't support tag filtering at the - // moment. + // Note: "Recently viewed" models don't support tag filtering at the + // moment. // - // - filterOutOfStockItems. Restricts predictions to products that do not - // have a - // stockState value of OUT_OF_STOCK. + // * filterOutOfStockItems. Restricts predictions to products that do not + // have a + // stockState value of OUT_OF_STOCK. // // Examples: // - // - tag=("Red" OR "Blue") tag="New-Arrival" tag=(NOT "promotional") - // - filterOutOfStockItems tag=(-"promotional") - // - filterOutOfStockItems + // * tag=("Red" OR "Blue") tag="New-Arrival" tag=(NOT "promotional") + // * filterOutOfStockItems tag=(-"promotional") + // * filterOutOfStockItems // // If your filter blocks all prediction results, the API will return generic // (unfiltered) popular products. If you only want results strictly matching @@ -120,9 +120,9 @@ type PredictRequest struct { // attribute-based expressions are expected instead of the above described // tag-based syntax. Examples: // - // - (colors: ANY("Red", "Blue")) AND NOT (categories: ANY("Phones")) - // - (availability: ANY("IN_STOCK")) AND - // (colors: ANY("Red") OR categories: ANY("Phones")) + // * (colors: ANY("Red", "Blue")) AND NOT (categories: ANY("Phones")) + // * (availability: ANY("IN_STOCK")) AND + // (colors: ANY("Red") OR categories: ANY("Phones")) Filter string `protobuf:"bytes,5,opt,name=filter,proto3" json:"filter,omitempty"` // Use validate only mode for this prediction query. If set to true, a // dummy model will be used that returns arbitrary products. @@ -133,43 +133,43 @@ type PredictRequest struct { // // Allowed values: // - // - `returnProduct`: Boolean. If set to true, the associated product - // object will be returned in the `results.metadata` field in the - // prediction response. - // - `returnScore`: Boolean. If set to true, the prediction 'score' - // corresponding to each returned product will be set in the - // `results.metadata` field in the prediction response. The given - // 'score' indicates the probability of an product being clicked/purchased - // given the user's context and history. - // - `strictFiltering`: Boolean. True by default. If set to false, the service - // will return generic (unfiltered) popular products instead of empty if - // your filter blocks all prediction results. - // - `priceRerankLevel`: String. Default empty. If set to be non-empty, then - // it needs to be one of {'no-price-reranking', 'low-price-reranking', - // 'medium-price-reranking', 'high-price-reranking'}. This gives - // request-level control and adjusts prediction results based on product - // price. - // - `diversityLevel`: String. Default empty. If set to be non-empty, then - // it needs to be one of {'no-diversity', 'low-diversity', - // 'medium-diversity', 'high-diversity', 'auto-diversity'}. This gives - // request-level control and adjusts prediction results based on product - // category. - // - `filterSyntaxV2`: Boolean. False by default. If set to true, the `filter` - // field is interpreteted according to the new, attribute-based syntax. + // * `returnProduct`: Boolean. If set to true, the associated product + // object will be returned in the `results.metadata` field in the + // prediction response. + // * `returnScore`: Boolean. If set to true, the prediction 'score' + // corresponding to each returned product will be set in the + // `results.metadata` field in the prediction response. The given + // 'score' indicates the probability of an product being clicked/purchased + // given the user's context and history. + // * `strictFiltering`: Boolean. True by default. If set to false, the service + // will return generic (unfiltered) popular products instead of empty if + // your filter blocks all prediction results. + // * `priceRerankLevel`: String. Default empty. If set to be non-empty, then + // it needs to be one of {'no-price-reranking', 'low-price-reranking', + // 'medium-price-reranking', 'high-price-reranking'}. This gives + // request-level control and adjusts prediction results based on product + // price. + // * `diversityLevel`: String. Default empty. If set to be non-empty, then + // it needs to be one of {'no-diversity', 'low-diversity', + // 'medium-diversity', 'high-diversity', 'auto-diversity'}. This gives + // request-level control and adjusts prediction results based on product + // category. + // * `filterSyntaxV2`: Boolean. False by default. If set to true, the `filter` + // field is interpreteted according to the new, attribute-based syntax. Params map[string]*structpb.Value `protobuf:"bytes,7,rep,name=params,proto3" json:"params,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` // The labels applied to a resource must meet the following requirements: // - // - Each resource can have multiple labels, up to a maximum of 64. - // - Each label must be a key-value pair. - // - Keys have a minimum length of 1 character and a maximum length of 63 - // characters and cannot be empty. Values can be empty and have a maximum - // length of 63 characters. - // - Keys and values can contain only lowercase letters, numeric characters, - // underscores, and dashes. All characters must use UTF-8 encoding, and - // international characters are allowed. - // - The key portion of a label must be unique. However, you can use the same - // key with multiple resources. - // - Keys must start with a lowercase letter or international character. + // * Each resource can have multiple labels, up to a maximum of 64. + // * Each label must be a key-value pair. + // * Keys have a minimum length of 1 character and a maximum length of 63 + // characters and cannot be empty. Values can be empty and have a maximum + // length of 63 characters. + // * Keys and values can contain only lowercase letters, numeric characters, + // underscores, and dashes. All characters must use UTF-8 encoding, and + // international characters are allowed. + // * The key portion of a label must be unique. However, you can use the same + // key with multiple resources. + // * Keys must start with a lowercase letter or international character. // // See [Google Cloud // Document](https://cloud.google.com/resource-manager/docs/creating-managing-labels#requirements) @@ -358,10 +358,10 @@ type PredictResponse_PredictionResult struct { // // Possible values: // - // - `product`: JSON representation of the product. Is set if - // `returnProduct` is set to true in `PredictRequest.params`. - // - `score`: Prediction score in double value. Is set if - // `returnScore` is set to true in `PredictRequest.params`. + // * `product`: JSON representation of the product. Is set if + // `returnProduct` is set to true in `PredictRequest.params`. + // * `score`: Prediction score in double value. Is set if + // `returnScore` is set to true in `PredictRequest.params`. Metadata map[string]*structpb.Value `protobuf:"bytes,2,rep,name=metadata,proto3" json:"metadata,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` } diff --git a/retail/apiv2alpha/retailpb/product.pb.go b/retail/apiv2alpha/retailpb/product.pb.go index 3a878939556d..876e3fc89757 100644 --- a/retail/apiv2alpha/retailpb/product.pb.go +++ b/retail/apiv2alpha/retailpb/product.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/retail/v2alpha/product.proto package retailpb @@ -189,7 +189,6 @@ type Product struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Expiration: - // // *Product_ExpireTime // *Product_Ttl Expiration isProduct_Expiration `protobuf_oneof:"expiration"` @@ -268,6 +267,7 @@ type Product struct { // belonging to several parallel categories. Strongly recommended using the // full path for better search / recommendation quality. // + // // To represent full path of category, use '>' sign to separate different // hierarchies. If '>' is part of the category name, please replace it with // other character(s). @@ -277,10 +277,10 @@ type Product struct { // ["Sports & Fitness" -> "Athletic Clothing" -> "Shoes"], it could be // represented as: // - // "categories": [ - // "Shoes & Accessories > Shoes", - // "Sports & Fitness > Athletic Clothing > Shoes" - // ] + // "categories": [ + // "Shoes & Accessories > Shoes", + // "Sports & Fitness > Athletic Clothing > Shoes" + // ] // // Must be set for // [Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] @@ -358,16 +358,16 @@ type Product struct { // This field needs to pass all below criteria, otherwise an INVALID_ARGUMENT // error is returned: // - // - Max entries count: 200. - // - The key must be a UTF-8 encoded string with a length limit of 128 - // characters. - // - For indexable attribute, the key must match the pattern: - // `[a-zA-Z0-9][a-zA-Z0-9_]*`. For example, `key0LikeThis` or - // `KEY_1_LIKE_THIS`. - // - For text attributes, at most 400 values are allowed. Empty values are not - // allowed. Each value must be a non-empty UTF-8 encoded string with a - // length limit of 256 characters. - // - For number attributes, at most 400 values are allowed. + // * Max entries count: 200. + // * The key must be a UTF-8 encoded string with a length limit of 128 + // characters. + // * For indexable attribute, the key must match the pattern: + // `[a-zA-Z0-9][a-zA-Z0-9_]*`. For example, `key0LikeThis` or + // `KEY_1_LIKE_THIS`. + // * For text attributes, at most 400 values are allowed. Empty values are not + // allowed. Each value must be a non-empty UTF-8 encoded string with a + // length limit of 256 characters. + // * For number attributes, at most 400 values are allowed. Attributes map[string]*CustomAttribute `protobuf:"bytes,12,rep,name=attributes,proto3" json:"attributes,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` // Custom tags associated with the product. // diff --git a/retail/apiv2alpha/retailpb/product_service.pb.go b/retail/apiv2alpha/retailpb/product_service.pb.go index 5905657c4f43..a0c3b93850a2 100644 --- a/retail/apiv2alpha/retailpb/product_service.pb.go +++ b/retail/apiv2alpha/retailpb/product_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/retail/v2alpha/product_service.proto package retailpb @@ -393,24 +393,19 @@ type ListProductsRequest struct { // * List // [Product.Type.VARIANT][google.cloud.retail.v2alpha.Product.Type.VARIANT] // [Product][google.cloud.retail.v2alpha.Product]s sharing the same - // - // [Product.Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] - // [Product][google.cloud.retail.v2alpha.Product]. For example: - // `primary_product_id = "some_product_id"` - // + // [Product.Type.PRIMARY][google.cloud.retail.v2alpha.Product.Type.PRIMARY] + // [Product][google.cloud.retail.v2alpha.Product]. For example: + // `primary_product_id = "some_product_id"` // * List [Product][google.cloud.retail.v2alpha.Product]s bundled in a // [Product.Type.COLLECTION][google.cloud.retail.v2alpha.Product.Type.COLLECTION] // [Product][google.cloud.retail.v2alpha.Product]. - // - // For example: - // `collection_product_id = "some_product_id"` - // + // For example: + // `collection_product_id = "some_product_id"` // * List [Product][google.cloud.retail.v2alpha.Product]s with a partibular // type. For example: - // - // `type = "PRIMARY"` - // `type = "VARIANT"` - // `type = "COLLECTION"` + // `type = "PRIMARY"` + // `type = "VARIANT"` + // `type = "COLLECTION"` // // If the field is unrecognizable, an INVALID_ARGUMENT error is returned. // diff --git a/retail/apiv2alpha/retailpb/promotion.pb.go b/retail/apiv2alpha/retailpb/promotion.pb.go index 2fc1b1671f15..cc35b0e725c0 100644 --- a/retail/apiv2alpha/retailpb/promotion.pb.go +++ b/retail/apiv2alpha/retailpb/promotion.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/retail/v2alpha/promotion.proto package retailpb diff --git a/retail/apiv2alpha/retailpb/purge_config.pb.go b/retail/apiv2alpha/retailpb/purge_config.pb.go index dbfbb8407590..03ad1d7341a2 100644 --- a/retail/apiv2alpha/retailpb/purge_config.pb.go +++ b/retail/apiv2alpha/retailpb/purge_config.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/retail/v2alpha/purge_config.proto package retailpb @@ -180,31 +180,31 @@ type PurgeProductsRequest struct { // // Supported syntax: // - // - Comparators (">", "<", ">=", "<=", "="). - // Examples: - // - create_time <= "2015-02-13T17:05:46Z" - // - availability = "IN_STOCK" + // * Comparators (">", "<", ">=", "<=", "="). + // Examples: + // * create_time <= "2015-02-13T17:05:46Z" + // * availability = "IN_STOCK" // - // - Conjunctions ("AND") - // Examples: - // - create_time <= "2015-02-13T17:05:46Z" AND availability = "PREORDER" + // * Conjunctions ("AND") + // Examples: + // * create_time <= "2015-02-13T17:05:46Z" AND availability = "PREORDER" // - // - Disjunctions ("OR") - // Examples: - // - create_time <= "2015-02-13T17:05:46Z" OR availability = "IN_STOCK" + // * Disjunctions ("OR") + // Examples: + // * create_time <= "2015-02-13T17:05:46Z" OR availability = "IN_STOCK" // - // - Can support nested queries. - // Examples: - // - (create_time <= "2015-02-13T17:05:46Z" AND availability = "PREORDER") - // OR (create_time >= "2015-02-14T13:03:32Z" AND availability = "IN_STOCK") + // * Can support nested queries. + // Examples: + // * (create_time <= "2015-02-13T17:05:46Z" AND availability = "PREORDER") + // OR (create_time >= "2015-02-14T13:03:32Z" AND availability = "IN_STOCK") // // * Filter Limits: - // - Filter should not contain more than 6 conditions. - // - Max nesting depth should not exceed 2 levels. + // * Filter should not contain more than 6 conditions. + // * Max nesting depth should not exceed 2 levels. // // Examples queries: - // - Delete back order products created before a timestamp. - // create_time <= "2015-02-13T17:05:46Z" OR availability = "BACKORDER" + // * Delete back order products created before a timestamp. + // create_time <= "2015-02-13T17:05:46Z" OR availability = "BACKORDER" Filter string `protobuf:"bytes,2,opt,name=filter,proto3" json:"filter,omitempty"` // Actually perform the purge. // If `force` is set to false, the method will return the expected purge count @@ -344,21 +344,21 @@ type PurgeUserEventsRequest struct { // * `eventType`: Double quoted // [UserEvent.event_type][google.cloud.retail.v2alpha.UserEvent.event_type] // string. - // - `eventTime`: in ISO 8601 "zulu" format. - // - `visitorId`: Double quoted string. Specifying this will delete all - // events associated with a visitor. - // - `userId`: Double quoted string. Specifying this will delete all events - // associated with a user. + // * `eventTime`: in ISO 8601 "zulu" format. + // * `visitorId`: Double quoted string. Specifying this will delete all + // events associated with a visitor. + // * `userId`: Double quoted string. Specifying this will delete all events + // associated with a user. // // Examples: // - // - Deleting all events in a time range: - // `eventTime > "2012-04-23T18:25:43.511Z" - // eventTime < "2012-04-23T18:30:43.511Z"` - // - Deleting specific eventType in time range: - // `eventTime > "2012-04-23T18:25:43.511Z" eventType = "detail-page-view"` - // - Deleting all events for a specific visitor: - // `visitorId = "visitor1024"` + // * Deleting all events in a time range: + // `eventTime > "2012-04-23T18:25:43.511Z" + // eventTime < "2012-04-23T18:30:43.511Z"` + // * Deleting specific eventType in time range: + // `eventTime > "2012-04-23T18:25:43.511Z" eventType = "detail-page-view"` + // * Deleting all events for a specific visitor: + // `visitorId = "visitor1024"` // // The filtering fields are assumed to have an implicit AND. Filter string `protobuf:"bytes,2,opt,name=filter,proto3" json:"filter,omitempty"` diff --git a/retail/apiv2alpha/retailpb/search_service.pb.go b/retail/apiv2alpha/retailpb/search_service.pb.go index f055e3ccd036..b869174a0c7f 100644 --- a/retail/apiv2alpha/retailpb/search_service.pb.go +++ b/retail/apiv2alpha/retailpb/search_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/retail/v2alpha/search_service.proto package retailpb @@ -552,81 +552,63 @@ type SearchRequest struct { // // Supported keys are: // - // - colorFamilies - // - price - // - originalPrice - // - discount - // - variantId - // - inventory(place_id,price) - // - inventory(place_id,original_price) - // - inventory(place_id,attributes.key), where key is any key in the - // [Product.local_inventories.attributes][google.cloud.retail.v2alpha.LocalInventory.attributes] - // map. - // - attributes.key, where key is any key in the - // [Product.attributes][google.cloud.retail.v2alpha.Product.attributes] map. - // - pickupInStore.id, where id is any - // + // * colorFamilies + // * price + // * originalPrice + // * discount + // * variantId + // * inventory(place_id,price) + // * inventory(place_id,original_price) + // * inventory(place_id,attributes.key), where key is any key in the + // [Product.local_inventories.attributes][google.cloud.retail.v2alpha.LocalInventory.attributes] + // map. + // * attributes.key, where key is any key in the + // [Product.attributes][google.cloud.retail.v2alpha.Product.attributes] map. + // * pickupInStore.id, where id is any // [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] // for // [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] - // - // "pickup-in-store". - // + // "pickup-in-store". // * shipToStore.id, where id is any // [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] // for // [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] - // - // "ship-to-store". - // + // "ship-to-store". // * sameDayDelivery.id, where id is any // [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] // for // [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] - // - // "same-day-delivery". - // + // "same-day-delivery". // * nextDayDelivery.id, where id is any // [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] // for // [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] - // - // "next-day-delivery". - // + // "next-day-delivery". // * customFulfillment1.id, where id is any // [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] // for // [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] - // - // "custom-type-1". - // + // "custom-type-1". // * customFulfillment2.id, where id is any // [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] // for // [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] - // - // "custom-type-2". - // + // "custom-type-2". // * customFulfillment3.id, where id is any // [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] // for // [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] - // - // "custom-type-3". - // + // "custom-type-3". // * customFulfillment4.id, where id is any // [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] // for // [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] - // - // "custom-type-4". - // + // "custom-type-4". // * customFulfillment5.id, where id is any // [FulfillmentInfo.place_ids][google.cloud.retail.v2alpha.FulfillmentInfo.place_ids] // for // [FulfillmentInfo.type][google.cloud.retail.v2alpha.FulfillmentInfo.type] - // - // "custom-type-5". + // "custom-type-5". // // If this field is set to an invalid value other than these, an // INVALID_ARGUMENT error is returned. @@ -651,17 +633,17 @@ type SearchRequest struct { PersonalizationSpec *SearchRequest_PersonalizationSpec `protobuf:"bytes,32,opt,name=personalization_spec,json=personalizationSpec,proto3" json:"personalization_spec,omitempty"` // The labels applied to a resource must meet the following requirements: // - // - Each resource can have multiple labels, up to a maximum of 64. - // - Each label must be a key-value pair. - // - Keys have a minimum length of 1 character and a maximum length of 63 - // characters and cannot be empty. Values can be empty and have a maximum - // length of 63 characters. - // - Keys and values can contain only lowercase letters, numeric characters, - // underscores, and dashes. All characters must use UTF-8 encoding, and - // international characters are allowed. - // - The key portion of a label must be unique. However, you can use the same - // key with multiple resources. - // - Keys must start with a lowercase letter or international character. + // * Each resource can have multiple labels, up to a maximum of 64. + // * Each label must be a key-value pair. + // * Keys have a minimum length of 1 character and a maximum length of 63 + // characters and cannot be empty. Values can be empty and have a maximum + // length of 63 characters. + // * Keys and values can contain only lowercase letters, numeric characters, + // underscores, and dashes. All characters must use UTF-8 encoding, and + // international characters are allowed. + // * The key portion of a label must be unique. However, you can use the same + // key with multiple resources. + // * Keys must start with a lowercase letter or international character. // // See [Google Cloud // Document](https://cloud.google.com/resource-manager/docs/creating-managing-labels#requirements) @@ -1025,6 +1007,7 @@ type SearchRequest_FacetSpec struct { Limit int32 `protobuf:"varint,2,opt,name=limit,proto3" json:"limit,omitempty"` // List of keys to exclude when faceting. // + // // By default, // [FacetKey.key][google.cloud.retail.v2alpha.SearchRequest.FacetSpec.FacetKey.key] // is not excluded from the filter unless it is listed in this field. @@ -1438,38 +1421,38 @@ type SearchRequest_FacetSpec_FacetKey struct { // is not specified: // // * textual_field = - // - "brands" - // - "categories" - // - "genders" - // - "ageGroups" - // - "availability" - // - "colorFamilies" - // - "colors" - // - "sizes" - // - "materials" - // - "patterns" - // - "conditions" - // - "attributes.key" - // - "pickupInStore" - // - "shipToStore" - // - "sameDayDelivery" - // - "nextDayDelivery" - // - "customFulfillment1" - // - "customFulfillment2" - // - "customFulfillment3" - // - "customFulfillment4" - // - "customFulfillment5" - // - "inventory(place_id,attributes.key)" + // * "brands" + // * "categories" + // * "genders" + // * "ageGroups" + // * "availability" + // * "colorFamilies" + // * "colors" + // * "sizes" + // * "materials" + // * "patterns" + // * "conditions" + // * "attributes.key" + // * "pickupInStore" + // * "shipToStore" + // * "sameDayDelivery" + // * "nextDayDelivery" + // * "customFulfillment1" + // * "customFulfillment2" + // * "customFulfillment3" + // * "customFulfillment4" + // * "customFulfillment5" + // * "inventory(place_id,attributes.key)" // // * numerical_field = - // - "price" - // - "discount" - // - "rating" - // - "ratingCount" - // - "attributes.key" - // - "inventory(place_id,price)" - // - "inventory(place_id,original_price)" - // - "inventory(place_id,attributes.key)" + // * "price" + // * "discount" + // * "rating" + // * "ratingCount" + // * "attributes.key" + // * "inventory(place_id,price)" + // * "inventory(place_id,original_price)" + // * "inventory(place_id,attributes.key)" Key string `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"` // Set only if values should be bucketized into intervals. Must be set // for facets with numerical values. Must not be set for facet with text @@ -1529,8 +1512,7 @@ type SearchRequest_FacetSpec_FacetKey struct { // * "value desc", which means order by // [SearchResponse.Facet.values.value][google.cloud.retail.v2alpha.SearchResponse.Facet.FacetValue.value] // descending. - // - // Only applies to textual facets. + // Only applies to textual facets. // // If not set, textual values are sorted in [natural // order](https://en.wikipedia.org/wiki/Natural_sort_order); numerical @@ -1679,10 +1661,9 @@ type SearchRequest_BoostSpec_ConditionBoostSpec struct { // // * To boost products with product ID "product_1" or "product_2", and // color - // - // "Red" or "Blue": - // * (id: ANY("product_1", "product_2")) AND (colorFamilies: - // ANY("Red","Blue")) + // "Red" or "Blue": + // * (id: ANY("product_1", "product_2")) AND (colorFamilies: + // ANY("Red","Blue")) Condition string `protobuf:"bytes,1,opt,name=condition,proto3" json:"condition,omitempty"` // Strength of the condition boost, which should be in [-1, 1]. Negative // boost means demotion. Default is 0.0. @@ -1808,14 +1789,14 @@ type SearchResponse_SearchResult struct { // there are two variants with colors "red" and "blue", the rollup values // are // - // { key: "colorFamilies" - // value { - // list_value { - // values { string_value: "red" } - // values { string_value: "blue" } - // } - // } - // } + // { key: "colorFamilies" + // value { + // list_value { + // values { string_value: "red" } + // values { string_value: "blue" } + // } + // } + // } // // For [FulfillmentInfo][google.cloud.retail.v2alpha.FulfillmentInfo], the // rollup values is a double value with type @@ -2031,7 +2012,6 @@ type SearchResponse_Facet_FacetValue struct { // A facet value which contains values. // // Types that are assignable to FacetValue: - // // *SearchResponse_Facet_FacetValue_Value // *SearchResponse_Facet_FacetValue_Interval FacetValue isSearchResponse_Facet_FacetValue_FacetValue `protobuf_oneof:"facet_value"` diff --git a/retail/apiv2alpha/retailpb/serving_config.pb.go b/retail/apiv2alpha/retailpb/serving_config.pb.go index 802ac978bf01..302add1ccd52 100644 --- a/retail/apiv2alpha/retailpb/serving_config.pb.go +++ b/retail/apiv2alpha/retailpb/serving_config.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/retail/v2alpha/serving_config.proto package retailpb @@ -70,8 +70,7 @@ type ServingConfig struct { // recommendation probability to be ordered by price, with the // highest-priced items first. This setting could result in a decrease in // click-through and conversion rates. - // - // Allowed values are: + // Allowed values are: // // * 'no-price-reranking' // * 'low-price-raranking' @@ -215,15 +214,14 @@ type ServingConfig struct { DiversityLevel string `protobuf:"bytes,8,opt,name=diversity_level,json=diversityLevel,proto3" json:"diversity_level,omitempty"` // Whether to add additional category filters on the 'similar-items' model. // If not specified, we enable it by default. + // Allowed values are: // - // Allowed values are: - // - // - 'no-category-match': No additional filtering of original results from - // the model and the customer's filters. - // - 'relaxed-category-match': Only keep results with categories that match - // at least one item categories in the PredictRequests's context item. - // - If customer also sends filters in the PredictRequest, then the results - // will satisfy both conditions (user given and category match). + // * 'no-category-match': No additional filtering of original results from + // the model and the customer's filters. + // * 'relaxed-category-match': Only keep results with categories that match + // at least one item categories in the PredictRequests's context item. + // * If customer also sends filters in the PredictRequest, then the results + // will satisfy both conditions (user given and category match). // // Can only be set if // [solution_types][google.cloud.retail.v2alpha.ServingConfig.solution_types] diff --git a/retail/apiv2alpha/retailpb/serving_config_service.pb.go b/retail/apiv2alpha/retailpb/serving_config_service.pb.go index 87ee2e41eb36..4c7caad7ba50 100644 --- a/retail/apiv2alpha/retailpb/serving_config_service.pb.go +++ b/retail/apiv2alpha/retailpb/serving_config_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/retail/v2alpha/serving_config_service.proto package retailpb diff --git a/retail/apiv2alpha/retailpb/user_event.pb.go b/retail/apiv2alpha/retailpb/user_event.pb.go index c66d71952fdd..8f5016746305 100644 --- a/retail/apiv2alpha/retailpb/user_event.pb.go +++ b/retail/apiv2alpha/retailpb/user_event.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/retail/v2alpha/user_event.proto package retailpb @@ -47,16 +47,16 @@ type UserEvent struct { // Required. User event type. Allowed values are: // - // - `add-to-cart`: Products being added to cart. - // - `category-page-view`: Special pages such as sale or promotion pages - // viewed. - // - `detail-page-view`: Products detail page viewed. - // - `home-page-view`: Homepage viewed. - // - `promotion-offered`: Promotion is offered to a user. - // - `promotion-not-offered`: Promotion is not offered to a user. - // - `purchase-complete`: User finishing a purchase. - // - `search`: Product search. - // - `shopping-cart-page-view`: User viewing a shopping cart. + // * `add-to-cart`: Products being added to cart. + // * `category-page-view`: Special pages such as sale or promotion pages + // viewed. + // * `detail-page-view`: Products detail page viewed. + // * `home-page-view`: Homepage viewed. + // * `promotion-offered`: Promotion is offered to a user. + // * `promotion-not-offered`: Promotion is not offered to a user. + // * `purchase-complete`: User finishing a purchase. + // * `search`: Product search. + // * `shopping-cart-page-view`: User viewing a shopping cart. EventType string `protobuf:"bytes,1,opt,name=event_type,json=eventType,proto3" json:"event_type,omitempty"` // Required. A unique identifier for tracking visitors. // @@ -151,12 +151,12 @@ type UserEvent struct { // This field needs to pass all below criteria, otherwise an INVALID_ARGUMENT // error is returned: // - // - The key must be a UTF-8 encoded string with a length limit of 5,000 - // characters. - // - For text attributes, at most 400 values are allowed. Empty values are not - // allowed. Each value must be a UTF-8 encoded string with a length limit of - // 256 characters. - // - For number attributes, at most 400 values are allowed. + // * The key must be a UTF-8 encoded string with a length limit of 5,000 + // characters. + // * For text attributes, at most 400 values are allowed. Empty values are not + // allowed. Each value must be a UTF-8 encoded string with a length limit of + // 256 characters. + // * For number attributes, at most 400 values are allowed. // // For product recommendations, an example of extra user information is // traffic_channel, which is how a user arrives at the site. Users can arrive diff --git a/retail/apiv2alpha/retailpb/user_event_service.pb.go b/retail/apiv2alpha/retailpb/user_event_service.pb.go index 7210be572ad9..39713ac44246 100644 --- a/retail/apiv2alpha/retailpb/user_event_service.pb.go +++ b/retail/apiv2alpha/retailpb/user_event_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/retail/v2alpha/user_event_service.proto package retailpb diff --git a/retail/apiv2alpha/search_client.go b/retail/apiv2alpha/search_client.go index ec72d6741afa..21b15724e531 100644 --- a/retail/apiv2alpha/search_client.go +++ b/retail/apiv2alpha/search_client.go @@ -482,6 +482,11 @@ func (c *searchRESTClient) Search(ctx context.Context, req *retailpb.SearchReque } baseUrl.Path += fmt.Sprintf("/v2alpha/%v:search", req.GetPlacement()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { @@ -546,6 +551,11 @@ func (c *searchRESTClient) GetOperation(ctx context.Context, req *longrunningpb. } baseUrl.Path += fmt.Sprintf("/v2alpha/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -613,6 +623,7 @@ func (c *searchRESTClient) ListOperations(ctx context.Context, req *longrunningp baseUrl.Path += fmt.Sprintf("/v2alpha/%v/operations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/retail/apiv2alpha/serving_config_client.go b/retail/apiv2alpha/serving_config_client.go index 5c19e3ad676d..9d0ffa50ede4 100644 --- a/retail/apiv2alpha/serving_config_client.go +++ b/retail/apiv2alpha/serving_config_client.go @@ -610,6 +610,7 @@ func (c *servingConfigRESTClient) CreateServingConfig(ctx context.Context, req * baseUrl.Path += fmt.Sprintf("/v2alpha/%v/servingConfigs", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("servingConfigId", fmt.Sprintf("%v", req.GetServingConfigId())) baseUrl.RawQuery = params.Encode() @@ -669,6 +670,11 @@ func (c *servingConfigRESTClient) DeleteServingConfig(ctx context.Context, req * } baseUrl.Path += fmt.Sprintf("/v2alpha/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -712,6 +718,7 @@ func (c *servingConfigRESTClient) UpdateServingConfig(ctx context.Context, req * baseUrl.Path += fmt.Sprintf("/v2alpha/%v", req.GetServingConfig().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -777,6 +784,11 @@ func (c *servingConfigRESTClient) GetServingConfig(ctx context.Context, req *ret } baseUrl.Path += fmt.Sprintf("/v2alpha/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -844,6 +856,7 @@ func (c *servingConfigRESTClient) ListServingConfigs(ctx context.Context, req *r baseUrl.Path += fmt.Sprintf("/v2alpha/%v/servingConfigs", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -929,6 +942,11 @@ func (c *servingConfigRESTClient) AddControl(ctx context.Context, req *retailpb. } baseUrl.Path += fmt.Sprintf("/v2alpha/%v:addControl", req.GetServingConfig()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "serving_config", url.QueryEscape(req.GetServingConfig()))) @@ -991,6 +1009,11 @@ func (c *servingConfigRESTClient) RemoveControl(ctx context.Context, req *retail } baseUrl.Path += fmt.Sprintf("/v2alpha/%v:removeControl", req.GetServingConfig()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "serving_config", url.QueryEscape(req.GetServingConfig()))) @@ -1044,6 +1067,11 @@ func (c *servingConfigRESTClient) GetOperation(ctx context.Context, req *longrun } baseUrl.Path += fmt.Sprintf("/v2alpha/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1111,6 +1139,7 @@ func (c *servingConfigRESTClient) ListOperations(ctx context.Context, req *longr baseUrl.Path += fmt.Sprintf("/v2alpha/%v/operations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/retail/apiv2alpha/user_event_client.go b/retail/apiv2alpha/user_event_client.go index 89e28d627ffb..62b27bdf03c7 100644 --- a/retail/apiv2alpha/user_event_client.go +++ b/retail/apiv2alpha/user_event_client.go @@ -726,6 +726,11 @@ func (c *userEventRESTClient) WriteUserEvent(ctx context.Context, req *retailpb. } baseUrl.Path += fmt.Sprintf("/v2alpha/%v/userEvents:write", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -784,6 +789,7 @@ func (c *userEventRESTClient) CollectUserEvent(ctx context.Context, req *retailp baseUrl.Path += fmt.Sprintf("/v2alpha/%v/userEvents:collect", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetEts() != 0 { params.Add("ets", fmt.Sprintf("%v", req.GetEts())) } @@ -856,6 +862,11 @@ func (c *userEventRESTClient) PurgeUserEvents(ctx context.Context, req *retailpb } baseUrl.Path += fmt.Sprintf("/v2alpha/%v/userEvents:purge", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -925,6 +936,11 @@ func (c *userEventRESTClient) ImportUserEvents(ctx context.Context, req *retailp } baseUrl.Path += fmt.Sprintf("/v2alpha/%v/userEvents:import", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -995,6 +1011,11 @@ func (c *userEventRESTClient) RejoinUserEvents(ctx context.Context, req *retailp } baseUrl.Path += fmt.Sprintf("/v2alpha/%v/userEvents:rejoin", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1052,6 +1073,11 @@ func (c *userEventRESTClient) GetOperation(ctx context.Context, req *longrunning } baseUrl.Path += fmt.Sprintf("/v2alpha/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1119,6 +1145,7 @@ func (c *userEventRESTClient) ListOperations(ctx context.Context, req *longrunni baseUrl.Path += fmt.Sprintf("/v2alpha/%v/operations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/retail/apiv2beta/catalog_client.go b/retail/apiv2beta/catalog_client.go index a5042fb9d43d..a7711e9448e8 100644 --- a/retail/apiv2beta/catalog_client.go +++ b/retail/apiv2beta/catalog_client.go @@ -1096,6 +1096,7 @@ func (c *catalogRESTClient) ListCatalogs(ctx context.Context, req *retailpb.List baseUrl.Path += fmt.Sprintf("/v2beta/%v/catalogs", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -1177,6 +1178,7 @@ func (c *catalogRESTClient) UpdateCatalog(ctx context.Context, req *retailpb.Upd baseUrl.Path += fmt.Sprintf("/v2beta/%v", req.GetCatalog().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -1280,6 +1282,11 @@ func (c *catalogRESTClient) SetDefaultBranch(ctx context.Context, req *retailpb. } baseUrl.Path += fmt.Sprintf("/v2beta/%v:setDefaultBranch", req.GetCatalog()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "catalog", url.QueryEscape(req.GetCatalog()))) @@ -1317,6 +1324,11 @@ func (c *catalogRESTClient) GetDefaultBranch(ctx context.Context, req *retailpb. } baseUrl.Path += fmt.Sprintf("/v2beta/%v:getDefaultBranch", req.GetCatalog()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "catalog", url.QueryEscape(req.GetCatalog()))) @@ -1370,6 +1382,11 @@ func (c *catalogRESTClient) GetCompletionConfig(ctx context.Context, req *retail } baseUrl.Path += fmt.Sprintf("/v2beta/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1432,6 +1449,7 @@ func (c *catalogRESTClient) UpdateCompletionConfig(ctx context.Context, req *ret baseUrl.Path += fmt.Sprintf("/v2beta/%v", req.GetCompletionConfig().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -1495,6 +1513,11 @@ func (c *catalogRESTClient) GetAttributesConfig(ctx context.Context, req *retail } baseUrl.Path += fmt.Sprintf("/v2beta/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1564,6 +1587,7 @@ func (c *catalogRESTClient) UpdateAttributesConfig(ctx context.Context, req *ret baseUrl.Path += fmt.Sprintf("/v2beta/%v", req.GetAttributesConfig().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -1638,6 +1662,11 @@ func (c *catalogRESTClient) AddCatalogAttribute(ctx context.Context, req *retail } baseUrl.Path += fmt.Sprintf("/v2beta/%v:addCatalogAttribute", req.GetAttributesConfig()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "attributes_config", url.QueryEscape(req.GetAttributesConfig()))) @@ -1702,6 +1731,11 @@ func (c *catalogRESTClient) RemoveCatalogAttribute(ctx context.Context, req *ret } baseUrl.Path += fmt.Sprintf("/v2beta/%v:removeCatalogAttribute", req.GetAttributesConfig()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "attributes_config", url.QueryEscape(req.GetAttributesConfig()))) @@ -1763,6 +1797,11 @@ func (c *catalogRESTClient) BatchRemoveCatalogAttributes(ctx context.Context, re } baseUrl.Path += fmt.Sprintf("/v2beta/%v:batchRemoveCatalogAttributes", req.GetAttributesConfig()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "attributes_config", url.QueryEscape(req.GetAttributesConfig()))) @@ -1829,6 +1868,11 @@ func (c *catalogRESTClient) ReplaceCatalogAttribute(ctx context.Context, req *re } baseUrl.Path += fmt.Sprintf("/v2beta/%v:replaceCatalogAttribute", req.GetAttributesConfig()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "attributes_config", url.QueryEscape(req.GetAttributesConfig()))) @@ -1882,6 +1926,11 @@ func (c *catalogRESTClient) GetOperation(ctx context.Context, req *longrunningpb } baseUrl.Path += fmt.Sprintf("/v2beta/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1949,6 +1998,7 @@ func (c *catalogRESTClient) ListOperations(ctx context.Context, req *longrunning baseUrl.Path += fmt.Sprintf("/v2beta/%v/operations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/retail/apiv2beta/completion_client.go b/retail/apiv2beta/completion_client.go index 4426243f863e..e359aceb78f3 100644 --- a/retail/apiv2beta/completion_client.go +++ b/retail/apiv2beta/completion_client.go @@ -548,14 +548,17 @@ func (c *completionRESTClient) CompleteQuery(ctx context.Context, req *retailpb. baseUrl.Path += fmt.Sprintf("/v2beta/%v:completeQuery", req.GetCatalog()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetDataset() != "" { params.Add("dataset", fmt.Sprintf("%v", req.GetDataset())) } if req.GetDeviceType() != "" { params.Add("deviceType", fmt.Sprintf("%v", req.GetDeviceType())) } - if req.GetLanguageCodes() != nil { - params.Add("languageCodes", fmt.Sprintf("%v", req.GetLanguageCodes())) + if items := req.GetLanguageCodes(); len(items) > 0 { + for _, item := range items { + params.Add("languageCodes", fmt.Sprintf("%v", item)) + } } if req.GetMaxSuggestions() != 0 { params.Add("maxSuggestions", fmt.Sprintf("%v", req.GetMaxSuggestions())) @@ -634,6 +637,11 @@ func (c *completionRESTClient) ImportCompletionData(ctx context.Context, req *re } baseUrl.Path += fmt.Sprintf("/v2beta/%v/completionData:import", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -691,6 +699,11 @@ func (c *completionRESTClient) GetOperation(ctx context.Context, req *longrunnin } baseUrl.Path += fmt.Sprintf("/v2beta/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -758,6 +771,7 @@ func (c *completionRESTClient) ListOperations(ctx context.Context, req *longrunn baseUrl.Path += fmt.Sprintf("/v2beta/%v/operations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/retail/apiv2beta/control_client.go b/retail/apiv2beta/control_client.go index dabee08d26ad..9d67834db138 100644 --- a/retail/apiv2beta/control_client.go +++ b/retail/apiv2beta/control_client.go @@ -550,6 +550,7 @@ func (c *controlRESTClient) CreateControl(ctx context.Context, req *retailpb.Cre baseUrl.Path += fmt.Sprintf("/v2beta/%v/controls", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("controlId", fmt.Sprintf("%v", req.GetControlId())) baseUrl.RawQuery = params.Encode() @@ -610,6 +611,11 @@ func (c *controlRESTClient) DeleteControl(ctx context.Context, req *retailpb.Del } baseUrl.Path += fmt.Sprintf("/v2beta/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -658,6 +664,7 @@ func (c *controlRESTClient) UpdateControl(ctx context.Context, req *retailpb.Upd baseUrl.Path += fmt.Sprintf("/v2beta/%v", req.GetControl().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -721,6 +728,11 @@ func (c *controlRESTClient) GetControl(ctx context.Context, req *retailpb.GetCon } baseUrl.Path += fmt.Sprintf("/v2beta/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -789,6 +801,7 @@ func (c *controlRESTClient) ListControls(ctx context.Context, req *retailpb.List baseUrl.Path += fmt.Sprintf("/v2beta/%v/controls", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -865,6 +878,11 @@ func (c *controlRESTClient) GetOperation(ctx context.Context, req *longrunningpb } baseUrl.Path += fmt.Sprintf("/v2beta/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -932,6 +950,7 @@ func (c *controlRESTClient) ListOperations(ctx context.Context, req *longrunning baseUrl.Path += fmt.Sprintf("/v2beta/%v/operations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/retail/apiv2beta/model_client.go b/retail/apiv2beta/model_client.go index 146d859f2338..39bb8dec1910 100644 --- a/retail/apiv2beta/model_client.go +++ b/retail/apiv2beta/model_client.go @@ -688,6 +688,7 @@ func (c *modelRESTClient) CreateModel(ctx context.Context, req *retailpb.CreateM baseUrl.Path += fmt.Sprintf("/v2beta/%v/models", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetDryRun() { params.Add("dryRun", fmt.Sprintf("%v", req.GetDryRun())) } @@ -757,6 +758,11 @@ func (c *modelRESTClient) PauseModel(ctx context.Context, req *retailpb.PauseMod } baseUrl.Path += fmt.Sprintf("/v2beta/%v:pause", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -816,6 +822,11 @@ func (c *modelRESTClient) ResumeModel(ctx context.Context, req *retailpb.ResumeM } baseUrl.Path += fmt.Sprintf("/v2beta/%v:resume", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -869,6 +880,11 @@ func (c *modelRESTClient) DeleteModel(ctx context.Context, req *retailpb.DeleteM } baseUrl.Path += fmt.Sprintf("/v2beta/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -918,6 +934,7 @@ func (c *modelRESTClient) ListModels(ctx context.Context, req *retailpb.ListMode baseUrl.Path += fmt.Sprintf("/v2beta/%v/models", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -1002,6 +1019,7 @@ func (c *modelRESTClient) UpdateModel(ctx context.Context, req *retailpb.UpdateM baseUrl.Path += fmt.Sprintf("/v2beta/%v", req.GetModel().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -1071,6 +1089,11 @@ func (c *modelRESTClient) TuneModel(ctx context.Context, req *retailpb.TuneModel } baseUrl.Path += fmt.Sprintf("/v2beta/%v:tune", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1128,6 +1151,11 @@ func (c *modelRESTClient) GetOperation(ctx context.Context, req *longrunningpb.G } baseUrl.Path += fmt.Sprintf("/v2beta/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1195,6 +1223,7 @@ func (c *modelRESTClient) ListOperations(ctx context.Context, req *longrunningpb baseUrl.Path += fmt.Sprintf("/v2beta/%v/operations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/retail/apiv2beta/prediction_client.go b/retail/apiv2beta/prediction_client.go index 8133b8be21a3..e7048d18e073 100644 --- a/retail/apiv2beta/prediction_client.go +++ b/retail/apiv2beta/prediction_client.go @@ -431,6 +431,11 @@ func (c *predictionRESTClient) Predict(ctx context.Context, req *retailpb.Predic } baseUrl.Path += fmt.Sprintf("/v2beta/%v:predict", req.GetPlacement()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "placement", url.QueryEscape(req.GetPlacement()))) @@ -484,6 +489,11 @@ func (c *predictionRESTClient) GetOperation(ctx context.Context, req *longrunnin } baseUrl.Path += fmt.Sprintf("/v2beta/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -551,6 +561,7 @@ func (c *predictionRESTClient) ListOperations(ctx context.Context, req *longrunn baseUrl.Path += fmt.Sprintf("/v2beta/%v/operations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/retail/apiv2beta/product_client.go b/retail/apiv2beta/product_client.go index ee1189ad0429..f82d3140234d 100644 --- a/retail/apiv2beta/product_client.go +++ b/retail/apiv2beta/product_client.go @@ -1228,6 +1228,7 @@ func (c *productRESTClient) CreateProduct(ctx context.Context, req *retailpb.Cre baseUrl.Path += fmt.Sprintf("/v2beta/%v/products", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("productId", fmt.Sprintf("%v", req.GetProductId())) baseUrl.RawQuery = params.Encode() @@ -1285,6 +1286,11 @@ func (c *productRESTClient) GetProduct(ctx context.Context, req *retailpb.GetPro } baseUrl.Path += fmt.Sprintf("/v2beta/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1352,6 +1358,7 @@ func (c *productRESTClient) ListProducts(ctx context.Context, req *retailpb.List baseUrl.Path += fmt.Sprintf("/v2beta/%v/products", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1443,6 +1450,7 @@ func (c *productRESTClient) UpdateProduct(ctx context.Context, req *retailpb.Upd baseUrl.Path += fmt.Sprintf("/v2beta/%v", req.GetProduct().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetAllowMissing() { params.Add("allowMissing", fmt.Sprintf("%v", req.GetAllowMissing())) } @@ -1509,6 +1517,11 @@ func (c *productRESTClient) DeleteProduct(ctx context.Context, req *retailpb.Del } baseUrl.Path += fmt.Sprintf("/v2beta/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1556,6 +1569,11 @@ func (c *productRESTClient) ImportProducts(ctx context.Context, req *retailpb.Im } baseUrl.Path += fmt.Sprintf("/v2beta/%v/products:import", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1670,6 +1688,11 @@ func (c *productRESTClient) SetInventory(ctx context.Context, req *retailpb.SetI } baseUrl.Path += fmt.Sprintf("/v2beta/%v:setInventory", req.GetInventory().GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "inventory.name", url.QueryEscape(req.GetInventory().GetName()))) @@ -1756,6 +1779,11 @@ func (c *productRESTClient) AddFulfillmentPlaces(ctx context.Context, req *retai } baseUrl.Path += fmt.Sprintf("/v2beta/%v:addFulfillmentPlaces", req.GetProduct()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "product", url.QueryEscape(req.GetProduct()))) @@ -1842,6 +1870,11 @@ func (c *productRESTClient) RemoveFulfillmentPlaces(ctx context.Context, req *re } baseUrl.Path += fmt.Sprintf("/v2beta/%v:removeFulfillmentPlaces", req.GetProduct()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "product", url.QueryEscape(req.GetProduct()))) @@ -1935,6 +1968,11 @@ func (c *productRESTClient) AddLocalInventories(ctx context.Context, req *retail } baseUrl.Path += fmt.Sprintf("/v2beta/%v:addLocalInventories", req.GetProduct()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "product", url.QueryEscape(req.GetProduct()))) @@ -2026,6 +2064,11 @@ func (c *productRESTClient) RemoveLocalInventories(ctx context.Context, req *ret } baseUrl.Path += fmt.Sprintf("/v2beta/%v:removeLocalInventories", req.GetProduct()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "product", url.QueryEscape(req.GetProduct()))) @@ -2083,6 +2126,11 @@ func (c *productRESTClient) GetOperation(ctx context.Context, req *longrunningpb } baseUrl.Path += fmt.Sprintf("/v2beta/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2150,6 +2198,7 @@ func (c *productRESTClient) ListOperations(ctx context.Context, req *longrunning baseUrl.Path += fmt.Sprintf("/v2beta/%v/operations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/retail/apiv2beta/retailpb/catalog.pb.go b/retail/apiv2beta/retailpb/catalog.pb.go index e90a89be0d48..1229fa529236 100644 --- a/retail/apiv2beta/retailpb/catalog.pb.go +++ b/retail/apiv2beta/retailpb/catalog.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/retail/v2beta/catalog.proto package retailpb @@ -320,17 +320,16 @@ type ProductLevelConfig struct { // // * `primary` (default): You can ingest // [Product][google.cloud.retail.v2beta.Product]s of all types. When - // - // ingesting a [Product][google.cloud.retail.v2beta.Product], its type will - // default to - // [Product.Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] - // if unset. - // - `variant` (incompatible with Retail Search): You can only - // ingest - // [Product.Type.VARIANT][google.cloud.retail.v2beta.Product.Type.VARIANT] - // [Product][google.cloud.retail.v2beta.Product]s. This means - // [Product.primary_product_id][google.cloud.retail.v2beta.Product.primary_product_id] - // cannot be empty. + // ingesting a [Product][google.cloud.retail.v2beta.Product], its type will + // default to + // [Product.Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] + // if unset. + // * `variant` (incompatible with Retail Search): You can only + // ingest + // [Product.Type.VARIANT][google.cloud.retail.v2beta.Product.Type.VARIANT] + // [Product][google.cloud.retail.v2beta.Product]s. This means + // [Product.primary_product_id][google.cloud.retail.v2beta.Product.primary_product_id] + // cannot be empty. // // If this field is set to an invalid value other than these, an // INVALID_ARGUMENT error is returned. @@ -348,10 +347,10 @@ type ProductLevelConfig struct { // imported as [Product.id][google.cloud.retail.v2beta.Product.id]. Acceptable // values are: // - // - `offerId` (default): Import `offerId` as the product ID. - // - `itemGroupId`: Import `itemGroupId` as the product ID. Notice that Retail - // API will choose one item from the ones with the same `itemGroupId`, and - // use it to represent the item group. + // * `offerId` (default): Import `offerId` as the product ID. + // * `itemGroupId`: Import `itemGroupId` as the product ID. Notice that Retail + // API will choose one item from the ones with the same `itemGroupId`, and + // use it to represent the item group. // // If this field is set to an invalid value other than these, an // INVALID_ARGUMENT error is returned. diff --git a/retail/apiv2beta/retailpb/catalog_service.pb.go b/retail/apiv2beta/retailpb/catalog_service.pb.go index 74119bbf1c30..c56b15bc7bd7 100644 --- a/retail/apiv2beta/retailpb/catalog_service.pb.go +++ b/retail/apiv2beta/retailpb/catalog_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/retail/v2beta/catalog_service.proto package retailpb @@ -1756,11 +1756,11 @@ type CatalogServiceClient interface { // // More specifically: // - // - PredictionService will only return product IDs from branch {newBranch}. - // - SearchService will only return product IDs from branch {newBranch} - // (if branch is not explicitly set). - // - UserEventService will only join events with products from branch - // {newBranch}. + // * PredictionService will only return product IDs from branch {newBranch}. + // * SearchService will only return product IDs from branch {newBranch} + // (if branch is not explicitly set). + // * UserEventService will only join events with products from branch + // {newBranch}. SetDefaultBranch(ctx context.Context, in *SetDefaultBranchRequest, opts ...grpc.CallOption) (*emptypb.Empty, error) // Get which branch is currently default branch set by // [CatalogService.SetDefaultBranch][google.cloud.retail.v2beta.CatalogService.SetDefaultBranch] @@ -1963,11 +1963,11 @@ type CatalogServiceServer interface { // // More specifically: // - // - PredictionService will only return product IDs from branch {newBranch}. - // - SearchService will only return product IDs from branch {newBranch} - // (if branch is not explicitly set). - // - UserEventService will only join events with products from branch - // {newBranch}. + // * PredictionService will only return product IDs from branch {newBranch}. + // * SearchService will only return product IDs from branch {newBranch} + // (if branch is not explicitly set). + // * UserEventService will only join events with products from branch + // {newBranch}. SetDefaultBranch(context.Context, *SetDefaultBranchRequest) (*emptypb.Empty, error) // Get which branch is currently default branch set by // [CatalogService.SetDefaultBranch][google.cloud.retail.v2beta.CatalogService.SetDefaultBranch] diff --git a/retail/apiv2beta/retailpb/common.pb.go b/retail/apiv2beta/retailpb/common.pb.go index 408b696255bd..513c7be85317 100644 --- a/retail/apiv2beta/retailpb/common.pb.go +++ b/retail/apiv2beta/retailpb/common.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/retail/v2beta/common.proto package retailpb @@ -339,7 +339,6 @@ type Rule struct { // An action must be provided. // // Types that are assignable to Action: - // // *Rule_BoostAction_ // *Rule_RedirectAction_ // *Rule_OnewaySynonymsAction_ @@ -988,7 +987,6 @@ type Interval struct { // Otherwise, an INVALID_ARGUMENT error is returned. // // Types that are assignable to Min: - // // *Interval_Minimum // *Interval_ExclusiveMinimum Min isInterval_Min `protobuf_oneof:"min"` @@ -999,7 +997,6 @@ type Interval struct { // Otherwise, an INVALID_ARGUMENT error is returned. // // Types that are assignable to Max: - // // *Interval_Maximum // *Interval_ExclusiveMaximum Max isInterval_Max `protobuf_oneof:"max"` @@ -1501,18 +1498,18 @@ type LocalInventory struct { // This field needs to pass all below criteria, otherwise an INVALID_ARGUMENT // error is returned: // - // - At most 30 attributes are allowed. - // - The key must be a UTF-8 encoded string with a length limit of 32 - // characters. - // - The key must match the pattern: `[a-zA-Z0-9][a-zA-Z0-9_]*`. For example, - // key0LikeThis or KEY_1_LIKE_THIS. - // - The attribute values must be of the same type (text or number). - // - Only 1 value is allowed for each attribute. - // - For text values, the length limit is 256 UTF-8 characters. - // - The attribute does not support search. The `searchable` field should be - // unset or set to false. - // - The max summed total bytes of custom attribute keys and values per - // product is 5MiB. + // * At most 30 attributes are allowed. + // * The key must be a UTF-8 encoded string with a length limit of 32 + // characters. + // * The key must match the pattern: `[a-zA-Z0-9][a-zA-Z0-9_]*`. For example, + // key0LikeThis or KEY_1_LIKE_THIS. + // * The attribute values must be of the same type (text or number). + // * Only 1 value is allowed for each attribute. + // * For text values, the length limit is 256 UTF-8 characters. + // * The attribute does not support search. The `searchable` field should be + // unset or set to false. + // * The max summed total bytes of custom attribute keys and values per + // product is 5MiB. Attributes map[string]*CustomAttribute `protobuf:"bytes,3,rep,name=attributes,proto3" json:"attributes,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` // Input only. Supported fulfillment types. Valid fulfillment type values // include commonly used types (such as pickup in store and same day @@ -1755,11 +1752,10 @@ type Rule_BoostAction struct { // // * To boost products with product ID "product_1" or "product_2", and // color - // - // "Red" or "Blue":
- // *(id: ANY("product_1", "product_2"))
* - // *AND
* - // *(colorFamilies: ANY("Red", "Blue"))
* + // "Red" or "Blue":
+ // *(id: ANY("product_1", "product_2"))
* + // *AND
* + // *(colorFamilies: ANY("Red", "Blue"))
* ProductsFilter string `protobuf:"bytes,2,opt,name=products_filter,json=productsFilter,proto3" json:"products_filter,omitempty"` } @@ -1836,17 +1832,14 @@ type Rule_FilterAction struct { // * Filter syntax is identical to // [SearchRequest.filter][google.cloud.retail.v2beta.SearchRequest.filter]. // See more - // - // details at the Retail Search - // [user guide](/retail/search/docs/filter-and-order#filter). - // + // details at the Retail Search + // [user guide](/retail/search/docs/filter-and-order#filter). // * To filter products with product ID "product_1" or "product_2", and // color - // - // "Red" or "Blue":
- // *(id: ANY("product_1", "product_2"))
* - // *AND
* - // *(colorFamilies: ANY("Red", "Blue"))
* + // "Red" or "Blue":
+ // *(id: ANY("product_1", "product_2"))
* + // *AND
* + // *(colorFamilies: ANY("Red", "Blue"))
* Filter string `protobuf:"bytes,1,opt,name=filter,proto3" json:"filter,omitempty"` } diff --git a/retail/apiv2beta/retailpb/completion_service.pb.go b/retail/apiv2beta/retailpb/completion_service.pb.go index f34ed7c4569d..09350d4bdefc 100644 --- a/retail/apiv2beta/retailpb/completion_service.pb.go +++ b/retail/apiv2beta/retailpb/completion_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/retail/v2beta/completion_service.proto package retailpb @@ -99,9 +99,9 @@ type CompleteQueryRequest struct { // // * user-data // - // - cloud-retail: - // This option requires enabling auto-learning function first. See - // [guidelines](https://cloud.google.com/retail/docs/completion-overview#generated-completion-dataset). + // * cloud-retail: + // This option requires enabling auto-learning function first. See + // [guidelines](https://cloud.google.com/retail/docs/completion-overview#generated-completion-dataset). Dataset string `protobuf:"bytes,6,opt,name=dataset,proto3" json:"dataset,omitempty"` // Completion max suggestions. If left unset or set to 0, then will fallback // to the configured value @@ -216,15 +216,15 @@ type CompleteQueryResponse struct { // field is set and [UserEvent][google.cloud.retail.v2beta.UserEvent] is // imported. The recent searches satisfy the follow rules: // - // - They are ordered from latest to oldest. + // * They are ordered from latest to oldest. // - // - They are matched with - // [CompleteQueryRequest.query][google.cloud.retail.v2beta.CompleteQueryRequest.query] - // case insensitively. + // * They are matched with + // [CompleteQueryRequest.query][google.cloud.retail.v2beta.CompleteQueryRequest.query] + // case insensitively. // - // - They are transformed to lower case. + // * They are transformed to lower case. // - // - They are UTF-8 safe. + // * They are UTF-8 safe. // // Recent searches are deduplicated. More recent searches will be reserved // when duplication happens. diff --git a/retail/apiv2beta/retailpb/control.pb.go b/retail/apiv2beta/retailpb/control.pb.go index d96b95ef335f..0289cd020d94 100644 --- a/retail/apiv2beta/retailpb/control.pb.go +++ b/retail/apiv2beta/retailpb/control.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/retail/v2beta/control.proto package retailpb @@ -51,7 +51,6 @@ type Control struct { // INVALID_ARGUMENT will be returned if either condition is violated. // // Types that are assignable to Control: - // // *Control_FacetSpec // *Control_Rule Control isControl_Control `protobuf_oneof:"control"` diff --git a/retail/apiv2beta/retailpb/control_service.pb.go b/retail/apiv2beta/retailpb/control_service.pb.go index 2f2997ffd79c..5cd8d317bdf1 100644 --- a/retail/apiv2beta/retailpb/control_service.pb.go +++ b/retail/apiv2beta/retailpb/control_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/retail/v2beta/control_service.proto package retailpb @@ -297,7 +297,7 @@ type ListControlsRequest struct { // // * List all the products under the parent branch if // [filter][google.cloud.retail.v2beta.ListControlsRequest.filter] is unset. - // - List controls that are used in a single ServingConfig: + // * List controls that are used in a single ServingConfig: // 'serving_config = "boosted_home_page_cvr"' Filter string `protobuf:"bytes,4,opt,name=filter,proto3" json:"filter,omitempty"` } diff --git a/retail/apiv2beta/retailpb/export_config.pb.go b/retail/apiv2beta/retailpb/export_config.pb.go index d767743c1c96..fdd0282d1343 100644 --- a/retail/apiv2beta/retailpb/export_config.pb.go +++ b/retail/apiv2beta/retailpb/export_config.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/retail/v2beta/export_config.proto package retailpb @@ -47,7 +47,6 @@ type ExportErrorsConfig struct { // Required. Errors destination. // // Types that are assignable to Destination: - // // *ExportErrorsConfig_GcsPrefix Destination isExportErrorsConfig_Destination `protobuf_oneof:"destination"` } diff --git a/retail/apiv2beta/retailpb/import_config.pb.go b/retail/apiv2beta/retailpb/import_config.pb.go index a75ad99e859f..9b47cff03720 100644 --- a/retail/apiv2beta/retailpb/import_config.pb.go +++ b/retail/apiv2beta/retailpb/import_config.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/retail/v2beta/import_config.proto package retailpb @@ -116,17 +116,16 @@ type GcsSource struct { // // * `product` (default): One JSON // [Product][google.cloud.retail.v2beta.Product] per line. Each product must - // - // have a valid [Product.id][google.cloud.retail.v2beta.Product.id]. - // - `product_merchant_center`: See [Importing catalog data from Merchant - // Center](https://cloud.google.com/retail/recommendations-ai/docs/upload-catalog#mc). + // have a valid [Product.id][google.cloud.retail.v2beta.Product.id]. + // * `product_merchant_center`: See [Importing catalog data from Merchant + // Center](https://cloud.google.com/retail/recommendations-ai/docs/upload-catalog#mc). // // Supported values for user events imports: // // * `user_event` (default): One JSON // [UserEvent][google.cloud.retail.v2beta.UserEvent] per line. - // - `user_event_ga360`: Using - // https://support.google.com/analytics/answer/3437719. + // * `user_event_ga360`: Using + // https://support.google.com/analytics/answer/3437719. // // Supported values for control imports: // @@ -196,7 +195,6 @@ type BigQuerySource struct { // is not partitioned. // // Types that are assignable to Partition: - // // *BigQuerySource_PartitionDate Partition isBigQuerySource_Partition `protobuf_oneof:"partition"` // The project ID (can be project # or ID) that the BigQuery source is in with @@ -219,21 +217,20 @@ type BigQuerySource struct { // // * `product` (default): One JSON // [Product][google.cloud.retail.v2beta.Product] per line. Each product must - // - // have a valid [Product.id][google.cloud.retail.v2beta.Product.id]. - // - `product_merchant_center`: See [Importing catalog data from Merchant - // Center](https://cloud.google.com/retail/recommendations-ai/docs/upload-catalog#mc). + // have a valid [Product.id][google.cloud.retail.v2beta.Product.id]. + // * `product_merchant_center`: See [Importing catalog data from Merchant + // Center](https://cloud.google.com/retail/recommendations-ai/docs/upload-catalog#mc). // // Supported values for user events imports: // // * `user_event` (default): One JSON // [UserEvent][google.cloud.retail.v2beta.UserEvent] per line. - // - `user_event_ga360`: - // The schema is available here: - // https://support.google.com/analytics/answer/3437719. - // - `user_event_ga4`: - // The schema is available here: - // https://support.google.com/analytics/answer/7029846. + // * `user_event_ga360`: + // The schema is available here: + // https://support.google.com/analytics/answer/3437719. + // * `user_event_ga4`: + // The schema is available here: + // https://support.google.com/analytics/answer/7029846. // // Supported values for auto-completion imports: // @@ -447,7 +444,6 @@ type ImportErrorsConfig struct { // Required. Errors destination. // // Types that are assignable to Destination: - // // *ImportErrorsConfig_GcsPrefix Destination isImportErrorsConfig_Destination `protobuf_oneof:"destination"` } @@ -785,7 +781,6 @@ type ProductInputConfig struct { // Required. The source of the input. // // Types that are assignable to Source: - // // *ProductInputConfig_ProductInlineSource // *ProductInputConfig_GcsSource // *ProductInputConfig_BigQuerySource @@ -886,7 +881,6 @@ type UserEventInputConfig struct { // The source of the input. // // Types that are assignable to Source: - // // *UserEventInputConfig_UserEventInlineSource // *UserEventInputConfig_GcsSource // *UserEventInputConfig_BigQuerySource @@ -995,7 +989,6 @@ type CompletionDataInputConfig struct { // * `allowlist`: One JSON allow suggestion per line. // // Types that are assignable to Source: - // // *CompletionDataInputConfig_BigQuerySource Source isCompletionDataInputConfig_Source `protobuf_oneof:"source"` } diff --git a/retail/apiv2beta/retailpb/model.pb.go b/retail/apiv2beta/retailpb/model.pb.go index 00778b07c4af..620feb19ce0a 100644 --- a/retail/apiv2beta/retailpb/model.pb.go +++ b/retail/apiv2beta/retailpb/model.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/retail/v2beta/model.proto package retailpb @@ -332,8 +332,7 @@ type Model struct { // Currently supported // values: `ctr`, `cvr`, `revenue-per-order`. // - // If not specified, we choose default based on model type. - // + // If not specified, we choose default based on model type. // Default depends on type of recommendation: // // `recommended-for-you` => `ctr` diff --git a/retail/apiv2beta/retailpb/model_service.pb.go b/retail/apiv2beta/retailpb/model_service.pb.go index 770e4876a86e..1a5c765b78f7 100644 --- a/retail/apiv2beta/retailpb/model_service.pb.go +++ b/retail/apiv2beta/retailpb/model_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/retail/v2beta/model_service.proto package retailpb diff --git a/retail/apiv2beta/retailpb/prediction_service.pb.go b/retail/apiv2beta/retailpb/prediction_service.pb.go index 3c515431a440..c995792fdd08 100644 --- a/retail/apiv2beta/retailpb/prediction_service.pb.go +++ b/retail/apiv2beta/retailpb/prediction_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/retail/v2beta/prediction_service.proto package retailpb @@ -89,25 +89,25 @@ type PredictRequest struct { // Filter for restricting prediction results with a length limit of 5,000 // characters. Accepts values for tags and the `filterOutOfStockItems` flag. // - // - Tag expressions. Restricts predictions to products that match all of the - // specified tags. Boolean operators `OR` and `NOT` are supported if the - // expression is enclosed in parentheses, and must be separated from the - // tag values by a space. `-"tagA"` is also supported and is equivalent to - // `NOT "tagA"`. Tag values must be double quoted UTF-8 encoded strings - // with a size limit of 1,000 characters. + // * Tag expressions. Restricts predictions to products that match all of the + // specified tags. Boolean operators `OR` and `NOT` are supported if the + // expression is enclosed in parentheses, and must be separated from the + // tag values by a space. `-"tagA"` is also supported and is equivalent to + // `NOT "tagA"`. Tag values must be double quoted UTF-8 encoded strings + // with a size limit of 1,000 characters. // - // Note: "Recently viewed" models don't support tag filtering at the - // moment. + // Note: "Recently viewed" models don't support tag filtering at the + // moment. // - // - filterOutOfStockItems. Restricts predictions to products that do not - // have a - // stockState value of OUT_OF_STOCK. + // * filterOutOfStockItems. Restricts predictions to products that do not + // have a + // stockState value of OUT_OF_STOCK. // // Examples: // - // - tag=("Red" OR "Blue") tag="New-Arrival" tag=(NOT "promotional") - // - filterOutOfStockItems tag=(-"promotional") - // - filterOutOfStockItems + // * tag=("Red" OR "Blue") tag="New-Arrival" tag=(NOT "promotional") + // * filterOutOfStockItems tag=(-"promotional") + // * filterOutOfStockItems // // If your filter blocks all prediction results, the API will return generic // (unfiltered) popular products. If you only want results strictly matching @@ -120,9 +120,9 @@ type PredictRequest struct { // attribute-based expressions are expected instead of the above described // tag-based syntax. Examples: // - // - (colors: ANY("Red", "Blue")) AND NOT (categories: ANY("Phones")) - // - (availability: ANY("IN_STOCK")) AND - // (colors: ANY("Red") OR categories: ANY("Phones")) + // * (colors: ANY("Red", "Blue")) AND NOT (categories: ANY("Phones")) + // * (availability: ANY("IN_STOCK")) AND + // (colors: ANY("Red") OR categories: ANY("Phones")) Filter string `protobuf:"bytes,5,opt,name=filter,proto3" json:"filter,omitempty"` // Use validate only mode for this prediction query. If set to true, a // dummy model will be used that returns arbitrary products. @@ -133,43 +133,43 @@ type PredictRequest struct { // // Allowed values: // - // - `returnProduct`: Boolean. If set to true, the associated product - // object will be returned in the `results.metadata` field in the - // prediction response. - // - `returnScore`: Boolean. If set to true, the prediction 'score' - // corresponding to each returned product will be set in the - // `results.metadata` field in the prediction response. The given - // 'score' indicates the probability of an product being clicked/purchased - // given the user's context and history. - // - `strictFiltering`: Boolean. True by default. If set to false, the service - // will return generic (unfiltered) popular products instead of empty if - // your filter blocks all prediction results. - // - `priceRerankLevel`: String. Default empty. If set to be non-empty, then - // it needs to be one of {'no-price-reranking', 'low-price-reranking', - // 'medium-price-reranking', 'high-price-reranking'}. This gives - // request-level control and adjusts prediction results based on product - // price. - // - `diversityLevel`: String. Default empty. If set to be non-empty, then - // it needs to be one of {'no-diversity', 'low-diversity', - // 'medium-diversity', 'high-diversity', 'auto-diversity'}. This gives - // request-level control and adjusts prediction results based on product - // category. - // - `filterSyntaxV2`: Boolean. False by default. If set to true, the `filter` - // field is interpreteted according to the new, attribute-based syntax. + // * `returnProduct`: Boolean. If set to true, the associated product + // object will be returned in the `results.metadata` field in the + // prediction response. + // * `returnScore`: Boolean. If set to true, the prediction 'score' + // corresponding to each returned product will be set in the + // `results.metadata` field in the prediction response. The given + // 'score' indicates the probability of an product being clicked/purchased + // given the user's context and history. + // * `strictFiltering`: Boolean. True by default. If set to false, the service + // will return generic (unfiltered) popular products instead of empty if + // your filter blocks all prediction results. + // * `priceRerankLevel`: String. Default empty. If set to be non-empty, then + // it needs to be one of {'no-price-reranking', 'low-price-reranking', + // 'medium-price-reranking', 'high-price-reranking'}. This gives + // request-level control and adjusts prediction results based on product + // price. + // * `diversityLevel`: String. Default empty. If set to be non-empty, then + // it needs to be one of {'no-diversity', 'low-diversity', + // 'medium-diversity', 'high-diversity', 'auto-diversity'}. This gives + // request-level control and adjusts prediction results based on product + // category. + // * `filterSyntaxV2`: Boolean. False by default. If set to true, the `filter` + // field is interpreteted according to the new, attribute-based syntax. Params map[string]*structpb.Value `protobuf:"bytes,7,rep,name=params,proto3" json:"params,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` // The labels applied to a resource must meet the following requirements: // - // - Each resource can have multiple labels, up to a maximum of 64. - // - Each label must be a key-value pair. - // - Keys have a minimum length of 1 character and a maximum length of 63 - // characters and cannot be empty. Values can be empty and have a maximum - // length of 63 characters. - // - Keys and values can contain only lowercase letters, numeric characters, - // underscores, and dashes. All characters must use UTF-8 encoding, and - // international characters are allowed. - // - The key portion of a label must be unique. However, you can use the same - // key with multiple resources. - // - Keys must start with a lowercase letter or international character. + // * Each resource can have multiple labels, up to a maximum of 64. + // * Each label must be a key-value pair. + // * Keys have a minimum length of 1 character and a maximum length of 63 + // characters and cannot be empty. Values can be empty and have a maximum + // length of 63 characters. + // * Keys and values can contain only lowercase letters, numeric characters, + // underscores, and dashes. All characters must use UTF-8 encoding, and + // international characters are allowed. + // * The key portion of a label must be unique. However, you can use the same + // key with multiple resources. + // * Keys must start with a lowercase letter or international character. // // See [Google Cloud // Document](https://cloud.google.com/resource-manager/docs/creating-managing-labels#requirements) @@ -358,10 +358,10 @@ type PredictResponse_PredictionResult struct { // // Possible values: // - // - `product`: JSON representation of the product. Is set if - // `returnProduct` is set to true in `PredictRequest.params`. - // - `score`: Prediction score in double value. Is set if - // `returnScore` is set to true in `PredictRequest.params`. + // * `product`: JSON representation of the product. Is set if + // `returnProduct` is set to true in `PredictRequest.params`. + // * `score`: Prediction score in double value. Is set if + // `returnScore` is set to true in `PredictRequest.params`. Metadata map[string]*structpb.Value `protobuf:"bytes,2,rep,name=metadata,proto3" json:"metadata,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` } diff --git a/retail/apiv2beta/retailpb/product.pb.go b/retail/apiv2beta/retailpb/product.pb.go index b1aad5075ebd..af9981cd12bc 100644 --- a/retail/apiv2beta/retailpb/product.pb.go +++ b/retail/apiv2beta/retailpb/product.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/retail/v2beta/product.proto package retailpb @@ -189,7 +189,6 @@ type Product struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Expiration: - // // *Product_ExpireTime // *Product_Ttl Expiration isProduct_Expiration `protobuf_oneof:"expiration"` @@ -268,6 +267,7 @@ type Product struct { // belonging to several parallel categories. Strongly recommended using the // full path for better search / recommendation quality. // + // // To represent full path of category, use '>' sign to separate different // hierarchies. If '>' is part of the category name, replace it with // other character(s). @@ -277,10 +277,10 @@ type Product struct { // ["Sports & Fitness" -> "Athletic Clothing" -> "Shoes"], it could be // represented as: // - // "categories": [ - // "Shoes & Accessories > Shoes", - // "Sports & Fitness > Athletic Clothing > Shoes" - // ] + // "categories": [ + // "Shoes & Accessories > Shoes", + // "Sports & Fitness > Athletic Clothing > Shoes" + // ] // // Must be set for // [Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] @@ -358,16 +358,16 @@ type Product struct { // This field needs to pass all below criteria, otherwise an INVALID_ARGUMENT // error is returned: // - // - Max entries count: 200. - // - The key must be a UTF-8 encoded string with a length limit of 128 - // characters. - // - For indexable attribute, the key must match the pattern: - // `[a-zA-Z0-9][a-zA-Z0-9_]*`. For example, `key0LikeThis` or - // `KEY_1_LIKE_THIS`. - // - For text attributes, at most 400 values are allowed. Empty values are not - // allowed. Each value must be a non-empty UTF-8 encoded string with a - // length limit of 256 characters. - // - For number attributes, at most 400 values are allowed. + // * Max entries count: 200. + // * The key must be a UTF-8 encoded string with a length limit of 128 + // characters. + // * For indexable attribute, the key must match the pattern: + // `[a-zA-Z0-9][a-zA-Z0-9_]*`. For example, `key0LikeThis` or + // `KEY_1_LIKE_THIS`. + // * For text attributes, at most 400 values are allowed. Empty values are not + // allowed. Each value must be a non-empty UTF-8 encoded string with a + // length limit of 256 characters. + // * For number attributes, at most 400 values are allowed. Attributes map[string]*CustomAttribute `protobuf:"bytes,12,rep,name=attributes,proto3" json:"attributes,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` // Custom tags associated with the product. // diff --git a/retail/apiv2beta/retailpb/product_service.pb.go b/retail/apiv2beta/retailpb/product_service.pb.go index 6eb920f48d25..9a2073cb2891 100644 --- a/retail/apiv2beta/retailpb/product_service.pb.go +++ b/retail/apiv2beta/retailpb/product_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/retail/v2beta/product_service.proto package retailpb @@ -393,24 +393,19 @@ type ListProductsRequest struct { // * List // [Product.Type.VARIANT][google.cloud.retail.v2beta.Product.Type.VARIANT] // [Product][google.cloud.retail.v2beta.Product]s sharing the same - // - // [Product.Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] - // [Product][google.cloud.retail.v2beta.Product]. For example: - // `primary_product_id = "some_product_id"` - // + // [Product.Type.PRIMARY][google.cloud.retail.v2beta.Product.Type.PRIMARY] + // [Product][google.cloud.retail.v2beta.Product]. For example: + // `primary_product_id = "some_product_id"` // * List [Product][google.cloud.retail.v2beta.Product]s bundled in a // [Product.Type.COLLECTION][google.cloud.retail.v2beta.Product.Type.COLLECTION] // [Product][google.cloud.retail.v2beta.Product]. - // - // For example: - // `collection_product_id = "some_product_id"` - // + // For example: + // `collection_product_id = "some_product_id"` // * List [Product][google.cloud.retail.v2beta.Product]s with a partibular // type. For example: - // - // `type = "PRIMARY"` - // `type = "VARIANT"` - // `type = "COLLECTION"` + // `type = "PRIMARY"` + // `type = "VARIANT"` + // `type = "COLLECTION"` // // If the field is unrecognizable, an INVALID_ARGUMENT error is returned. // diff --git a/retail/apiv2beta/retailpb/promotion.pb.go b/retail/apiv2beta/retailpb/promotion.pb.go index 9ab854a1f1f4..25f6cbd6f377 100644 --- a/retail/apiv2beta/retailpb/promotion.pb.go +++ b/retail/apiv2beta/retailpb/promotion.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/retail/v2beta/promotion.proto package retailpb diff --git a/retail/apiv2beta/retailpb/purge_config.pb.go b/retail/apiv2beta/retailpb/purge_config.pb.go index f388d3ae2511..cc56bf7fa0eb 100644 --- a/retail/apiv2beta/retailpb/purge_config.pb.go +++ b/retail/apiv2beta/retailpb/purge_config.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/retail/v2beta/purge_config.proto package retailpb @@ -93,21 +93,21 @@ type PurgeUserEventsRequest struct { // * `eventType`: Double quoted // [UserEvent.event_type][google.cloud.retail.v2beta.UserEvent.event_type] // string. - // - `eventTime`: in ISO 8601 "zulu" format. - // - `visitorId`: Double quoted string. Specifying this will delete all - // events associated with a visitor. - // - `userId`: Double quoted string. Specifying this will delete all events - // associated with a user. + // * `eventTime`: in ISO 8601 "zulu" format. + // * `visitorId`: Double quoted string. Specifying this will delete all + // events associated with a visitor. + // * `userId`: Double quoted string. Specifying this will delete all events + // associated with a user. // // Examples: // - // - Deleting all events in a time range: - // `eventTime > "2012-04-23T18:25:43.511Z" - // eventTime < "2012-04-23T18:30:43.511Z"` - // - Deleting specific eventType in time range: - // `eventTime > "2012-04-23T18:25:43.511Z" eventType = "detail-page-view"` - // - Deleting all events for a specific visitor: - // `visitorId = "visitor1024"` + // * Deleting all events in a time range: + // `eventTime > "2012-04-23T18:25:43.511Z" + // eventTime < "2012-04-23T18:30:43.511Z"` + // * Deleting specific eventType in time range: + // `eventTime > "2012-04-23T18:25:43.511Z" eventType = "detail-page-view"` + // * Deleting all events for a specific visitor: + // `visitorId = "visitor1024"` // // The filtering fields are assumed to have an implicit AND. Filter string `protobuf:"bytes,2,opt,name=filter,proto3" json:"filter,omitempty"` diff --git a/retail/apiv2beta/retailpb/search_service.pb.go b/retail/apiv2beta/retailpb/search_service.pb.go index 91f4c673be09..f2537448eb67 100644 --- a/retail/apiv2beta/retailpb/search_service.pb.go +++ b/retail/apiv2beta/retailpb/search_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/retail/v2beta/search_service.proto package retailpb @@ -487,72 +487,54 @@ type SearchRequest struct { // // Supported keys are: // - // - colorFamilies - // - price - // - originalPrice - // - discount - // - variantId - // - inventory(place_id,price) - // - inventory(place_id,original_price) - // - inventory(place_id,attributes.key), where key is any key in the - // [Product.local_inventories.attributes][google.cloud.retail.v2beta.LocalInventory.attributes] - // map. - // - attributes.key, where key is any key in the - // [Product.attributes][google.cloud.retail.v2beta.Product.attributes] map. - // - pickupInStore.id, where id is any - // + // * colorFamilies + // * price + // * originalPrice + // * discount + // * variantId + // * inventory(place_id,price) + // * inventory(place_id,original_price) + // * inventory(place_id,attributes.key), where key is any key in the + // [Product.local_inventories.attributes][google.cloud.retail.v2beta.LocalInventory.attributes] + // map. + // * attributes.key, where key is any key in the + // [Product.attributes][google.cloud.retail.v2beta.Product.attributes] map. + // * pickupInStore.id, where id is any // [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] // for [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] - // - // "pickup-in-store". - // + // "pickup-in-store". // * shipToStore.id, where id is any // [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] // for [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] - // - // "ship-to-store". - // + // "ship-to-store". // * sameDayDelivery.id, where id is any // [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] // for [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] - // - // "same-day-delivery". - // + // "same-day-delivery". // * nextDayDelivery.id, where id is any // [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] // for [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] - // - // "next-day-delivery". - // + // "next-day-delivery". // * customFulfillment1.id, where id is any // [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] // for [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] - // - // "custom-type-1". - // + // "custom-type-1". // * customFulfillment2.id, where id is any // [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] // for [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] - // - // "custom-type-2". - // + // "custom-type-2". // * customFulfillment3.id, where id is any // [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] // for [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] - // - // "custom-type-3". - // + // "custom-type-3". // * customFulfillment4.id, where id is any // [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] // for [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] - // - // "custom-type-4". - // + // "custom-type-4". // * customFulfillment5.id, where id is any // [FulfillmentInfo.place_ids][google.cloud.retail.v2beta.FulfillmentInfo.place_ids] // for [FulfillmentInfo.type][google.cloud.retail.v2beta.FulfillmentInfo.type] - // - // "custom-type-5". + // "custom-type-5". // // If this field is set to an invalid value other than these, an // INVALID_ARGUMENT error is returned. @@ -586,17 +568,17 @@ type SearchRequest struct { PersonalizationSpec *SearchRequest_PersonalizationSpec `protobuf:"bytes,32,opt,name=personalization_spec,json=personalizationSpec,proto3" json:"personalization_spec,omitempty"` // The labels applied to a resource must meet the following requirements: // - // - Each resource can have multiple labels, up to a maximum of 64. - // - Each label must be a key-value pair. - // - Keys have a minimum length of 1 character and a maximum length of 63 - // characters and cannot be empty. Values can be empty and have a maximum - // length of 63 characters. - // - Keys and values can contain only lowercase letters, numeric characters, - // underscores, and dashes. All characters must use UTF-8 encoding, and - // international characters are allowed. - // - The key portion of a label must be unique. However, you can use the same - // key with multiple resources. - // - Keys must start with a lowercase letter or international character. + // * Each resource can have multiple labels, up to a maximum of 64. + // * Each label must be a key-value pair. + // * Keys have a minimum length of 1 character and a maximum length of 63 + // characters and cannot be empty. Values can be empty and have a maximum + // length of 63 characters. + // * Keys and values can contain only lowercase letters, numeric characters, + // underscores, and dashes. All characters must use UTF-8 encoding, and + // international characters are allowed. + // * The key portion of a label must be unique. However, you can use the same + // key with multiple resources. + // * Keys must start with a lowercase letter or international character. // // See [Google Cloud // Document](https://cloud.google.com/resource-manager/docs/creating-managing-labels#requirements) @@ -953,6 +935,7 @@ type SearchRequest_FacetSpec struct { Limit int32 `protobuf:"varint,2,opt,name=limit,proto3" json:"limit,omitempty"` // List of keys to exclude when faceting. // + // // By default, // [FacetKey.key][google.cloud.retail.v2beta.SearchRequest.FacetSpec.FacetKey.key] // is not excluded from the filter unless it is listed in this field. @@ -1366,38 +1349,38 @@ type SearchRequest_FacetSpec_FacetKey struct { // is not specified: // // * textual_field = - // - "brands" - // - "categories" - // - "genders" - // - "ageGroups" - // - "availability" - // - "colorFamilies" - // - "colors" - // - "sizes" - // - "materials" - // - "patterns" - // - "conditions" - // - "attributes.key" - // - "pickupInStore" - // - "shipToStore" - // - "sameDayDelivery" - // - "nextDayDelivery" - // - "customFulfillment1" - // - "customFulfillment2" - // - "customFulfillment3" - // - "customFulfillment4" - // - "customFulfillment5" - // - "inventory(place_id,attributes.key)" + // * "brands" + // * "categories" + // * "genders" + // * "ageGroups" + // * "availability" + // * "colorFamilies" + // * "colors" + // * "sizes" + // * "materials" + // * "patterns" + // * "conditions" + // * "attributes.key" + // * "pickupInStore" + // * "shipToStore" + // * "sameDayDelivery" + // * "nextDayDelivery" + // * "customFulfillment1" + // * "customFulfillment2" + // * "customFulfillment3" + // * "customFulfillment4" + // * "customFulfillment5" + // * "inventory(place_id,attributes.key)" // // * numerical_field = - // - "price" - // - "discount" - // - "rating" - // - "ratingCount" - // - "attributes.key" - // - "inventory(place_id,price)" - // - "inventory(place_id,original_price)" - // - "inventory(place_id,attributes.key)" + // * "price" + // * "discount" + // * "rating" + // * "ratingCount" + // * "attributes.key" + // * "inventory(place_id,price)" + // * "inventory(place_id,original_price)" + // * "inventory(place_id,attributes.key)" Key string `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"` // Set only if values should be bucketized into intervals. Must be set // for facets with numerical values. Must not be set for facet with text @@ -1457,8 +1440,7 @@ type SearchRequest_FacetSpec_FacetKey struct { // * "value desc", which means order by // [SearchResponse.Facet.values.value][google.cloud.retail.v2beta.SearchResponse.Facet.FacetValue.value] // descending. - // - // Only applies to textual facets. + // Only applies to textual facets. // // If not set, textual values are sorted in [natural // order](https://en.wikipedia.org/wiki/Natural_sort_order); numerical @@ -1607,10 +1589,9 @@ type SearchRequest_BoostSpec_ConditionBoostSpec struct { // // * To boost products with product ID "product_1" or "product_2", and // color - // - // "Red" or "Blue": - // * (id: ANY("product_1", "product_2")) AND (colorFamilies: - // ANY("Red","Blue")) + // "Red" or "Blue": + // * (id: ANY("product_1", "product_2")) AND (colorFamilies: + // ANY("Red","Blue")) Condition string `protobuf:"bytes,1,opt,name=condition,proto3" json:"condition,omitempty"` // Strength of the condition boost, which should be in [-1, 1]. Negative // boost means demotion. Default is 0.0. @@ -1736,14 +1717,14 @@ type SearchResponse_SearchResult struct { // there are two variants with colors "red" and "blue", the rollup values // are // - // { key: "colorFamilies" - // value { - // list_value { - // values { string_value: "red" } - // values { string_value: "blue" } - // } - // } - // } + // { key: "colorFamilies" + // value { + // list_value { + // values { string_value: "red" } + // values { string_value: "blue" } + // } + // } + // } // // For [FulfillmentInfo][google.cloud.retail.v2beta.FulfillmentInfo], the // rollup values is a double value with type @@ -1980,7 +1961,6 @@ type SearchResponse_Facet_FacetValue struct { // A facet value which contains values. // // Types that are assignable to FacetValue: - // // *SearchResponse_Facet_FacetValue_Value // *SearchResponse_Facet_FacetValue_Interval FacetValue isSearchResponse_Facet_FacetValue_FacetValue `protobuf_oneof:"facet_value"` diff --git a/retail/apiv2beta/retailpb/serving_config.pb.go b/retail/apiv2beta/retailpb/serving_config.pb.go index 666dfd173ff7..c92f65dc56df 100644 --- a/retail/apiv2beta/retailpb/serving_config.pb.go +++ b/retail/apiv2beta/retailpb/serving_config.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/retail/v2beta/serving_config.proto package retailpb @@ -123,8 +123,7 @@ type ServingConfig struct { // recommendation probability to be ordered by price, with the // highest-priced items first. This setting could result in a decrease in // click-through and conversion rates. - // - // Allowed values are: + // Allowed values are: // // * `no-price-reranking` // * `low-price-raranking` @@ -270,15 +269,14 @@ type ServingConfig struct { DiversityType ServingConfig_DiversityType `protobuf:"varint,20,opt,name=diversity_type,json=diversityType,proto3,enum=google.cloud.retail.v2beta.ServingConfig_DiversityType" json:"diversity_type,omitempty"` // Whether to add additional category filters on the `similar-items` model. // If not specified, we enable it by default. + // Allowed values are: // - // Allowed values are: - // - // - `no-category-match`: No additional filtering of original results from - // the model and the customer's filters. - // - `relaxed-category-match`: Only keep results with categories that match - // at least one item categories in the PredictRequests's context item. - // - If customer also sends filters in the PredictRequest, then the results - // will satisfy both conditions (user given and category match). + // * `no-category-match`: No additional filtering of original results from + // the model and the customer's filters. + // * `relaxed-category-match`: Only keep results with categories that match + // at least one item categories in the PredictRequests's context item. + // * If customer also sends filters in the PredictRequest, then the results + // will satisfy both conditions (user given and category match). // // Can only be set if // [solution_types][google.cloud.retail.v2beta.ServingConfig.solution_types] diff --git a/retail/apiv2beta/retailpb/serving_config_service.pb.go b/retail/apiv2beta/retailpb/serving_config_service.pb.go index 11a4553a85dc..2dd1a10957c7 100644 --- a/retail/apiv2beta/retailpb/serving_config_service.pb.go +++ b/retail/apiv2beta/retailpb/serving_config_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/retail/v2beta/serving_config_service.proto package retailpb diff --git a/retail/apiv2beta/retailpb/user_event.pb.go b/retail/apiv2beta/retailpb/user_event.pb.go index 576eb679120b..046e58ae469f 100644 --- a/retail/apiv2beta/retailpb/user_event.pb.go +++ b/retail/apiv2beta/retailpb/user_event.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/retail/v2beta/user_event.proto package retailpb @@ -47,16 +47,16 @@ type UserEvent struct { // Required. User event type. Allowed values are: // - // - `add-to-cart`: Products being added to cart. - // - `category-page-view`: Special pages such as sale or promotion pages - // viewed. - // - `detail-page-view`: Products detail page viewed. - // - `home-page-view`: Homepage viewed. - // - `promotion-offered`: Promotion is offered to a user. - // - `promotion-not-offered`: Promotion is not offered to a user. - // - `purchase-complete`: User finishing a purchase. - // - `search`: Product search. - // - `shopping-cart-page-view`: User viewing a shopping cart. + // * `add-to-cart`: Products being added to cart. + // * `category-page-view`: Special pages such as sale or promotion pages + // viewed. + // * `detail-page-view`: Products detail page viewed. + // * `home-page-view`: Homepage viewed. + // * `promotion-offered`: Promotion is offered to a user. + // * `promotion-not-offered`: Promotion is not offered to a user. + // * `purchase-complete`: User finishing a purchase. + // * `search`: Product search. + // * `shopping-cart-page-view`: User viewing a shopping cart. EventType string `protobuf:"bytes,1,opt,name=event_type,json=eventType,proto3" json:"event_type,omitempty"` // Required. A unique identifier for tracking visitors. // @@ -151,12 +151,12 @@ type UserEvent struct { // This field needs to pass all below criteria, otherwise an INVALID_ARGUMENT // error is returned: // - // - The key must be a UTF-8 encoded string with a length limit of 5,000 - // characters. - // - For text attributes, at most 400 values are allowed. Empty values are not - // allowed. Each value must be a UTF-8 encoded string with a length limit of - // 256 characters. - // - For number attributes, at most 400 values are allowed. + // * The key must be a UTF-8 encoded string with a length limit of 5,000 + // characters. + // * For text attributes, at most 400 values are allowed. Empty values are not + // allowed. Each value must be a UTF-8 encoded string with a length limit of + // 256 characters. + // * For number attributes, at most 400 values are allowed. // // For product recommendations, an example of extra user information is // traffic_channel, which is how a user arrives at the site. Users can arrive diff --git a/retail/apiv2beta/retailpb/user_event_service.pb.go b/retail/apiv2beta/retailpb/user_event_service.pb.go index 87888bc18c76..2b61f7b33c61 100644 --- a/retail/apiv2beta/retailpb/user_event_service.pb.go +++ b/retail/apiv2beta/retailpb/user_event_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/retail/v2beta/user_event_service.proto package retailpb diff --git a/retail/apiv2beta/search_client.go b/retail/apiv2beta/search_client.go index 1bf30676dfb5..ead3ff752e2a 100644 --- a/retail/apiv2beta/search_client.go +++ b/retail/apiv2beta/search_client.go @@ -482,6 +482,11 @@ func (c *searchRESTClient) Search(ctx context.Context, req *retailpb.SearchReque } baseUrl.Path += fmt.Sprintf("/v2beta/%v:search", req.GetPlacement()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { @@ -546,6 +551,11 @@ func (c *searchRESTClient) GetOperation(ctx context.Context, req *longrunningpb. } baseUrl.Path += fmt.Sprintf("/v2beta/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -613,6 +623,7 @@ func (c *searchRESTClient) ListOperations(ctx context.Context, req *longrunningp baseUrl.Path += fmt.Sprintf("/v2beta/%v/operations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/retail/apiv2beta/serving_config_client.go b/retail/apiv2beta/serving_config_client.go index eaef8a5c4c9f..ac7894df97c7 100644 --- a/retail/apiv2beta/serving_config_client.go +++ b/retail/apiv2beta/serving_config_client.go @@ -608,6 +608,7 @@ func (c *servingConfigRESTClient) CreateServingConfig(ctx context.Context, req * baseUrl.Path += fmt.Sprintf("/v2beta/%v/servingConfigs", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("servingConfigId", fmt.Sprintf("%v", req.GetServingConfigId())) baseUrl.RawQuery = params.Encode() @@ -667,6 +668,11 @@ func (c *servingConfigRESTClient) DeleteServingConfig(ctx context.Context, req * } baseUrl.Path += fmt.Sprintf("/v2beta/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -710,6 +716,7 @@ func (c *servingConfigRESTClient) UpdateServingConfig(ctx context.Context, req * baseUrl.Path += fmt.Sprintf("/v2beta/%v", req.GetServingConfig().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -775,6 +782,11 @@ func (c *servingConfigRESTClient) GetServingConfig(ctx context.Context, req *ret } baseUrl.Path += fmt.Sprintf("/v2beta/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -842,6 +854,7 @@ func (c *servingConfigRESTClient) ListServingConfigs(ctx context.Context, req *r baseUrl.Path += fmt.Sprintf("/v2beta/%v/servingConfigs", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -927,6 +940,11 @@ func (c *servingConfigRESTClient) AddControl(ctx context.Context, req *retailpb. } baseUrl.Path += fmt.Sprintf("/v2beta/%v:addControl", req.GetServingConfig()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "serving_config", url.QueryEscape(req.GetServingConfig()))) @@ -989,6 +1007,11 @@ func (c *servingConfigRESTClient) RemoveControl(ctx context.Context, req *retail } baseUrl.Path += fmt.Sprintf("/v2beta/%v:removeControl", req.GetServingConfig()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "serving_config", url.QueryEscape(req.GetServingConfig()))) @@ -1042,6 +1065,11 @@ func (c *servingConfigRESTClient) GetOperation(ctx context.Context, req *longrun } baseUrl.Path += fmt.Sprintf("/v2beta/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1109,6 +1137,7 @@ func (c *servingConfigRESTClient) ListOperations(ctx context.Context, req *longr baseUrl.Path += fmt.Sprintf("/v2beta/%v/operations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/retail/apiv2beta/user_event_client.go b/retail/apiv2beta/user_event_client.go index 00508a1f6b81..bb91a46bf3bc 100644 --- a/retail/apiv2beta/user_event_client.go +++ b/retail/apiv2beta/user_event_client.go @@ -726,6 +726,11 @@ func (c *userEventRESTClient) WriteUserEvent(ctx context.Context, req *retailpb. } baseUrl.Path += fmt.Sprintf("/v2beta/%v/userEvents:write", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -784,6 +789,7 @@ func (c *userEventRESTClient) CollectUserEvent(ctx context.Context, req *retailp baseUrl.Path += fmt.Sprintf("/v2beta/%v/userEvents:collect", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetEts() != 0 { params.Add("ets", fmt.Sprintf("%v", req.GetEts())) } @@ -856,6 +862,11 @@ func (c *userEventRESTClient) PurgeUserEvents(ctx context.Context, req *retailpb } baseUrl.Path += fmt.Sprintf("/v2beta/%v/userEvents:purge", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -925,6 +936,11 @@ func (c *userEventRESTClient) ImportUserEvents(ctx context.Context, req *retailp } baseUrl.Path += fmt.Sprintf("/v2beta/%v/userEvents:import", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -995,6 +1011,11 @@ func (c *userEventRESTClient) RejoinUserEvents(ctx context.Context, req *retailp } baseUrl.Path += fmt.Sprintf("/v2beta/%v/userEvents:rejoin", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1052,6 +1073,11 @@ func (c *userEventRESTClient) GetOperation(ctx context.Context, req *longrunning } baseUrl.Path += fmt.Sprintf("/v2beta/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1119,6 +1145,7 @@ func (c *userEventRESTClient) ListOperations(ctx context.Context, req *longrunni baseUrl.Path += fmt.Sprintf("/v2beta/%v/operations", req.GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/run/apiv2/doc.go b/run/apiv2/doc.go index 48e11cc1b14a..d401e654a92b 100644 --- a/run/apiv2/doc.go +++ b/run/apiv2/doc.go @@ -86,6 +86,8 @@ package run // import "cloud.google.com/go/run/apiv2" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -174,3 +176,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/run/apiv2/executions_client.go b/run/apiv2/executions_client.go index 4517a967696c..9e236ddd04f2 100644 --- a/run/apiv2/executions_client.go +++ b/run/apiv2/executions_client.go @@ -19,7 +19,9 @@ package run import ( "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,13 +29,16 @@ import ( lroauto "cloud.google.com/go/longrunning/autogen" runpb "cloud.google.com/go/run/apiv2/runpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -72,6 +77,17 @@ func defaultExecutionsCallOptions() *ExecutionsCallOptions { } } +func defaultExecutionsRESTCallOptions() *ExecutionsCallOptions { + return &ExecutionsCallOptions{ + GetExecution: []gax.CallOption{}, + ListExecutions: []gax.CallOption{}, + DeleteExecution: []gax.CallOption{}, + DeleteOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalExecutionsClient is an interface that defines the methods available from Cloud Run Admin API. type internalExecutionsClient interface { Close() error @@ -262,6 +278,89 @@ func (c *executionsGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type executionsRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing ExecutionsClient + CallOptions **ExecutionsCallOptions +} + +// NewExecutionsRESTClient creates a new executions rest client. +// +// Cloud Run Execution Control Plane API. +func NewExecutionsRESTClient(ctx context.Context, opts ...option.ClientOption) (*ExecutionsClient, error) { + clientOpts := append(defaultExecutionsRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultExecutionsRESTCallOptions() + c := &executionsRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &ExecutionsClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultExecutionsRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://run.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://run.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://run.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *executionsRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *executionsRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *executionsRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *executionsGRPCClient) GetExecution(ctx context.Context, req *runpb.GetExecutionRequest, opts ...gax.CallOption) (*runpb.Execution, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -418,9 +517,416 @@ func (c *executionsGRPCClient) ListOperations(ctx context.Context, req *longrunn return it } +// GetExecution gets information about an Execution. +func (c *executionsRESTClient) GetExecution(ctx context.Context, req *runpb.GetExecutionRequest, opts ...gax.CallOption) (*runpb.Execution, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetExecution[0:len((*c.CallOptions).GetExecution):len((*c.CallOptions).GetExecution)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &runpb.Execution{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListExecutions lists Executions from a Job. +func (c *executionsRESTClient) ListExecutions(ctx context.Context, req *runpb.ListExecutionsRequest, opts ...gax.CallOption) *ExecutionIterator { + it := &ExecutionIterator{} + req = proto.Clone(req).(*runpb.ListExecutionsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*runpb.Execution, string, error) { + resp := &runpb.ListExecutionsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/executions", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + if req.GetShowDeleted() { + params.Add("showDeleted", fmt.Sprintf("%v", req.GetShowDeleted())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetExecutions(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// DeleteExecution deletes an Execution. +func (c *executionsRESTClient) DeleteExecution(ctx context.Context, req *runpb.DeleteExecutionRequest, opts ...gax.CallOption) (*DeleteExecutionOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetEtag() != "" { + params.Add("etag", fmt.Sprintf("%v", req.GetEtag())) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &DeleteExecutionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteOperation is a utility method from google.longrunning.Operations. +func (c *executionsRESTClient) DeleteOperation(ctx context.Context, req *longrunningpb.DeleteOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *executionsRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *executionsRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + // DeleteExecutionOperation manages a long-running operation from DeleteExecution. type DeleteExecutionOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteExecutionOperation returns a new DeleteExecutionOperation from a given name. @@ -431,10 +937,21 @@ func (c *executionsGRPCClient) DeleteExecutionOperation(name string) *DeleteExec } } +// DeleteExecutionOperation returns a new DeleteExecutionOperation from a given name. +// The name must be that of a previously created DeleteExecutionOperation, possibly from a different process. +func (c *executionsRESTClient) DeleteExecutionOperation(name string) *DeleteExecutionOperation { + override := fmt.Sprintf("/v2/%s", name) + return &DeleteExecutionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteExecutionOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*runpb.Execution, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp runpb.Execution if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -452,6 +969,7 @@ func (op *DeleteExecutionOperation) Wait(ctx context.Context, opts ...gax.CallOp // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteExecutionOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*runpb.Execution, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp runpb.Execution if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/run/apiv2/executions_client_example_test.go b/run/apiv2/executions_client_example_test.go index d3d5abbfaf0c..74bc5d5db007 100644 --- a/run/apiv2/executions_client_example_test.go +++ b/run/apiv2/executions_client_example_test.go @@ -42,6 +42,23 @@ func ExampleNewExecutionsClient() { _ = c } +func ExampleNewExecutionsRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := run.NewExecutionsRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleExecutionsClient_GetExecution() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/run/apiv2/gapic_metadata.json b/run/apiv2/gapic_metadata.json index 69a78a2cf44f..d927fc28d41d 100644 --- a/run/apiv2/gapic_metadata.json +++ b/run/apiv2/gapic_metadata.json @@ -41,6 +41,41 @@ ] } } + }, + "rest": { + "libraryClient": "ExecutionsClient", + "rpcs": { + "DeleteExecution": { + "methods": [ + "DeleteExecution" + ] + }, + "DeleteOperation": { + "methods": [ + "DeleteOperation" + ] + }, + "GetExecution": { + "methods": [ + "GetExecution" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ListExecutions": { + "methods": [ + "ListExecutions" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + } + } } } }, @@ -110,6 +145,71 @@ ] } } + }, + "rest": { + "libraryClient": "JobsClient", + "rpcs": { + "CreateJob": { + "methods": [ + "CreateJob" + ] + }, + "DeleteJob": { + "methods": [ + "DeleteJob" + ] + }, + "DeleteOperation": { + "methods": [ + "DeleteOperation" + ] + }, + "GetIamPolicy": { + "methods": [ + "GetIamPolicy" + ] + }, + "GetJob": { + "methods": [ + "GetJob" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ListJobs": { + "methods": [ + "ListJobs" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "RunJob": { + "methods": [ + "RunJob" + ] + }, + "SetIamPolicy": { + "methods": [ + "SetIamPolicy" + ] + }, + "TestIamPermissions": { + "methods": [ + "TestIamPermissions" + ] + }, + "UpdateJob": { + "methods": [ + "UpdateJob" + ] + } + } } } }, @@ -149,6 +249,41 @@ ] } } + }, + "rest": { + "libraryClient": "RevisionsClient", + "rpcs": { + "DeleteOperation": { + "methods": [ + "DeleteOperation" + ] + }, + "DeleteRevision": { + "methods": [ + "DeleteRevision" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "GetRevision": { + "methods": [ + "GetRevision" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "ListRevisions": { + "methods": [ + "ListRevisions" + ] + } + } } } }, @@ -213,6 +348,66 @@ ] } } + }, + "rest": { + "libraryClient": "ServicesClient", + "rpcs": { + "CreateService": { + "methods": [ + "CreateService" + ] + }, + "DeleteOperation": { + "methods": [ + "DeleteOperation" + ] + }, + "DeleteService": { + "methods": [ + "DeleteService" + ] + }, + "GetIamPolicy": { + "methods": [ + "GetIamPolicy" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "GetService": { + "methods": [ + "GetService" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "ListServices": { + "methods": [ + "ListServices" + ] + }, + "SetIamPolicy": { + "methods": [ + "SetIamPolicy" + ] + }, + "TestIamPermissions": { + "methods": [ + "TestIamPermissions" + ] + }, + "UpdateService": { + "methods": [ + "UpdateService" + ] + } + } } } }, @@ -247,6 +442,36 @@ ] } } + }, + "rest": { + "libraryClient": "TasksClient", + "rpcs": { + "DeleteOperation": { + "methods": [ + "DeleteOperation" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "GetTask": { + "methods": [ + "GetTask" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "ListTasks": { + "methods": [ + "ListTasks" + ] + } + } } } } diff --git a/run/apiv2/jobs_client.go b/run/apiv2/jobs_client.go index 887697c68bd2..ecef72b64995 100644 --- a/run/apiv2/jobs_client.go +++ b/run/apiv2/jobs_client.go @@ -17,9 +17,12 @@ package run import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,14 +30,17 @@ import ( lroauto "cloud.google.com/go/longrunning/autogen" runpb "cloud.google.com/go/run/apiv2/runpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" iampb "google.golang.org/genproto/googleapis/iam/v1" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -85,6 +91,23 @@ func defaultJobsCallOptions() *JobsCallOptions { } } +func defaultJobsRESTCallOptions() *JobsCallOptions { + return &JobsCallOptions{ + CreateJob: []gax.CallOption{}, + GetJob: []gax.CallOption{}, + ListJobs: []gax.CallOption{}, + UpdateJob: []gax.CallOption{}, + DeleteJob: []gax.CallOption{}, + RunJob: []gax.CallOption{}, + GetIamPolicy: []gax.CallOption{}, + SetIamPolicy: []gax.CallOption{}, + TestIamPermissions: []gax.CallOption{}, + DeleteOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalJobsClient is an interface that defines the methods available from Cloud Run Admin API. type internalJobsClient interface { Close() error @@ -336,6 +359,89 @@ func (c *jobsGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type jobsRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing JobsClient + CallOptions **JobsCallOptions +} + +// NewJobsRESTClient creates a new jobs rest client. +// +// Cloud Run Job Control Plane API. +func NewJobsRESTClient(ctx context.Context, opts ...option.ClientOption) (*JobsClient, error) { + clientOpts := append(defaultJobsRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultJobsRESTCallOptions() + c := &jobsRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &JobsClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultJobsRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://run.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://run.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://run.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *jobsRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *jobsRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *jobsRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *jobsGRPCClient) CreateJob(ctx context.Context, req *runpb.CreateJobRequest, opts ...gax.CallOption) (*CreateJobOperation, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -600,178 +706,1032 @@ func (c *jobsGRPCClient) ListOperations(ctx context.Context, req *longrunningpb. return it } -// CreateJobOperation manages a long-running operation from CreateJob. -type CreateJobOperation struct { - lro *longrunning.Operation -} - -// CreateJobOperation returns a new CreateJobOperation from a given name. -// The name must be that of a previously created CreateJobOperation, possibly from a different process. -func (c *jobsGRPCClient) CreateJobOperation(name string) *CreateJobOperation { - return &CreateJobOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} - -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *CreateJobOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*runpb.Job, error) { - var resp runpb.Job - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { +// CreateJob creates a Job. +func (c *jobsRESTClient) CreateJob(ctx context.Context, req *runpb.CreateJobRequest, opts ...gax.CallOption) (*CreateJobOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetJob() + jsonReq, err := m.Marshal(body) + if err != nil { return nil, err } - return &resp, nil -} -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *CreateJobOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*runpb.Job, error) { - var resp runpb.Job - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - if !op.Done() { - return nil, nil - } - return &resp, nil -} + baseUrl.Path += fmt.Sprintf("/v2/%v/jobs", req.GetParent()) -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *CreateJobOperation) Metadata() (*runpb.Job, error) { - var meta runpb.Job - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { - return nil, err + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("jobId", fmt.Sprintf("%v", req.GetJobId())) + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) } - return &meta, nil -} -// Done reports whether the long-running operation has completed. -func (op *CreateJobOperation) Done() bool { - return op.lro.Done() -} + baseUrl.RawQuery = params.Encode() -// 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 *CreateJobOperation) Name() string { - return op.lro.Name() -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) -// DeleteJobOperation manages a long-running operation from DeleteJob. -type DeleteJobOperation struct { - lro *longrunning.Operation -} + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers -// DeleteJobOperation returns a new DeleteJobOperation from a given name. -// The name must be that of a previously created DeleteJobOperation, possibly from a different process. -func (c *jobsGRPCClient) DeleteJobOperation(name string) *DeleteJobOperation { - return &DeleteJobOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *DeleteJobOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*runpb.Job, error) { - var resp runpb.Job - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { - return nil, err - } - return &resp, nil -} + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *DeleteJobOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*runpb.Job, error) { - var resp runpb.Job - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { - return nil, err - } - if !op.Done() { - return nil, nil + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e } - return &resp, nil + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &CreateJobOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil } -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *DeleteJobOperation) Metadata() (*runpb.Job, error) { - var meta runpb.Job - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { +// GetJob gets information about a Job. +func (c *jobsRESTClient) GetJob(ctx context.Context, req *runpb.GetJobRequest, opts ...gax.CallOption) (*runpb.Job, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - return &meta, nil -} + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) -// Done reports whether the long-running operation has completed. -func (op *DeleteJobOperation) Done() bool { - return op.lro.Done() -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") -// 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 *DeleteJobOperation) Name() string { - return op.lro.Name() -} + baseUrl.RawQuery = params.Encode() -// RunJobOperation manages a long-running operation from RunJob. -type RunJobOperation struct { - lro *longrunning.Operation -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) -// RunJobOperation returns a new RunJobOperation from a given name. -// The name must be that of a previously created RunJobOperation, possibly from a different process. -func (c *jobsGRPCClient) RunJobOperation(name string) *RunJobOperation { - return &RunJobOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetJob[0:len((*c.CallOptions).GetJob):len((*c.CallOptions).GetJob)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &runpb.Job{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *RunJobOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*runpb.Execution, error) { - var resp runpb.Execution - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { - return nil, err + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e } - return &resp, nil + return resp, nil } -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *RunJobOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*runpb.Execution, error) { +// ListJobs lists Jobs. +func (c *jobsRESTClient) ListJobs(ctx context.Context, req *runpb.ListJobsRequest, opts ...gax.CallOption) *JobIterator { + it := &JobIterator{} + req = proto.Clone(req).(*runpb.ListJobsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*runpb.Job, string, error) { + resp := &runpb.ListJobsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/jobs", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + if req.GetShowDeleted() { + params.Add("showDeleted", fmt.Sprintf("%v", req.GetShowDeleted())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetJobs(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// UpdateJob updates a Job. +func (c *jobsRESTClient) UpdateJob(ctx context.Context, req *runpb.UpdateJobRequest, opts ...gax.CallOption) (*UpdateJobOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetJob() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetJob().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetAllowMissing() { + params.Add("allowMissing", fmt.Sprintf("%v", req.GetAllowMissing())) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "job.name", url.QueryEscape(req.GetJob().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &UpdateJobOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteJob deletes a Job. +func (c *jobsRESTClient) DeleteJob(ctx context.Context, req *runpb.DeleteJobRequest, opts ...gax.CallOption) (*DeleteJobOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetEtag() != "" { + params.Add("etag", fmt.Sprintf("%v", req.GetEtag())) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &DeleteJobOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// RunJob triggers creation of a new Execution of this Job. +func (c *jobsRESTClient) RunJob(ctx context.Context, req *runpb.RunJobRequest, opts ...gax.CallOption) (*RunJobOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:run", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &RunJobOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetIamPolicy gets the IAM Access Control policy currently in effect for the given Job. +// This result does not include any inherited policies. +func (c *jobsRESTClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:getIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetOptions().GetRequestedPolicyVersion() != 0 { + params.Add("options.requestedPolicyVersion", fmt.Sprintf("%v", req.GetOptions().GetRequestedPolicyVersion())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SetIamPolicy sets the IAM Access control policy for the specified Job. Overwrites +// any existing policy. +func (c *jobsRESTClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:setIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// TestIamPermissions returns permissions that a caller has on the specified Project. +// +// There are no permissions required for making this API call. +func (c *jobsRESTClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:testIamPermissions", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.TestIamPermissionsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteOperation is a utility method from google.longrunning.Operations. +func (c *jobsRESTClient) DeleteOperation(ctx context.Context, req *longrunningpb.DeleteOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *jobsRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *jobsRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CreateJobOperation manages a long-running operation from CreateJob. +type CreateJobOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateJobOperation returns a new CreateJobOperation from a given name. +// The name must be that of a previously created CreateJobOperation, possibly from a different process. +func (c *jobsGRPCClient) CreateJobOperation(name string) *CreateJobOperation { + return &CreateJobOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateJobOperation returns a new CreateJobOperation from a given name. +// The name must be that of a previously created CreateJobOperation, possibly from a different process. +func (c *jobsRESTClient) CreateJobOperation(name string) *CreateJobOperation { + override := fmt.Sprintf("/v2/%s", name) + return &CreateJobOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CreateJobOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*runpb.Job, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp runpb.Job + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *CreateJobOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*runpb.Job, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp runpb.Job + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *CreateJobOperation) Metadata() (*runpb.Job, error) { + var meta runpb.Job + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *CreateJobOperation) Done() bool { + return op.lro.Done() +} + +// 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 *CreateJobOperation) Name() string { + return op.lro.Name() +} + +// DeleteJobOperation manages a long-running operation from DeleteJob. +type DeleteJobOperation struct { + lro *longrunning.Operation + pollPath string +} + +// DeleteJobOperation returns a new DeleteJobOperation from a given name. +// The name must be that of a previously created DeleteJobOperation, possibly from a different process. +func (c *jobsGRPCClient) DeleteJobOperation(name string) *DeleteJobOperation { + return &DeleteJobOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// DeleteJobOperation returns a new DeleteJobOperation from a given name. +// The name must be that of a previously created DeleteJobOperation, possibly from a different process. +func (c *jobsRESTClient) DeleteJobOperation(name string) *DeleteJobOperation { + override := fmt.Sprintf("/v2/%s", name) + return &DeleteJobOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *DeleteJobOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*runpb.Job, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp runpb.Job + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *DeleteJobOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*runpb.Job, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp runpb.Job + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *DeleteJobOperation) Metadata() (*runpb.Job, error) { + var meta runpb.Job + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *DeleteJobOperation) Done() bool { + return op.lro.Done() +} + +// 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 *DeleteJobOperation) Name() string { + return op.lro.Name() +} + +// RunJobOperation manages a long-running operation from RunJob. +type RunJobOperation struct { + lro *longrunning.Operation + pollPath string +} + +// RunJobOperation returns a new RunJobOperation from a given name. +// The name must be that of a previously created RunJobOperation, possibly from a different process. +func (c *jobsGRPCClient) RunJobOperation(name string) *RunJobOperation { + return &RunJobOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// RunJobOperation returns a new RunJobOperation from a given name. +// The name must be that of a previously created RunJobOperation, possibly from a different process. +func (c *jobsRESTClient) RunJobOperation(name string) *RunJobOperation { + override := fmt.Sprintf("/v2/%s", name) + return &RunJobOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *RunJobOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*runpb.Execution, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp runpb.Execution + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *RunJobOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*runpb.Execution, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp runpb.Execution if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -809,7 +1769,8 @@ func (op *RunJobOperation) Name() string { // UpdateJobOperation manages a long-running operation from UpdateJob. type UpdateJobOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateJobOperation returns a new UpdateJobOperation from a given name. @@ -820,10 +1781,21 @@ func (c *jobsGRPCClient) UpdateJobOperation(name string) *UpdateJobOperation { } } +// UpdateJobOperation returns a new UpdateJobOperation from a given name. +// The name must be that of a previously created UpdateJobOperation, possibly from a different process. +func (c *jobsRESTClient) UpdateJobOperation(name string) *UpdateJobOperation { + override := fmt.Sprintf("/v2/%s", name) + return &UpdateJobOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateJobOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*runpb.Job, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp runpb.Job if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -841,6 +1813,7 @@ func (op *UpdateJobOperation) Wait(ctx context.Context, opts ...gax.CallOption) // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateJobOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*runpb.Job, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp runpb.Job if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/run/apiv2/jobs_client_example_test.go b/run/apiv2/jobs_client_example_test.go index a7ad00da4935..7e01d418e0c6 100644 --- a/run/apiv2/jobs_client_example_test.go +++ b/run/apiv2/jobs_client_example_test.go @@ -43,6 +43,23 @@ func ExampleNewJobsClient() { _ = c } +func ExampleNewJobsRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := run.NewJobsRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleJobsClient_CreateJob() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/run/apiv2/revisions_client.go b/run/apiv2/revisions_client.go index a187152f426a..7f4c58e12f77 100644 --- a/run/apiv2/revisions_client.go +++ b/run/apiv2/revisions_client.go @@ -19,7 +19,9 @@ package run import ( "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "regexp" "strings" @@ -29,13 +31,16 @@ import ( lroauto "cloud.google.com/go/longrunning/autogen" runpb "cloud.google.com/go/run/apiv2/runpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -74,6 +79,17 @@ func defaultRevisionsCallOptions() *RevisionsCallOptions { } } +func defaultRevisionsRESTCallOptions() *RevisionsCallOptions { + return &RevisionsCallOptions{ + GetRevision: []gax.CallOption{}, + ListRevisions: []gax.CallOption{}, + DeleteRevision: []gax.CallOption{}, + DeleteOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalRevisionsClient is an interface that defines the methods available from Cloud Run Admin API. type internalRevisionsClient interface { Close() error @@ -264,6 +280,89 @@ func (c *revisionsGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type revisionsRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing RevisionsClient + CallOptions **RevisionsCallOptions +} + +// NewRevisionsRESTClient creates a new revisions rest client. +// +// Cloud Run Revision Control Plane API. +func NewRevisionsRESTClient(ctx context.Context, opts ...option.ClientOption) (*RevisionsClient, error) { + clientOpts := append(defaultRevisionsRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRevisionsRESTCallOptions() + c := &revisionsRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &RevisionsClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRevisionsRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://run.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://run.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://run.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *revisionsRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *revisionsRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *revisionsRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *revisionsGRPCClient) GetRevision(ctx context.Context, req *runpb.GetRevisionRequest, opts ...gax.CallOption) (*runpb.Revision, error) { routingHeaders := "" routingHeadersMap := make(map[string]string) @@ -447,9 +546,434 @@ func (c *revisionsGRPCClient) ListOperations(ctx context.Context, req *longrunni return it } +// GetRevision gets information about a Revision. +func (c *revisionsRESTClient) GetRevision(ctx context.Context, req *runpb.GetRevisionRequest, opts ...gax.CallOption) (*runpb.Revision, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + routingHeaders := "" + routingHeadersMap := make(map[string]string) + if reg := regexp.MustCompile("projects/[^/]+/locations/(?P[^/]+)(?:/.*)?"); reg.MatchString(req.GetName()) && len(url.QueryEscape(reg.FindStringSubmatch(req.GetName())[1])) > 0 { + routingHeadersMap["location"] = url.QueryEscape(reg.FindStringSubmatch(req.GetName())[1]) + } + for headerName, headerValue := range routingHeadersMap { + routingHeaders = fmt.Sprintf("%s%s=%s&", routingHeaders, headerName, headerValue) + } + routingHeaders = strings.TrimSuffix(routingHeaders, "&") + md := metadata.Pairs("x-goog-request-params", routingHeaders) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetRevision[0:len((*c.CallOptions).GetRevision):len((*c.CallOptions).GetRevision)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &runpb.Revision{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListRevisions lists Revisions from a given Service, or from a given location. +func (c *revisionsRESTClient) ListRevisions(ctx context.Context, req *runpb.ListRevisionsRequest, opts ...gax.CallOption) *RevisionIterator { + it := &RevisionIterator{} + req = proto.Clone(req).(*runpb.ListRevisionsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*runpb.Revision, string, error) { + resp := &runpb.ListRevisionsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/revisions", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + if req.GetShowDeleted() { + params.Add("showDeleted", fmt.Sprintf("%v", req.GetShowDeleted())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetRevisions(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// DeleteRevision deletes a Revision. +func (c *revisionsRESTClient) DeleteRevision(ctx context.Context, req *runpb.DeleteRevisionRequest, opts ...gax.CallOption) (*DeleteRevisionOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetEtag() != "" { + params.Add("etag", fmt.Sprintf("%v", req.GetEtag())) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + routingHeaders := "" + routingHeadersMap := make(map[string]string) + if reg := regexp.MustCompile("projects/[^/]+/locations/(?P[^/]+)(?:/.*)?"); reg.MatchString(req.GetName()) && len(url.QueryEscape(reg.FindStringSubmatch(req.GetName())[1])) > 0 { + routingHeadersMap["location"] = url.QueryEscape(reg.FindStringSubmatch(req.GetName())[1]) + } + for headerName, headerValue := range routingHeadersMap { + routingHeaders = fmt.Sprintf("%s%s=%s&", routingHeaders, headerName, headerValue) + } + routingHeaders = strings.TrimSuffix(routingHeaders, "&") + md := metadata.Pairs("x-goog-request-params", routingHeaders) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &DeleteRevisionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteOperation is a utility method from google.longrunning.Operations. +func (c *revisionsRESTClient) DeleteOperation(ctx context.Context, req *longrunningpb.DeleteOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *revisionsRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *revisionsRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + // DeleteRevisionOperation manages a long-running operation from DeleteRevision. type DeleteRevisionOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteRevisionOperation returns a new DeleteRevisionOperation from a given name. @@ -460,10 +984,21 @@ func (c *revisionsGRPCClient) DeleteRevisionOperation(name string) *DeleteRevisi } } +// DeleteRevisionOperation returns a new DeleteRevisionOperation from a given name. +// The name must be that of a previously created DeleteRevisionOperation, possibly from a different process. +func (c *revisionsRESTClient) DeleteRevisionOperation(name string) *DeleteRevisionOperation { + override := fmt.Sprintf("/v2/%s", name) + return &DeleteRevisionOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteRevisionOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*runpb.Revision, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp runpb.Revision if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -481,6 +1016,7 @@ func (op *DeleteRevisionOperation) Wait(ctx context.Context, opts ...gax.CallOpt // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteRevisionOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*runpb.Revision, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp runpb.Revision if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/run/apiv2/revisions_client_example_test.go b/run/apiv2/revisions_client_example_test.go index 1a88950dd8a5..173fa0010ef0 100644 --- a/run/apiv2/revisions_client_example_test.go +++ b/run/apiv2/revisions_client_example_test.go @@ -42,6 +42,23 @@ func ExampleNewRevisionsClient() { _ = c } +func ExampleNewRevisionsRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := run.NewRevisionsRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleRevisionsClient_GetRevision() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/run/apiv2/runpb/condition.pb.go b/run/apiv2/runpb/condition.pb.go index a31e949b90c4..a0b516901eba 100644 --- a/run/apiv2/runpb/condition.pb.go +++ b/run/apiv2/runpb/condition.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/run/v2/condition.proto package runpb @@ -433,7 +433,6 @@ type Condition struct { // Successful conditions cannot have a reason. // // Types that are assignable to Reasons: - // // *Condition_Reason // *Condition_RevisionReason_ // *Condition_ExecutionReason_ diff --git a/run/apiv2/runpb/execution.pb.go b/run/apiv2/runpb/execution.pb.go index 220476eb4dd8..705e19b00ea8 100644 --- a/run/apiv2/runpb/execution.pb.go +++ b/run/apiv2/runpb/execution.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/run/v2/execution.proto package runpb @@ -510,7 +510,7 @@ func (x *Execution) GetLaunchStage() api.LaunchStage { if x != nil { return x.LaunchStage } - return api.LaunchStage_LAUNCH_STAGE_UNSPECIFIED + return api.LaunchStage(0) } func (x *Execution) GetJob() string { diff --git a/run/apiv2/runpb/execution_template.pb.go b/run/apiv2/runpb/execution_template.pb.go index ea88b24ee064..df28544c19b9 100644 --- a/run/apiv2/runpb/execution_template.pb.go +++ b/run/apiv2/runpb/execution_template.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/run/v2/execution_template.proto package runpb diff --git a/run/apiv2/runpb/job.pb.go b/run/apiv2/runpb/job.pb.go index 510ec2b69c66..4c3ad7599b45 100644 --- a/run/apiv2/runpb/job.pb.go +++ b/run/apiv2/runpb/job.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/run/v2/job.proto package runpb @@ -756,7 +756,7 @@ func (x *Job) GetLaunchStage() api.LaunchStage { if x != nil { return x.LaunchStage } - return api.LaunchStage_LAUNCH_STAGE_UNSPECIFIED + return api.LaunchStage(0) } func (x *Job) GetBinaryAuthorization() *BinaryAuthorization { diff --git a/run/apiv2/runpb/k8s.min.pb.go b/run/apiv2/runpb/k8s.min.pb.go index fb6ec3394766..fe5e171bb085 100644 --- a/run/apiv2/runpb/k8s.min.pb.go +++ b/run/apiv2/runpb/k8s.min.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/run/v2/k8s.min.proto package runpb @@ -285,7 +285,6 @@ type EnvVar struct { // exceed 32768 characters. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Types that are assignable to Values: - // // *EnvVar_Value // *EnvVar_ValueSource Values isEnvVar_Values `protobuf_oneof:"values"` @@ -619,7 +618,6 @@ type Volume struct { // Required. Volume's name. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Types that are assignable to VolumeType: - // // *Volume_Secret // *Volume_CloudSqlInstance VolumeType isVolume_VolumeType `protobuf_oneof:"volume_type"` @@ -729,7 +727,7 @@ type SecretVolumeSource struct { // Must be a value between 0000 and 0777 (octal), defaulting to 0444. // Directories within the path are not affected by this setting. // - // # Notes + // Notes // // * Internally, a umask of 0222 will be applied to any non-zero value. // * This is an integer representation of the mode bits. So, the octal @@ -816,7 +814,7 @@ type VersionToPath struct { // 01 and 0777 (octal). If 0 or not set, the Volume's default mode will be // used. // - // # Notes + // Notes // // * Internally, a umask of 0222 will be applied to any non-zero value. // * This is an integer representation of the mode bits. So, the octal @@ -965,7 +963,6 @@ type Probe struct { // having succeeded. Defaults to 3. Minimum value is 1. FailureThreshold int32 `protobuf:"varint,4,opt,name=failure_threshold,json=failureThreshold,proto3" json:"failure_threshold,omitempty"` // Types that are assignable to ProbeType: - // // *Probe_HttpGet // *Probe_TcpSocket // *Probe_Grpc diff --git a/run/apiv2/runpb/revision.pb.go b/run/apiv2/runpb/revision.pb.go index 8a0c88e66a18..39e187a6a7f4 100644 --- a/run/apiv2/runpb/revision.pb.go +++ b/run/apiv2/runpb/revision.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/run/v2/revision.proto package runpb @@ -494,7 +494,7 @@ func (x *Revision) GetLaunchStage() api.LaunchStage { if x != nil { return x.LaunchStage } - return api.LaunchStage_LAUNCH_STAGE_UNSPECIFIED + return api.LaunchStage(0) } func (x *Revision) GetService() string { diff --git a/run/apiv2/runpb/revision_template.pb.go b/run/apiv2/runpb/revision_template.pb.go index b569f9e5dfa0..007a418f2c62 100644 --- a/run/apiv2/runpb/revision_template.pb.go +++ b/run/apiv2/runpb/revision_template.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/run/v2/revision_template.proto package runpb diff --git a/run/apiv2/runpb/service.pb.go b/run/apiv2/runpb/service.pb.go index 3d02d1c3f558..4870eb2897ce 100644 --- a/run/apiv2/runpb/service.pb.go +++ b/run/apiv2/runpb/service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/run/v2/service.proto package runpb @@ -734,7 +734,7 @@ func (x *Service) GetLaunchStage() api.LaunchStage { if x != nil { return x.LaunchStage } - return api.LaunchStage_LAUNCH_STAGE_UNSPECIFIED + return api.LaunchStage(0) } func (x *Service) GetBinaryAuthorization() *BinaryAuthorization { diff --git a/run/apiv2/runpb/task.pb.go b/run/apiv2/runpb/task.pb.go index 438f2ab8bf0d..73227487fe7d 100644 --- a/run/apiv2/runpb/task.pb.go +++ b/run/apiv2/runpb/task.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/run/v2/task.proto package runpb diff --git a/run/apiv2/runpb/task_template.pb.go b/run/apiv2/runpb/task_template.pb.go index 04c283cf1ea8..53c0117996e5 100644 --- a/run/apiv2/runpb/task_template.pb.go +++ b/run/apiv2/runpb/task_template.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/run/v2/task_template.proto package runpb @@ -50,7 +50,6 @@ type TaskTemplate struct { // A list of Volumes to make available to containers. Volumes []*Volume `protobuf:"bytes,2,rep,name=volumes,proto3" json:"volumes,omitempty"` // Types that are assignable to Retries: - // // *TaskTemplate_MaxRetries Retries isTaskTemplate_Retries `protobuf_oneof:"retries"` // Max allowed time duration the Task may be active before the system will diff --git a/run/apiv2/runpb/traffic_target.pb.go b/run/apiv2/runpb/traffic_target.pb.go index 377189ca41a3..f8d013625246 100644 --- a/run/apiv2/runpb/traffic_target.pb.go +++ b/run/apiv2/runpb/traffic_target.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/run/v2/traffic_target.proto package runpb diff --git a/run/apiv2/runpb/vendor_settings.pb.go b/run/apiv2/runpb/vendor_settings.pb.go index 26824ddf3e72..8ecf57f0c028 100644 --- a/run/apiv2/runpb/vendor_settings.pb.go +++ b/run/apiv2/runpb/vendor_settings.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/run/v2/vendor_settings.proto package runpb @@ -269,7 +269,6 @@ type BinaryAuthorization struct { unknownFields protoimpl.UnknownFields // Types that are assignable to BinauthzMethod: - // // *BinaryAuthorization_UseDefault BinauthzMethod isBinaryAuthorization_BinauthzMethod `protobuf_oneof:"binauthz_method"` // If present, indicates to use Breakglass using this justification. diff --git a/run/apiv2/services_client.go b/run/apiv2/services_client.go index 7dc5a9e18c7e..04b725851dcb 100644 --- a/run/apiv2/services_client.go +++ b/run/apiv2/services_client.go @@ -17,9 +17,12 @@ package run import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "regexp" "strings" @@ -29,15 +32,18 @@ import ( lroauto "cloud.google.com/go/longrunning/autogen" runpb "cloud.google.com/go/run/apiv2/runpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" iampb "google.golang.org/genproto/googleapis/iam/v1" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -106,6 +112,40 @@ func defaultServicesCallOptions() *ServicesCallOptions { } } +func defaultServicesRESTCallOptions() *ServicesCallOptions { + return &ServicesCallOptions{ + CreateService: []gax.CallOption{}, + GetService: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListServices: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + UpdateService: []gax.CallOption{}, + DeleteService: []gax.CallOption{}, + GetIamPolicy: []gax.CallOption{}, + SetIamPolicy: []gax.CallOption{}, + TestIamPermissions: []gax.CallOption{}, + DeleteOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalServicesClient is an interface that defines the methods available from Cloud Run Admin API. type internalServicesClient interface { Close() error @@ -346,6 +386,89 @@ func (c *servicesGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type servicesRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing ServicesClient + CallOptions **ServicesCallOptions +} + +// NewServicesRESTClient creates a new services rest client. +// +// Cloud Run Service Control Plane API +func NewServicesRESTClient(ctx context.Context, opts ...option.ClientOption) (*ServicesClient, error) { + clientOpts := append(defaultServicesRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultServicesRESTCallOptions() + c := &servicesRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &ServicesClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultServicesRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://run.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://run.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://run.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *servicesRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *servicesRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *servicesRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *servicesGRPCClient) CreateService(ctx context.Context, req *runpb.CreateServiceRequest, opts ...gax.CallOption) (*CreateServiceOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 15000*time.Millisecond) @@ -656,147 +779,959 @@ func (c *servicesGRPCClient) ListOperations(ctx context.Context, req *longrunnin return it } -// CreateServiceOperation manages a long-running operation from CreateService. -type CreateServiceOperation struct { - lro *longrunning.Operation -} - -// CreateServiceOperation returns a new CreateServiceOperation from a given name. -// The name must be that of a previously created CreateServiceOperation, possibly from a different process. -func (c *servicesGRPCClient) CreateServiceOperation(name string) *CreateServiceOperation { - return &CreateServiceOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} - -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *CreateServiceOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*runpb.Service, error) { - var resp runpb.Service - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { +// CreateService creates a new Service in a given project and location. +func (c *servicesRESTClient) CreateService(ctx context.Context, req *runpb.CreateServiceRequest, opts ...gax.CallOption) (*CreateServiceOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetService() + jsonReq, err := m.Marshal(body) + if err != nil { return nil, err } - return &resp, nil -} -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *CreateServiceOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*runpb.Service, error) { - var resp runpb.Service - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - if !op.Done() { - return nil, nil + baseUrl.Path += fmt.Sprintf("/v2/%v/services", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("serviceId", fmt.Sprintf("%v", req.GetServiceId())) + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) } - return &resp, nil -} -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *CreateServiceOperation) Metadata() (*runpb.Service, error) { - var meta runpb.Service - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { - return nil, err + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + routingHeaders := "" + routingHeadersMap := make(map[string]string) + if reg := regexp.MustCompile("projects/[^/]+/locations/(?P[^/]+)"); reg.MatchString(req.GetParent()) && len(url.QueryEscape(reg.FindStringSubmatch(req.GetParent())[1])) > 0 { + routingHeadersMap["location"] = url.QueryEscape(reg.FindStringSubmatch(req.GetParent())[1]) } - return &meta, nil -} + for headerName, headerValue := range routingHeadersMap { + routingHeaders = fmt.Sprintf("%s%s=%s&", routingHeaders, headerName, headerValue) + } + routingHeaders = strings.TrimSuffix(routingHeaders, "&") + md := metadata.Pairs("x-goog-request-params", routingHeaders) -// Done reports whether the long-running operation has completed. -func (op *CreateServiceOperation) Done() bool { - return op.lro.Done() -} + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers -// 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 *CreateServiceOperation) Name() string { - return op.lro.Name() -} + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() -// DeleteServiceOperation manages a long-running operation from DeleteService. -type DeleteServiceOperation struct { - lro *longrunning.Operation -} + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } -// DeleteServiceOperation returns a new DeleteServiceOperation from a given name. -// The name must be that of a previously created DeleteServiceOperation, possibly from a different process. -func (c *servicesGRPCClient) DeleteServiceOperation(name string) *DeleteServiceOperation { - return &DeleteServiceOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &CreateServiceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil } -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *DeleteServiceOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*runpb.Service, error) { - var resp runpb.Service - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { +// GetService gets information about a Service. +func (c *servicesRESTClient) GetService(ctx context.Context, req *runpb.GetServiceRequest, opts ...gax.CallOption) (*runpb.Service, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - return &resp, nil -} + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *DeleteServiceOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*runpb.Service, error) { - var resp runpb.Service - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { - return nil, err + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + routingHeaders := "" + routingHeadersMap := make(map[string]string) + if reg := regexp.MustCompile("projects/[^/]+/locations/(?P[^/]+)(?:/.*)?"); reg.MatchString(req.GetName()) && len(url.QueryEscape(reg.FindStringSubmatch(req.GetName())[1])) > 0 { + routingHeadersMap["location"] = url.QueryEscape(reg.FindStringSubmatch(req.GetName())[1]) } - if !op.Done() { - return nil, nil + for headerName, headerValue := range routingHeadersMap { + routingHeaders = fmt.Sprintf("%s%s=%s&", routingHeaders, headerName, headerValue) } - return &resp, nil -} + routingHeaders = strings.TrimSuffix(routingHeaders, "&") + md := metadata.Pairs("x-goog-request-params", routingHeaders) -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *DeleteServiceOperation) Metadata() (*runpb.Service, error) { - var meta runpb.Service - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { - return nil, err - } - return &meta, nil -} + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetService[0:len((*c.CallOptions).GetService):len((*c.CallOptions).GetService)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &runpb.Service{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers -// Done reports whether the long-running operation has completed. -func (op *DeleteServiceOperation) Done() bool { - return op.lro.Done() -} + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() -// 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 *DeleteServiceOperation) Name() string { - return op.lro.Name() -} + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } -// UpdateServiceOperation manages a long-running operation from UpdateService. -type UpdateServiceOperation struct { - lro *longrunning.Operation + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListServices lists Services. +func (c *servicesRESTClient) ListServices(ctx context.Context, req *runpb.ListServicesRequest, opts ...gax.CallOption) *ServiceIterator { + it := &ServiceIterator{} + req = proto.Clone(req).(*runpb.ListServicesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*runpb.Service, string, error) { + resp := &runpb.ListServicesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/services", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + if req.GetShowDeleted() { + params.Add("showDeleted", fmt.Sprintf("%v", req.GetShowDeleted())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetServices(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// UpdateService updates a Service. +func (c *servicesRESTClient) UpdateService(ctx context.Context, req *runpb.UpdateServiceRequest, opts ...gax.CallOption) (*UpdateServiceOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetService() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetService().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetAllowMissing() { + params.Add("allowMissing", fmt.Sprintf("%v", req.GetAllowMissing())) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + routingHeaders := "" + routingHeadersMap := make(map[string]string) + if reg := regexp.MustCompile("projects/[^/]+/locations/(?P[^/]+)(?:/.*)?"); reg.MatchString(req.GetService().GetName()) && len(url.QueryEscape(reg.FindStringSubmatch(req.GetService().GetName())[1])) > 0 { + routingHeadersMap["location"] = url.QueryEscape(reg.FindStringSubmatch(req.GetService().GetName())[1]) + } + for headerName, headerValue := range routingHeadersMap { + routingHeaders = fmt.Sprintf("%s%s=%s&", routingHeaders, headerName, headerValue) + } + routingHeaders = strings.TrimSuffix(routingHeaders, "&") + md := metadata.Pairs("x-goog-request-params", routingHeaders) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &UpdateServiceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteService deletes a Service. +// This will cause the Service to stop serving traffic and will delete all +// revisions. +func (c *servicesRESTClient) DeleteService(ctx context.Context, req *runpb.DeleteServiceRequest, opts ...gax.CallOption) (*DeleteServiceOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetEtag() != "" { + params.Add("etag", fmt.Sprintf("%v", req.GetEtag())) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + routingHeaders := "" + routingHeadersMap := make(map[string]string) + if reg := regexp.MustCompile("projects/[^/]+/locations/(?P[^/]+)(?:/.*)?"); reg.MatchString(req.GetName()) && len(url.QueryEscape(reg.FindStringSubmatch(req.GetName())[1])) > 0 { + routingHeadersMap["location"] = url.QueryEscape(reg.FindStringSubmatch(req.GetName())[1]) + } + for headerName, headerValue := range routingHeadersMap { + routingHeaders = fmt.Sprintf("%s%s=%s&", routingHeaders, headerName, headerValue) + } + routingHeaders = strings.TrimSuffix(routingHeaders, "&") + md := metadata.Pairs("x-goog-request-params", routingHeaders) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &DeleteServiceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetIamPolicy gets the IAM Access Control policy currently in effect for the given +// Cloud Run Service. This result does not include any inherited policies. +func (c *servicesRESTClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:getIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetOptions().GetRequestedPolicyVersion() != 0 { + params.Add("options.requestedPolicyVersion", fmt.Sprintf("%v", req.GetOptions().GetRequestedPolicyVersion())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SetIamPolicy sets the IAM Access control policy for the specified Service. Overwrites +// any existing policy. +func (c *servicesRESTClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:setIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// TestIamPermissions returns permissions that a caller has on the specified Project. +// +// There are no permissions required for making this API call. +func (c *servicesRESTClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:testIamPermissions", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.TestIamPermissionsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteOperation is a utility method from google.longrunning.Operations. +func (c *servicesRESTClient) DeleteOperation(ctx context.Context, req *longrunningpb.DeleteOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *servicesRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *servicesRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CreateServiceOperation manages a long-running operation from CreateService. +type CreateServiceOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateServiceOperation returns a new CreateServiceOperation from a given name. +// The name must be that of a previously created CreateServiceOperation, possibly from a different process. +func (c *servicesGRPCClient) CreateServiceOperation(name string) *CreateServiceOperation { + return &CreateServiceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateServiceOperation returns a new CreateServiceOperation from a given name. +// The name must be that of a previously created CreateServiceOperation, possibly from a different process. +func (c *servicesRESTClient) CreateServiceOperation(name string) *CreateServiceOperation { + override := fmt.Sprintf("/v2/%s", name) + return &CreateServiceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CreateServiceOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*runpb.Service, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp runpb.Service + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *CreateServiceOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*runpb.Service, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp runpb.Service + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *CreateServiceOperation) Metadata() (*runpb.Service, error) { + var meta runpb.Service + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *CreateServiceOperation) Done() bool { + return op.lro.Done() +} + +// 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 *CreateServiceOperation) Name() string { + return op.lro.Name() +} + +// DeleteServiceOperation manages a long-running operation from DeleteService. +type DeleteServiceOperation struct { + lro *longrunning.Operation + pollPath string +} + +// DeleteServiceOperation returns a new DeleteServiceOperation from a given name. +// The name must be that of a previously created DeleteServiceOperation, possibly from a different process. +func (c *servicesGRPCClient) DeleteServiceOperation(name string) *DeleteServiceOperation { + return &DeleteServiceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// DeleteServiceOperation returns a new DeleteServiceOperation from a given name. +// The name must be that of a previously created DeleteServiceOperation, possibly from a different process. +func (c *servicesRESTClient) DeleteServiceOperation(name string) *DeleteServiceOperation { + override := fmt.Sprintf("/v2/%s", name) + return &DeleteServiceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *DeleteServiceOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*runpb.Service, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp runpb.Service + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *DeleteServiceOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*runpb.Service, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp runpb.Service + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *DeleteServiceOperation) Metadata() (*runpb.Service, error) { + var meta runpb.Service + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *DeleteServiceOperation) Done() bool { + return op.lro.Done() +} + +// 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 *DeleteServiceOperation) Name() string { + return op.lro.Name() +} + +// UpdateServiceOperation manages a long-running operation from UpdateService. +type UpdateServiceOperation struct { + lro *longrunning.Operation + pollPath string } // UpdateServiceOperation returns a new UpdateServiceOperation from a given name. @@ -807,10 +1742,21 @@ func (c *servicesGRPCClient) UpdateServiceOperation(name string) *UpdateServiceO } } +// UpdateServiceOperation returns a new UpdateServiceOperation from a given name. +// The name must be that of a previously created UpdateServiceOperation, possibly from a different process. +func (c *servicesRESTClient) UpdateServiceOperation(name string) *UpdateServiceOperation { + override := fmt.Sprintf("/v2/%s", name) + return &UpdateServiceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateServiceOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*runpb.Service, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp runpb.Service if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -828,6 +1774,7 @@ func (op *UpdateServiceOperation) Wait(ctx context.Context, opts ...gax.CallOpti // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateServiceOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*runpb.Service, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp runpb.Service if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/run/apiv2/services_client_example_test.go b/run/apiv2/services_client_example_test.go index 2701608d31b9..59fd56491007 100644 --- a/run/apiv2/services_client_example_test.go +++ b/run/apiv2/services_client_example_test.go @@ -43,6 +43,23 @@ func ExampleNewServicesClient() { _ = c } +func ExampleNewServicesRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := run.NewServicesRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleServicesClient_CreateService() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/run/apiv2/tasks_client.go b/run/apiv2/tasks_client.go index 0cd747c45e86..8e6a8bc793a0 100644 --- a/run/apiv2/tasks_client.go +++ b/run/apiv2/tasks_client.go @@ -19,18 +19,23 @@ package run import ( "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" runpb "cloud.google.com/go/run/apiv2/runpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -67,6 +72,16 @@ func defaultTasksCallOptions() *TasksCallOptions { } } +func defaultTasksRESTCallOptions() *TasksCallOptions { + return &TasksCallOptions{ + GetTask: []gax.CallOption{}, + ListTasks: []gax.CallOption{}, + DeleteOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalTasksClient is an interface that defines the methods available from Cloud Run Admin API. type internalTasksClient interface { Close() error @@ -223,6 +238,74 @@ func (c *tasksGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type tasksRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing TasksClient + CallOptions **TasksCallOptions +} + +// NewTasksRESTClient creates a new tasks rest client. +// +// Cloud Run Task Control Plane API. +func NewTasksRESTClient(ctx context.Context, opts ...option.ClientOption) (*TasksClient, error) { + clientOpts := append(defaultTasksRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultTasksRESTCallOptions() + c := &tasksRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &TasksClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultTasksRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://run.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://run.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://run.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *tasksRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *tasksRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *tasksRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *tasksGRPCClient) GetTask(ctx context.Context, req *runpb.GetTaskRequest, opts ...gax.CallOption) (*runpb.Task, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -360,6 +443,344 @@ func (c *tasksGRPCClient) ListOperations(ctx context.Context, req *longrunningpb return it } +// GetTask gets information about a Task. +func (c *tasksRESTClient) GetTask(ctx context.Context, req *runpb.GetTaskRequest, opts ...gax.CallOption) (*runpb.Task, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetTask[0:len((*c.CallOptions).GetTask):len((*c.CallOptions).GetTask)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &runpb.Task{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListTasks lists Tasks from an Execution of a Job. +func (c *tasksRESTClient) ListTasks(ctx context.Context, req *runpb.ListTasksRequest, opts ...gax.CallOption) *TaskIterator { + it := &TaskIterator{} + req = proto.Clone(req).(*runpb.ListTasksRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*runpb.Task, string, error) { + resp := &runpb.ListTasksResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/tasks", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + if req.GetShowDeleted() { + params.Add("showDeleted", fmt.Sprintf("%v", req.GetShowDeleted())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetTasks(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// DeleteOperation is a utility method from google.longrunning.Operations. +func (c *tasksRESTClient) DeleteOperation(ctx context.Context, req *longrunningpb.DeleteOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *tasksRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *tasksRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + // TaskIterator manages a stream of *runpb.Task. type TaskIterator struct { items []*runpb.Task diff --git a/run/apiv2/tasks_client_example_test.go b/run/apiv2/tasks_client_example_test.go index 13e229894098..21073e345e02 100644 --- a/run/apiv2/tasks_client_example_test.go +++ b/run/apiv2/tasks_client_example_test.go @@ -42,6 +42,23 @@ func ExampleNewTasksClient() { _ = c } +func ExampleNewTasksRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := run.NewTasksRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleTasksClient_GetTask() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/scheduler/apiv1/cloud_scheduler_client.go b/scheduler/apiv1/cloud_scheduler_client.go index 0ea1b13906cf..7135ee795f77 100644 --- a/scheduler/apiv1/cloud_scheduler_client.go +++ b/scheduler/apiv1/cloud_scheduler_client.go @@ -17,21 +17,27 @@ package scheduler import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" schedulerpb "cloud.google.com/go/scheduler/apiv1/schedulerpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -107,6 +113,49 @@ func defaultCloudSchedulerCallOptions() *CloudSchedulerCallOptions { } } +func defaultCloudSchedulerRESTCallOptions() *CloudSchedulerCallOptions { + return &CloudSchedulerCallOptions{ + ListJobs: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + GetJob: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + CreateJob: []gax.CallOption{}, + UpdateJob: []gax.CallOption{}, + DeleteJob: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + PauseJob: []gax.CallOption{}, + ResumeJob: []gax.CallOption{}, + RunJob: []gax.CallOption{}, + } +} + // internalCloudSchedulerClient is an interface that defines the methods available from Cloud Scheduler API. type internalCloudSchedulerClient interface { Close() error @@ -302,6 +351,75 @@ func (c *cloudSchedulerGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type cloudSchedulerRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing CloudSchedulerClient + CallOptions **CloudSchedulerCallOptions +} + +// NewCloudSchedulerRESTClient creates a new cloud scheduler rest client. +// +// The Cloud Scheduler API allows external entities to reliably +// schedule asynchronous jobs. +func NewCloudSchedulerRESTClient(ctx context.Context, opts ...option.ClientOption) (*CloudSchedulerClient, error) { + clientOpts := append(defaultCloudSchedulerRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultCloudSchedulerRESTCallOptions() + c := &cloudSchedulerRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &CloudSchedulerClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultCloudSchedulerRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://cloudscheduler.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://cloudscheduler.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://cloudscheduler.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *cloudSchedulerRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *cloudSchedulerRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *cloudSchedulerRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *cloudSchedulerGRPCClient) ListJobs(ctx context.Context, req *schedulerpb.ListJobsRequest, opts ...gax.CallOption) *JobIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -497,6 +615,543 @@ func (c *cloudSchedulerGRPCClient) RunJob(ctx context.Context, req *schedulerpb. return resp, nil } +// ListJobs lists jobs. +func (c *cloudSchedulerRESTClient) ListJobs(ctx context.Context, req *schedulerpb.ListJobsRequest, opts ...gax.CallOption) *JobIterator { + it := &JobIterator{} + req = proto.Clone(req).(*schedulerpb.ListJobsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*schedulerpb.Job, string, error) { + resp := &schedulerpb.ListJobsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/jobs", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetJobs(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetJob gets a job. +func (c *cloudSchedulerRESTClient) GetJob(ctx context.Context, req *schedulerpb.GetJobRequest, opts ...gax.CallOption) (*schedulerpb.Job, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetJob[0:len((*c.CallOptions).GetJob):len((*c.CallOptions).GetJob)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &schedulerpb.Job{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateJob creates a job. +func (c *cloudSchedulerRESTClient) CreateJob(ctx context.Context, req *schedulerpb.CreateJobRequest, opts ...gax.CallOption) (*schedulerpb.Job, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetJob() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/jobs", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateJob[0:len((*c.CallOptions).CreateJob):len((*c.CallOptions).CreateJob)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &schedulerpb.Job{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateJob updates a job. +// +// If successful, the updated Job is returned. If the job does +// not exist, NOT_FOUND is returned. +// +// If UpdateJob does not successfully return, it is possible for the +// job to be in an Job.State.UPDATE_FAILED state. A job in this state may +// not be executed. If this happens, retry the UpdateJob request +// until a successful response is received. +func (c *cloudSchedulerRESTClient) UpdateJob(ctx context.Context, req *schedulerpb.UpdateJobRequest, opts ...gax.CallOption) (*schedulerpb.Job, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetJob() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetJob().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "job.name", url.QueryEscape(req.GetJob().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateJob[0:len((*c.CallOptions).UpdateJob):len((*c.CallOptions).UpdateJob)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &schedulerpb.Job{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteJob deletes a job. +func (c *cloudSchedulerRESTClient) DeleteJob(ctx context.Context, req *schedulerpb.DeleteJobRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// PauseJob pauses a job. +// +// If a job is paused then the system will stop executing the job +// until it is re-enabled via ResumeJob. The +// state of the job is stored in state; if paused it +// will be set to Job.State.PAUSED. A job must be in Job.State.ENABLED +// to be paused. +func (c *cloudSchedulerRESTClient) PauseJob(ctx context.Context, req *schedulerpb.PauseJobRequest, opts ...gax.CallOption) (*schedulerpb.Job, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:pause", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).PauseJob[0:len((*c.CallOptions).PauseJob):len((*c.CallOptions).PauseJob)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &schedulerpb.Job{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ResumeJob resume a job. +// +// This method reenables a job after it has been Job.State.PAUSED. The +// state of a job is stored in Job.state; after calling this method it +// will be set to Job.State.ENABLED. A job must be in +// Job.State.PAUSED to be resumed. +func (c *cloudSchedulerRESTClient) ResumeJob(ctx context.Context, req *schedulerpb.ResumeJobRequest, opts ...gax.CallOption) (*schedulerpb.Job, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:resume", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).ResumeJob[0:len((*c.CallOptions).ResumeJob):len((*c.CallOptions).ResumeJob)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &schedulerpb.Job{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// RunJob forces a job to run now. +// +// When this method is called, Cloud Scheduler will dispatch the job, even +// if the job is already running. +func (c *cloudSchedulerRESTClient) RunJob(ctx context.Context, req *schedulerpb.RunJobRequest, opts ...gax.CallOption) (*schedulerpb.Job, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:run", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).RunJob[0:len((*c.CallOptions).RunJob):len((*c.CallOptions).RunJob)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &schedulerpb.Job{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + // JobIterator manages a stream of *schedulerpb.Job. type JobIterator struct { items []*schedulerpb.Job diff --git a/scheduler/apiv1/cloud_scheduler_client_example_test.go b/scheduler/apiv1/cloud_scheduler_client_example_test.go index 7087d8aa2ca1..e476241e7075 100644 --- a/scheduler/apiv1/cloud_scheduler_client_example_test.go +++ b/scheduler/apiv1/cloud_scheduler_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewCloudSchedulerClient() { _ = c } +func ExampleNewCloudSchedulerRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := scheduler.NewCloudSchedulerRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleCloudSchedulerClient_ListJobs() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/scheduler/apiv1/doc.go b/scheduler/apiv1/doc.go index f527992413b0..7157f88572d6 100644 --- a/scheduler/apiv1/doc.go +++ b/scheduler/apiv1/doc.go @@ -86,6 +86,8 @@ package scheduler // import "cloud.google.com/go/scheduler/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -174,3 +176,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/scheduler/apiv1/gapic_metadata.json b/scheduler/apiv1/gapic_metadata.json index d0dd864d7eed..b8f477be6669 100644 --- a/scheduler/apiv1/gapic_metadata.json +++ b/scheduler/apiv1/gapic_metadata.json @@ -51,6 +51,51 @@ ] } } + }, + "rest": { + "libraryClient": "CloudSchedulerClient", + "rpcs": { + "CreateJob": { + "methods": [ + "CreateJob" + ] + }, + "DeleteJob": { + "methods": [ + "DeleteJob" + ] + }, + "GetJob": { + "methods": [ + "GetJob" + ] + }, + "ListJobs": { + "methods": [ + "ListJobs" + ] + }, + "PauseJob": { + "methods": [ + "PauseJob" + ] + }, + "ResumeJob": { + "methods": [ + "ResumeJob" + ] + }, + "RunJob": { + "methods": [ + "RunJob" + ] + }, + "UpdateJob": { + "methods": [ + "UpdateJob" + ] + } + } } } } diff --git a/scheduler/apiv1/schedulerpb/cloudscheduler.pb.go b/scheduler/apiv1/schedulerpb/cloudscheduler.pb.go index 67fbc8f6c3ec..b1c7cf861a64 100644 --- a/scheduler/apiv1/schedulerpb/cloudscheduler.pb.go +++ b/scheduler/apiv1/schedulerpb/cloudscheduler.pb.go @@ -15,8 +15,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/scheduler/v1/cloudscheduler.proto package schedulerpb diff --git a/scheduler/apiv1/schedulerpb/job.pb.go b/scheduler/apiv1/schedulerpb/job.pb.go index 72e3f53cc974..57658f5a3da2 100644 --- a/scheduler/apiv1/schedulerpb/job.pb.go +++ b/scheduler/apiv1/schedulerpb/job.pb.go @@ -15,8 +15,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/scheduler/v1/job.proto package schedulerpb @@ -119,17 +119,17 @@ type Job struct { // The job name. For example: // `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. // - // - `PROJECT_ID` can contain letters ([A-Za-z]), numbers ([0-9]), - // hyphens (-), colons (:), or periods (.). - // For more information, see - // [Identifying - // projects](https://cloud.google.com/resource-manager/docs/creating-managing-projects#identifying_projects) - // - `LOCATION_ID` is the canonical ID for the job's location. - // The list of available locations can be obtained by calling - // [ListLocations][google.cloud.location.Locations.ListLocations]. - // For more information, see https://cloud.google.com/about/locations/. - // - `JOB_ID` can contain only letters ([A-Za-z]), numbers ([0-9]), - // hyphens (-), or underscores (_). The maximum length is 500 characters. + // * `PROJECT_ID` can contain letters ([A-Za-z]), numbers ([0-9]), + // hyphens (-), colons (:), or periods (.). + // For more information, see + // [Identifying + // projects](https://cloud.google.com/resource-manager/docs/creating-managing-projects#identifying_projects) + // * `LOCATION_ID` is the canonical ID for the job's location. + // The list of available locations can be obtained by calling + // [ListLocations][google.cloud.location.Locations.ListLocations]. + // For more information, see https://cloud.google.com/about/locations/. + // * `JOB_ID` can contain only letters ([A-Za-z]), numbers ([0-9]), + // hyphens (-), or underscores (_). The maximum length is 500 characters. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Optionally caller-specified in [CreateJob][google.cloud.scheduler.v1.CloudScheduler.CreateJob] or // [UpdateJob][google.cloud.scheduler.v1.CloudScheduler.UpdateJob]. @@ -142,7 +142,6 @@ type Job struct { // Delivery settings containing destination and parameters. // // Types that are assignable to Target: - // // *Job_PubsubTarget // *Job_AppEngineHttpTarget // *Job_HttpTarget @@ -202,9 +201,9 @@ type Job struct { // to the [RetryConfig][google.cloud.scheduler.v1.RetryConfig]. // // The allowed duration for this deadline is: - // - For [HTTP targets][google.cloud.scheduler.v1.Job.http_target], between 15 seconds and 30 minutes. - // - For [App Engine HTTP targets][google.cloud.scheduler.v1.Job.app_engine_http_target], between 15 - // seconds and 24 hours. + // * For [HTTP targets][google.cloud.scheduler.v1.Job.http_target], between 15 seconds and 30 minutes. + // * For [App Engine HTTP targets][google.cloud.scheduler.v1.Job.app_engine_http_target], between 15 + // seconds and 24 hours. AttemptDeadline *durationpb.Duration `protobuf:"bytes,22,opt,name=attempt_deadline,json=attemptDeadline,proto3" json:"attempt_deadline,omitempty"` } diff --git a/scheduler/apiv1/schedulerpb/target.pb.go b/scheduler/apiv1/schedulerpb/target.pb.go index 31347bb53e97..0c73780e5030 100644 --- a/scheduler/apiv1/schedulerpb/target.pb.go +++ b/scheduler/apiv1/schedulerpb/target.pb.go @@ -15,8 +15,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/scheduler/v1/target.proto package schedulerpb @@ -156,7 +156,6 @@ type HttpTarget struct { // field will be overridden. // // Types that are assignable to AuthorizationHeader: - // // *HttpTarget_OauthToken // *HttpTarget_OidcToken AuthorizationHeader isHttpTarget_AuthorizationHeader `protobuf_oneof:"authorization_header"` @@ -307,23 +306,23 @@ type AppEngineHttpTarget struct { // // Cloud Scheduler sets some headers to default values: // - // - `User-Agent`: By default, this header is - // `"AppEngine-Google; (+http://code.google.com/appengine)"`. - // This header can be modified, but Cloud Scheduler will append - // `"AppEngine-Google; (+http://code.google.com/appengine)"` to the - // modified `User-Agent`. - // - `X-CloudScheduler`: This header will be set to true. + // * `User-Agent`: By default, this header is + // `"AppEngine-Google; (+http://code.google.com/appengine)"`. + // This header can be modified, but Cloud Scheduler will append + // `"AppEngine-Google; (+http://code.google.com/appengine)"` to the + // modified `User-Agent`. + // * `X-CloudScheduler`: This header will be set to true. // // If the job has an [body][google.cloud.scheduler.v1.AppEngineHttpTarget.body], Cloud Scheduler sets // the following headers: // - // - `Content-Type`: By default, the `Content-Type` header is set to - // `"application/octet-stream"`. The default can be overridden by explictly - // setting `Content-Type` to a particular media type when the job is - // created. - // For example, `Content-Type` can be set to `"application/json"`. - // - `Content-Length`: This is computed by Cloud Scheduler. This value is - // output only. It cannot be changed. + // * `Content-Type`: By default, the `Content-Type` header is set to + // `"application/octet-stream"`. The default can be overridden by explictly + // setting `Content-Type` to a particular media type when the job is + // created. + // For example, `Content-Type` can be set to `"application/json"`. + // * `Content-Length`: This is computed by Cloud Scheduler. This value is + // output only. It cannot be changed. // // The headers below are output only. They cannot be set or overridden: // @@ -535,41 +534,43 @@ type AppEngineRouting struct { // // The host is constructed as: // - // - `host = [application_domain_name]`
- // `| [service] + '.' + [application_domain_name]`
- // `| [version] + '.' + [application_domain_name]`
- // `| [version_dot_service]+ '.' + [application_domain_name]`
- // `| [instance] + '.' + [application_domain_name]`
- // `| [instance_dot_service] + '.' + [application_domain_name]`
- // `| [instance_dot_version] + '.' + [application_domain_name]`
- // `| [instance_dot_version_dot_service] + '.' + [application_domain_name]` // - // - `application_domain_name` = The domain name of the app, for - // example .appspot.com, which is associated with the - // job's project ID. + // * `host = [application_domain_name]`
+ // `| [service] + '.' + [application_domain_name]`
+ // `| [version] + '.' + [application_domain_name]`
+ // `| [version_dot_service]+ '.' + [application_domain_name]`
+ // `| [instance] + '.' + [application_domain_name]`
+ // `| [instance_dot_service] + '.' + [application_domain_name]`
+ // `| [instance_dot_version] + '.' + [application_domain_name]`
+ // `| [instance_dot_version_dot_service] + '.' + [application_domain_name]` + // + // * `application_domain_name` = The domain name of the app, for + // example .appspot.com, which is associated with the + // job's project ID. // // * `service =` [service][google.cloud.scheduler.v1.AppEngineRouting.service] // // * `version =` [version][google.cloud.scheduler.v1.AppEngineRouting.version] // - // - `version_dot_service =` - // [version][google.cloud.scheduler.v1.AppEngineRouting.version] `+ '.' +` - // [service][google.cloud.scheduler.v1.AppEngineRouting.service] + // * `version_dot_service =` + // [version][google.cloud.scheduler.v1.AppEngineRouting.version] `+ '.' +` + // [service][google.cloud.scheduler.v1.AppEngineRouting.service] // // * `instance =` [instance][google.cloud.scheduler.v1.AppEngineRouting.instance] // - // - `instance_dot_service =` - // [instance][google.cloud.scheduler.v1.AppEngineRouting.instance] `+ '.' +` - // [service][google.cloud.scheduler.v1.AppEngineRouting.service] + // * `instance_dot_service =` + // [instance][google.cloud.scheduler.v1.AppEngineRouting.instance] `+ '.' +` + // [service][google.cloud.scheduler.v1.AppEngineRouting.service] + // + // * `instance_dot_version =` + // [instance][google.cloud.scheduler.v1.AppEngineRouting.instance] `+ '.' +` + // [version][google.cloud.scheduler.v1.AppEngineRouting.version] // - // - `instance_dot_version =` - // [instance][google.cloud.scheduler.v1.AppEngineRouting.instance] `+ '.' +` - // [version][google.cloud.scheduler.v1.AppEngineRouting.version] + // * `instance_dot_version_dot_service =` + // [instance][google.cloud.scheduler.v1.AppEngineRouting.instance] `+ '.' +` + // [version][google.cloud.scheduler.v1.AppEngineRouting.version] `+ '.' +` + // [service][google.cloud.scheduler.v1.AppEngineRouting.service] // - // - `instance_dot_version_dot_service =` - // [instance][google.cloud.scheduler.v1.AppEngineRouting.instance] `+ '.' +` - // [version][google.cloud.scheduler.v1.AppEngineRouting.version] `+ '.' +` - // [service][google.cloud.scheduler.v1.AppEngineRouting.service] // // If [service][google.cloud.scheduler.v1.AppEngineRouting.service] is empty, then the job will be sent // to the service which is the default service when the job is attempted. diff --git a/scheduler/apiv1beta1/cloud_scheduler_client.go b/scheduler/apiv1beta1/cloud_scheduler_client.go index 899640f6790b..fcbc2e209f60 100644 --- a/scheduler/apiv1beta1/cloud_scheduler_client.go +++ b/scheduler/apiv1beta1/cloud_scheduler_client.go @@ -679,6 +679,7 @@ func (c *cloudSchedulerRESTClient) ListJobs(ctx context.Context, req *schedulerp baseUrl.Path += fmt.Sprintf("/v1beta1/%v/jobs", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -752,6 +753,11 @@ func (c *cloudSchedulerRESTClient) GetJob(ctx context.Context, req *schedulerpb. } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -812,6 +818,11 @@ func (c *cloudSchedulerRESTClient) CreateJob(ctx context.Context, req *scheduler } baseUrl.Path += fmt.Sprintf("/v1beta1/%v/jobs", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -881,6 +892,7 @@ func (c *cloudSchedulerRESTClient) UpdateJob(ctx context.Context, req *scheduler baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetJob().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -944,6 +956,11 @@ func (c *cloudSchedulerRESTClient) DeleteJob(ctx context.Context, req *scheduler } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -991,6 +1008,11 @@ func (c *cloudSchedulerRESTClient) PauseJob(ctx context.Context, req *schedulerp } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:pause", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1055,6 +1077,11 @@ func (c *cloudSchedulerRESTClient) ResumeJob(ctx context.Context, req *scheduler } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:resume", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1117,6 +1144,11 @@ func (c *cloudSchedulerRESTClient) RunJob(ctx context.Context, req *schedulerpb. } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:run", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) diff --git a/scheduler/apiv1beta1/schedulerpb/cloudscheduler.pb.go b/scheduler/apiv1beta1/schedulerpb/cloudscheduler.pb.go index a4135a554c6c..b87246a9b2f0 100644 --- a/scheduler/apiv1beta1/schedulerpb/cloudscheduler.pb.go +++ b/scheduler/apiv1beta1/schedulerpb/cloudscheduler.pb.go @@ -15,8 +15,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/scheduler/v1beta1/cloudscheduler.proto package schedulerpb diff --git a/scheduler/apiv1beta1/schedulerpb/job.pb.go b/scheduler/apiv1beta1/schedulerpb/job.pb.go index efa543e5e7d5..f577c38dd918 100644 --- a/scheduler/apiv1beta1/schedulerpb/job.pb.go +++ b/scheduler/apiv1beta1/schedulerpb/job.pb.go @@ -15,8 +15,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/scheduler/v1beta1/job.proto package schedulerpb @@ -119,17 +119,17 @@ type Job struct { // The job name. For example: // `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. // - // - `PROJECT_ID` can contain letters ([A-Za-z]), numbers ([0-9]), - // hyphens (-), colons (:), or periods (.). - // For more information, see - // [Identifying - // projects](https://cloud.google.com/resource-manager/docs/creating-managing-projects#identifying_projects) - // - `LOCATION_ID` is the canonical ID for the job's location. - // The list of available locations can be obtained by calling - // [ListLocations][google.cloud.location.Locations.ListLocations]. - // For more information, see https://cloud.google.com/about/locations/. - // - `JOB_ID` can contain only letters ([A-Za-z]), numbers ([0-9]), - // hyphens (-), or underscores (_). The maximum length is 500 characters. + // * `PROJECT_ID` can contain letters ([A-Za-z]), numbers ([0-9]), + // hyphens (-), colons (:), or periods (.). + // For more information, see + // [Identifying + // projects](https://cloud.google.com/resource-manager/docs/creating-managing-projects#identifying_projects) + // * `LOCATION_ID` is the canonical ID for the job's location. + // The list of available locations can be obtained by calling + // [ListLocations][google.cloud.location.Locations.ListLocations]. + // For more information, see https://cloud.google.com/about/locations/. + // * `JOB_ID` can contain only letters ([A-Za-z]), numbers ([0-9]), + // hyphens (-), or underscores (_). The maximum length is 500 characters. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Optionally caller-specified in [CreateJob][google.cloud.scheduler.v1beta1.CloudScheduler.CreateJob] or // [UpdateJob][google.cloud.scheduler.v1beta1.CloudScheduler.UpdateJob]. @@ -142,7 +142,6 @@ type Job struct { // Delivery settings containing destination and parameters. // // Types that are assignable to Target: - // // *Job_PubsubTarget // *Job_AppEngineHttpTarget // *Job_HttpTarget @@ -203,10 +202,10 @@ type Job struct { // // The allowed duration for this deadline is: // - // - For [HTTP targets][google.cloud.scheduler.v1beta1.Job.http_target], between 15 seconds and 30 minutes. - // - For [App Engine HTTP targets][google.cloud.scheduler.v1beta1.Job.app_engine_http_target], between 15 - // seconds and 24 hours. - // - For [PubSub targets][google.cloud.scheduler.v1beta1.Job.pubsub_target], this field is ignored. + // * For [HTTP targets][google.cloud.scheduler.v1beta1.Job.http_target], between 15 seconds and 30 minutes. + // * For [App Engine HTTP targets][google.cloud.scheduler.v1beta1.Job.app_engine_http_target], between 15 + // seconds and 24 hours. + // * For [PubSub targets][google.cloud.scheduler.v1beta1.Job.pubsub_target], this field is ignored. AttemptDeadline *durationpb.Duration `protobuf:"bytes,22,opt,name=attempt_deadline,json=attemptDeadline,proto3" json:"attempt_deadline,omitempty"` } diff --git a/scheduler/apiv1beta1/schedulerpb/target.pb.go b/scheduler/apiv1beta1/schedulerpb/target.pb.go index 380e5a04132e..759037946b75 100644 --- a/scheduler/apiv1beta1/schedulerpb/target.pb.go +++ b/scheduler/apiv1beta1/schedulerpb/target.pb.go @@ -15,8 +15,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/scheduler/v1beta1/target.proto package schedulerpb @@ -156,7 +156,6 @@ type HttpTarget struct { // field will be overridden. // // Types that are assignable to AuthorizationHeader: - // // *HttpTarget_OauthToken // *HttpTarget_OidcToken AuthorizationHeader isHttpTarget_AuthorizationHeader `protobuf_oneof:"authorization_header"` @@ -307,23 +306,23 @@ type AppEngineHttpTarget struct { // // Cloud Scheduler sets some headers to default values: // - // - `User-Agent`: By default, this header is - // `"AppEngine-Google; (+http://code.google.com/appengine)"`. - // This header can be modified, but Cloud Scheduler will append - // `"AppEngine-Google; (+http://code.google.com/appengine)"` to the - // modified `User-Agent`. - // - `X-CloudScheduler`: This header will be set to true. + // * `User-Agent`: By default, this header is + // `"AppEngine-Google; (+http://code.google.com/appengine)"`. + // This header can be modified, but Cloud Scheduler will append + // `"AppEngine-Google; (+http://code.google.com/appengine)"` to the + // modified `User-Agent`. + // * `X-CloudScheduler`: This header will be set to true. // // If the job has an [body][google.cloud.scheduler.v1beta1.AppEngineHttpTarget.body], Cloud Scheduler sets // the following headers: // - // - `Content-Type`: By default, the `Content-Type` header is set to - // `"application/octet-stream"`. The default can be overridden by explictly - // setting `Content-Type` to a particular media type when the job is - // created. - // For example, `Content-Type` can be set to `"application/json"`. - // - `Content-Length`: This is computed by Cloud Scheduler. This value is - // output only. It cannot be changed. + // * `Content-Type`: By default, the `Content-Type` header is set to + // `"application/octet-stream"`. The default can be overridden by explictly + // setting `Content-Type` to a particular media type when the job is + // created. + // For example, `Content-Type` can be set to `"application/json"`. + // * `Content-Length`: This is computed by Cloud Scheduler. This value is + // output only. It cannot be changed. // // The headers below are output only. They cannot be set or overridden: // @@ -535,41 +534,43 @@ type AppEngineRouting struct { // // The host is constructed as: // - // - `host = [application_domain_name]`
- // `| [service] + '.' + [application_domain_name]`
- // `| [version] + '.' + [application_domain_name]`
- // `| [version_dot_service]+ '.' + [application_domain_name]`
- // `| [instance] + '.' + [application_domain_name]`
- // `| [instance_dot_service] + '.' + [application_domain_name]`
- // `| [instance_dot_version] + '.' + [application_domain_name]`
- // `| [instance_dot_version_dot_service] + '.' + [application_domain_name]` // - // - `application_domain_name` = The domain name of the app, for - // example .appspot.com, which is associated with the - // job's project ID. + // * `host = [application_domain_name]`
+ // `| [service] + '.' + [application_domain_name]`
+ // `| [version] + '.' + [application_domain_name]`
+ // `| [version_dot_service]+ '.' + [application_domain_name]`
+ // `| [instance] + '.' + [application_domain_name]`
+ // `| [instance_dot_service] + '.' + [application_domain_name]`
+ // `| [instance_dot_version] + '.' + [application_domain_name]`
+ // `| [instance_dot_version_dot_service] + '.' + [application_domain_name]` + // + // * `application_domain_name` = The domain name of the app, for + // example .appspot.com, which is associated with the + // job's project ID. // // * `service =` [service][google.cloud.scheduler.v1beta1.AppEngineRouting.service] // // * `version =` [version][google.cloud.scheduler.v1beta1.AppEngineRouting.version] // - // - `version_dot_service =` - // [version][google.cloud.scheduler.v1beta1.AppEngineRouting.version] `+ '.' +` - // [service][google.cloud.scheduler.v1beta1.AppEngineRouting.service] + // * `version_dot_service =` + // [version][google.cloud.scheduler.v1beta1.AppEngineRouting.version] `+ '.' +` + // [service][google.cloud.scheduler.v1beta1.AppEngineRouting.service] // // * `instance =` [instance][google.cloud.scheduler.v1beta1.AppEngineRouting.instance] // - // - `instance_dot_service =` - // [instance][google.cloud.scheduler.v1beta1.AppEngineRouting.instance] `+ '.' +` - // [service][google.cloud.scheduler.v1beta1.AppEngineRouting.service] + // * `instance_dot_service =` + // [instance][google.cloud.scheduler.v1beta1.AppEngineRouting.instance] `+ '.' +` + // [service][google.cloud.scheduler.v1beta1.AppEngineRouting.service] + // + // * `instance_dot_version =` + // [instance][google.cloud.scheduler.v1beta1.AppEngineRouting.instance] `+ '.' +` + // [version][google.cloud.scheduler.v1beta1.AppEngineRouting.version] // - // - `instance_dot_version =` - // [instance][google.cloud.scheduler.v1beta1.AppEngineRouting.instance] `+ '.' +` - // [version][google.cloud.scheduler.v1beta1.AppEngineRouting.version] + // * `instance_dot_version_dot_service =` + // [instance][google.cloud.scheduler.v1beta1.AppEngineRouting.instance] `+ '.' +` + // [version][google.cloud.scheduler.v1beta1.AppEngineRouting.version] `+ '.' +` + // [service][google.cloud.scheduler.v1beta1.AppEngineRouting.service] // - // - `instance_dot_version_dot_service =` - // [instance][google.cloud.scheduler.v1beta1.AppEngineRouting.instance] `+ '.' +` - // [version][google.cloud.scheduler.v1beta1.AppEngineRouting.version] `+ '.' +` - // [service][google.cloud.scheduler.v1beta1.AppEngineRouting.service] // // If [service][google.cloud.scheduler.v1beta1.AppEngineRouting.service] is empty, then the job will be sent // to the service which is the default service when the job is attempted. diff --git a/secretmanager/apiv1/doc.go b/secretmanager/apiv1/doc.go index 4087b58523a2..1dd8241d46a0 100644 --- a/secretmanager/apiv1/doc.go +++ b/secretmanager/apiv1/doc.go @@ -87,6 +87,8 @@ package secretmanager // import "cloud.google.com/go/secretmanager/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -175,3 +177,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/secretmanager/apiv1/gapic_metadata.json b/secretmanager/apiv1/gapic_metadata.json index a5049c72dadf..56579a4afddf 100644 --- a/secretmanager/apiv1/gapic_metadata.json +++ b/secretmanager/apiv1/gapic_metadata.json @@ -86,6 +86,86 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "AccessSecretVersion": { + "methods": [ + "AccessSecretVersion" + ] + }, + "AddSecretVersion": { + "methods": [ + "AddSecretVersion" + ] + }, + "CreateSecret": { + "methods": [ + "CreateSecret" + ] + }, + "DeleteSecret": { + "methods": [ + "DeleteSecret" + ] + }, + "DestroySecretVersion": { + "methods": [ + "DestroySecretVersion" + ] + }, + "DisableSecretVersion": { + "methods": [ + "DisableSecretVersion" + ] + }, + "EnableSecretVersion": { + "methods": [ + "EnableSecretVersion" + ] + }, + "GetIamPolicy": { + "methods": [ + "GetIamPolicy" + ] + }, + "GetSecret": { + "methods": [ + "GetSecret" + ] + }, + "GetSecretVersion": { + "methods": [ + "GetSecretVersion" + ] + }, + "ListSecretVersions": { + "methods": [ + "ListSecretVersions" + ] + }, + "ListSecrets": { + "methods": [ + "ListSecrets" + ] + }, + "SetIamPolicy": { + "methods": [ + "SetIamPolicy" + ] + }, + "TestIamPermissions": { + "methods": [ + "TestIamPermissions" + ] + }, + "UpdateSecret": { + "methods": [ + "UpdateSecret" + ] + } + } } } } diff --git a/secretmanager/apiv1/secret_manager_client.go b/secretmanager/apiv1/secret_manager_client.go index b08ed1c32448..b26f54007014 100644 --- a/secretmanager/apiv1/secret_manager_client.go +++ b/secretmanager/apiv1/secret_manager_client.go @@ -17,22 +17,28 @@ package secretmanager import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" secretmanagerpb "cloud.google.com/go/secretmanager/apiv1/secretmanagerpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" iampb "google.golang.org/genproto/googleapis/iam/v1" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -100,6 +106,36 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + ListSecrets: []gax.CallOption{}, + CreateSecret: []gax.CallOption{}, + AddSecretVersion: []gax.CallOption{}, + GetSecret: []gax.CallOption{}, + UpdateSecret: []gax.CallOption{}, + DeleteSecret: []gax.CallOption{}, + ListSecretVersions: []gax.CallOption{}, + GetSecretVersion: []gax.CallOption{}, + AccessSecretVersion: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 2000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 2.00, + }, + http.StatusServiceUnavailable, + http.StatusTooManyRequests) + }), + }, + DisableSecretVersion: []gax.CallOption{}, + EnableSecretVersion: []gax.CallOption{}, + DestroySecretVersion: []gax.CallOption{}, + SetIamPolicy: []gax.CallOption{}, + GetIamPolicy: []gax.CallOption{}, + TestIamPermissions: []gax.CallOption{}, + } +} + // internalClient is an interface that defines the methods available from Secret Manager API. type internalClient interface { Close() error @@ -356,6 +392,81 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new secret manager service rest client. +// +// # Secret Manager Service +// +// Manages secrets and operations using those secrets. Implements a REST +// model with the following objects: +// +// Secret +// +// SecretVersion +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://secretmanager.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://secretmanager.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://secretmanager.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) ListSecrets(ctx context.Context, req *secretmanagerpb.ListSecretsRequest, opts ...gax.CallOption) *SecretIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -728,6 +839,1017 @@ func (c *gRPCClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamP return resp, nil } +// ListSecrets lists Secrets. +func (c *restClient) ListSecrets(ctx context.Context, req *secretmanagerpb.ListSecretsRequest, opts ...gax.CallOption) *SecretIterator { + it := &SecretIterator{} + req = proto.Clone(req).(*secretmanagerpb.ListSecretsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*secretmanagerpb.Secret, string, error) { + resp := &secretmanagerpb.ListSecretsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/secrets", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetSecrets(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CreateSecret creates a new Secret containing no SecretVersions. +func (c *restClient) CreateSecret(ctx context.Context, req *secretmanagerpb.CreateSecretRequest, opts ...gax.CallOption) (*secretmanagerpb.Secret, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetSecret() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/secrets", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("secretId", fmt.Sprintf("%v", req.GetSecretId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateSecret[0:len((*c.CallOptions).CreateSecret):len((*c.CallOptions).CreateSecret)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &secretmanagerpb.Secret{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// AddSecretVersion creates a new SecretVersion containing secret data and attaches +// it to an existing Secret. +func (c *restClient) AddSecretVersion(ctx context.Context, req *secretmanagerpb.AddSecretVersionRequest, opts ...gax.CallOption) (*secretmanagerpb.SecretVersion, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:addVersion", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).AddSecretVersion[0:len((*c.CallOptions).AddSecretVersion):len((*c.CallOptions).AddSecretVersion)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &secretmanagerpb.SecretVersion{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetSecret gets metadata for a given Secret. +func (c *restClient) GetSecret(ctx context.Context, req *secretmanagerpb.GetSecretRequest, opts ...gax.CallOption) (*secretmanagerpb.Secret, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetSecret[0:len((*c.CallOptions).GetSecret):len((*c.CallOptions).GetSecret)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &secretmanagerpb.Secret{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateSecret updates metadata of an existing Secret. +func (c *restClient) UpdateSecret(ctx context.Context, req *secretmanagerpb.UpdateSecretRequest, opts ...gax.CallOption) (*secretmanagerpb.Secret, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetSecret() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetSecret().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "secret.name", url.QueryEscape(req.GetSecret().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateSecret[0:len((*c.CallOptions).UpdateSecret):len((*c.CallOptions).UpdateSecret)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &secretmanagerpb.Secret{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteSecret deletes a Secret. +func (c *restClient) DeleteSecret(ctx context.Context, req *secretmanagerpb.DeleteSecretRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetEtag() != "" { + params.Add("etag", fmt.Sprintf("%v", req.GetEtag())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// ListSecretVersions lists SecretVersions. This call does not return secret +// data. +func (c *restClient) ListSecretVersions(ctx context.Context, req *secretmanagerpb.ListSecretVersionsRequest, opts ...gax.CallOption) *SecretVersionIterator { + it := &SecretVersionIterator{} + req = proto.Clone(req).(*secretmanagerpb.ListSecretVersionsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*secretmanagerpb.SecretVersion, string, error) { + resp := &secretmanagerpb.ListSecretVersionsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/versions", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetVersions(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetSecretVersion gets metadata for a SecretVersion. +// +// projects/*/secrets/*/versions/latest is an alias to the most recently +// created SecretVersion. +func (c *restClient) GetSecretVersion(ctx context.Context, req *secretmanagerpb.GetSecretVersionRequest, opts ...gax.CallOption) (*secretmanagerpb.SecretVersion, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetSecretVersion[0:len((*c.CallOptions).GetSecretVersion):len((*c.CallOptions).GetSecretVersion)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &secretmanagerpb.SecretVersion{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// AccessSecretVersion accesses a SecretVersion. This call returns the secret data. +// +// projects/*/secrets/*/versions/latest is an alias to the most recently +// created SecretVersion. +func (c *restClient) AccessSecretVersion(ctx context.Context, req *secretmanagerpb.AccessSecretVersionRequest, opts ...gax.CallOption) (*secretmanagerpb.AccessSecretVersionResponse, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:access", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).AccessSecretVersion[0:len((*c.CallOptions).AccessSecretVersion):len((*c.CallOptions).AccessSecretVersion)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &secretmanagerpb.AccessSecretVersionResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DisableSecretVersion disables a SecretVersion. +// +// Sets the state of the SecretVersion to +// DISABLED. +func (c *restClient) DisableSecretVersion(ctx context.Context, req *secretmanagerpb.DisableSecretVersionRequest, opts ...gax.CallOption) (*secretmanagerpb.SecretVersion, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:disable", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).DisableSecretVersion[0:len((*c.CallOptions).DisableSecretVersion):len((*c.CallOptions).DisableSecretVersion)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &secretmanagerpb.SecretVersion{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// EnableSecretVersion enables a SecretVersion. +// +// Sets the state of the SecretVersion to +// ENABLED. +func (c *restClient) EnableSecretVersion(ctx context.Context, req *secretmanagerpb.EnableSecretVersionRequest, opts ...gax.CallOption) (*secretmanagerpb.SecretVersion, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:enable", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).EnableSecretVersion[0:len((*c.CallOptions).EnableSecretVersion):len((*c.CallOptions).EnableSecretVersion)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &secretmanagerpb.SecretVersion{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DestroySecretVersion destroys a SecretVersion. +// +// Sets the state of the SecretVersion to +// DESTROYED and irrevocably destroys the +// secret data. +func (c *restClient) DestroySecretVersion(ctx context.Context, req *secretmanagerpb.DestroySecretVersionRequest, opts ...gax.CallOption) (*secretmanagerpb.SecretVersion, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:destroy", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).DestroySecretVersion[0:len((*c.CallOptions).DestroySecretVersion):len((*c.CallOptions).DestroySecretVersion)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &secretmanagerpb.SecretVersion{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SetIamPolicy sets the access control policy on the specified secret. Replaces any +// existing policy. +// +// Permissions on SecretVersions are enforced according +// to the policy set on the associated Secret. +func (c *restClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:setIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetIamPolicy gets the access control policy for a secret. +// Returns empty policy if the secret exists and does not have a policy set. +func (c *restClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:getIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetOptions().GetRequestedPolicyVersion() != 0 { + params.Add("options.requestedPolicyVersion", fmt.Sprintf("%v", req.GetOptions().GetRequestedPolicyVersion())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// TestIamPermissions returns permissions that a caller has for the specified secret. +// If the secret does not exist, this call returns an empty set of +// permissions, not a NOT_FOUND error. +// +// Note: This operation is designed to be used for building permission-aware +// UIs and command-line tools, not for authorization checking. This operation +// may “fail open” without warning. +func (c *restClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:testIamPermissions", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.TestIamPermissionsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + // SecretIterator manages a stream of *secretmanagerpb.Secret. type SecretIterator struct { items []*secretmanagerpb.Secret diff --git a/secretmanager/apiv1/secret_manager_client_example_test.go b/secretmanager/apiv1/secret_manager_client_example_test.go index 8605703794fc..072d657368d2 100644 --- a/secretmanager/apiv1/secret_manager_client_example_test.go +++ b/secretmanager/apiv1/secret_manager_client_example_test.go @@ -42,6 +42,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := secretmanager.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_ListSecrets() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/secretmanager/apiv1/secretmanagerpb/resources.pb.go b/secretmanager/apiv1/secretmanagerpb/resources.pb.go index 52cc5b666d3c..24be7eb5fcc5 100644 --- a/secretmanager/apiv1/secretmanagerpb/resources.pb.go +++ b/secretmanager/apiv1/secretmanagerpb/resources.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/secretmanager/v1/resources.proto package secretmanagerpb @@ -141,7 +141,6 @@ type Secret struct { // can be reversed. // // Types that are assignable to Expiration: - // // *Secret_ExpireTime // *Secret_Ttl Expiration isSecret_Expiration `protobuf_oneof:"expiration"` @@ -412,7 +411,6 @@ type Replication struct { // The replication policy for this secret. // // Types that are assignable to Replication: - // // *Replication_Automatic_ // *Replication_UserManaged_ Replication isReplication_Replication `protobuf_oneof:"replication"` @@ -558,7 +556,6 @@ type ReplicationStatus struct { // The replication status of the [SecretVersion][google.cloud.secretmanager.v1.SecretVersion]. // // Types that are assignable to ReplicationStatus: - // // *ReplicationStatus_Automatic // *ReplicationStatus_UserManaged ReplicationStatus isReplicationStatus_ReplicationStatus `protobuf_oneof:"replication_status"` diff --git a/secretmanager/apiv1/secretmanagerpb/service.pb.go b/secretmanager/apiv1/secretmanagerpb/service.pb.go index 5bffd9664326..10f5d2a304fc 100644 --- a/secretmanager/apiv1/secretmanagerpb/service.pb.go +++ b/secretmanager/apiv1/secretmanagerpb/service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/secretmanager/v1/service.proto package secretmanagerpb diff --git a/security/privateca/apiv1/certificate_authority_client.go b/security/privateca/apiv1/certificate_authority_client.go index 6d460739bd2f..0812ee0090aa 100644 --- a/security/privateca/apiv1/certificate_authority_client.go +++ b/security/privateca/apiv1/certificate_authority_client.go @@ -17,9 +17,12 @@ package privateca import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,16 +30,19 @@ import ( lroauto "cloud.google.com/go/longrunning/autogen" privatecapb "cloud.google.com/go/security/privateca/apiv1/privatecapb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" iampb "google.golang.org/genproto/googleapis/iam/v1" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -479,6 +485,364 @@ func defaultCertificateAuthorityCallOptions() *CertificateAuthorityCallOptions { } } +func defaultCertificateAuthorityRESTCallOptions() *CertificateAuthorityCallOptions { + return &CertificateAuthorityCallOptions{ + CreateCertificate: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusInternalServerError, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + GetCertificate: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusInternalServerError, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + ListCertificates: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusInternalServerError, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + RevokeCertificate: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusInternalServerError, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + UpdateCertificate: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusInternalServerError, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + ActivateCertificateAuthority: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusInternalServerError, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + CreateCertificateAuthority: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusInternalServerError, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + DisableCertificateAuthority: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusInternalServerError, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + EnableCertificateAuthority: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusInternalServerError, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + FetchCertificateAuthorityCsr: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusInternalServerError, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + GetCertificateAuthority: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusInternalServerError, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + ListCertificateAuthorities: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusInternalServerError, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + UndeleteCertificateAuthority: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusInternalServerError, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + DeleteCertificateAuthority: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusInternalServerError, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + UpdateCertificateAuthority: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusInternalServerError, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + CreateCaPool: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusInternalServerError, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + UpdateCaPool: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusInternalServerError, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + GetCaPool: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusInternalServerError, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + ListCaPools: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusInternalServerError, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + DeleteCaPool: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusInternalServerError, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + FetchCaCerts: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusInternalServerError, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + GetCertificateRevocationList: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusInternalServerError, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + ListCertificateRevocationLists: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusInternalServerError, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + UpdateCertificateRevocationList: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusInternalServerError, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + CreateCertificateTemplate: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusInternalServerError, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + DeleteCertificateTemplate: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusInternalServerError, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + GetCertificateTemplate: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusInternalServerError, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + ListCertificateTemplates: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusInternalServerError, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + UpdateCertificateTemplate: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusInternalServerError, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + GetIamPolicy: []gax.CallOption{}, + SetIamPolicy: []gax.CallOption{}, + TestIamPermissions: []gax.CallOption{}, + } +} + // internalCertificateAuthorityClient is an interface that defines the methods available from Certificate Authority API. type internalCertificateAuthorityClient interface { Close() error @@ -959,39 +1323,123 @@ func (c *certificateAuthorityGRPCClient) Close() error { return c.connPool.Close() } -func (c *certificateAuthorityGRPCClient) CreateCertificate(ctx context.Context, req *privatecapb.CreateCertificateRequest, opts ...gax.CallOption) (*privatecapb.Certificate, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx - } - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type certificateAuthorityRESTClient struct { + // The http endpoint to connect to. + endpoint string - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).CreateCertificate[0:len((*c.CallOptions).CreateCertificate):len((*c.CallOptions).CreateCertificate)], opts...) - var resp *privatecapb.Certificate - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.certificateAuthorityClient.CreateCertificate(ctx, req, settings.GRPC...) - return err - }, opts...) + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing CertificateAuthorityClient + CallOptions **CertificateAuthorityCallOptions +} + +// NewCertificateAuthorityRESTClient creates a new certificate authority service rest client. +// +// [Certificate Authority Service][google.cloud.security.privateca.v1.CertificateAuthorityService] manages private +// certificate authorities and issued certificates. +func NewCertificateAuthorityRESTClient(ctx context.Context, opts ...option.ClientOption) (*CertificateAuthorityClient, error) { + clientOpts := append(defaultCertificateAuthorityRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) if err != nil { return nil, err } - return resp, nil -} -func (c *certificateAuthorityGRPCClient) GetCertificate(ctx context.Context, req *privatecapb.GetCertificateRequest, opts ...gax.CallOption) (*privatecapb.Certificate, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx + callOpts := defaultCertificateAuthorityRESTCallOptions() + c := &certificateAuthorityRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, } - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + c.setGoogleClientInfo() - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).GetCertificate[0:len((*c.CallOptions).GetCertificate):len((*c.CallOptions).GetCertificate)], opts...) - var resp *privatecapb.Certificate + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &CertificateAuthorityClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultCertificateAuthorityRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://privateca.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://privateca.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://privateca.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *certificateAuthorityRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *certificateAuthorityRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *certificateAuthorityRESTClient) Connection() *grpc.ClientConn { + return nil +} +func (c *certificateAuthorityGRPCClient) CreateCertificate(ctx context.Context, req *privatecapb.CreateCertificateRequest, opts ...gax.CallOption) (*privatecapb.Certificate, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).CreateCertificate[0:len((*c.CallOptions).CreateCertificate):len((*c.CallOptions).CreateCertificate)], opts...) + var resp *privatecapb.Certificate + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.certificateAuthorityClient.CreateCertificate(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *certificateAuthorityGRPCClient) GetCertificate(ctx context.Context, req *privatecapb.GetCertificateRequest, opts ...gax.CallOption) (*privatecapb.Certificate, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).GetCertificate[0:len((*c.CallOptions).GetCertificate):len((*c.CallOptions).GetCertificate)], opts...) + var resp *privatecapb.Certificate err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error resp, err = c.certificateAuthorityClient.GetCertificate(ctx, req, settings.GRPC...) @@ -1740,30 +2188,2303 @@ func (c *certificateAuthorityGRPCClient) UpdateCertificateTemplate(ctx context.C }, nil } -func (c *certificateAuthorityGRPCClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { +func (c *certificateAuthorityGRPCClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + var resp *locationpb.Location + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.locationsClient.GetLocation(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *certificateAuthorityGRPCClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).ListLocations[0:len((*c.CallOptions).ListLocations):len((*c.CallOptions).ListLocations)], opts...) + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.locationsClient.ListLocations(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, "", err + } + + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +func (c *certificateAuthorityGRPCClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) + var resp *iampb.Policy + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.iamPolicyClient.GetIamPolicy(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *certificateAuthorityGRPCClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) + var resp *iampb.Policy + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.iamPolicyClient.SetIamPolicy(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *certificateAuthorityGRPCClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) + var resp *iampb.TestIamPermissionsResponse + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.iamPolicyClient.TestIamPermissions(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return resp, nil +} + +// CreateCertificate create a new Certificate in a given Project, Location from a particular +// CaPool. +func (c *certificateAuthorityRESTClient) CreateCertificate(ctx context.Context, req *privatecapb.CreateCertificateRequest, opts ...gax.CallOption) (*privatecapb.Certificate, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetCertificate() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/certificates", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetCertificateId() != "" { + params.Add("certificateId", fmt.Sprintf("%v", req.GetCertificateId())) + } + if req.GetIssuingCertificateAuthorityId() != "" { + params.Add("issuingCertificateAuthorityId", fmt.Sprintf("%v", req.GetIssuingCertificateAuthorityId())) + } + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateCertificate[0:len((*c.CallOptions).CreateCertificate):len((*c.CallOptions).CreateCertificate)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &privatecapb.Certificate{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetCertificate returns a Certificate. +func (c *certificateAuthorityRESTClient) GetCertificate(ctx context.Context, req *privatecapb.GetCertificateRequest, opts ...gax.CallOption) (*privatecapb.Certificate, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetCertificate[0:len((*c.CallOptions).GetCertificate):len((*c.CallOptions).GetCertificate)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &privatecapb.Certificate{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListCertificates lists Certificates. +func (c *certificateAuthorityRESTClient) ListCertificates(ctx context.Context, req *privatecapb.ListCertificatesRequest, opts ...gax.CallOption) *CertificateIterator { + it := &CertificateIterator{} + req = proto.Clone(req).(*privatecapb.ListCertificatesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*privatecapb.Certificate, string, error) { + resp := &privatecapb.ListCertificatesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/certificates", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetCertificates(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// RevokeCertificate revoke a Certificate. +func (c *certificateAuthorityRESTClient) RevokeCertificate(ctx context.Context, req *privatecapb.RevokeCertificateRequest, opts ...gax.CallOption) (*privatecapb.Certificate, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:revoke", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).RevokeCertificate[0:len((*c.CallOptions).RevokeCertificate):len((*c.CallOptions).RevokeCertificate)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &privatecapb.Certificate{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateCertificate update a Certificate. Currently, the only field you can update is the +// labels field. +func (c *certificateAuthorityRESTClient) UpdateCertificate(ctx context.Context, req *privatecapb.UpdateCertificateRequest, opts ...gax.CallOption) (*privatecapb.Certificate, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetCertificate() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetCertificate().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "certificate.name", url.QueryEscape(req.GetCertificate().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateCertificate[0:len((*c.CallOptions).UpdateCertificate):len((*c.CallOptions).UpdateCertificate)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &privatecapb.Certificate{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ActivateCertificateAuthority activate a CertificateAuthority that is in state +// AWAITING_USER_ACTIVATION +// and is of type SUBORDINATE. After +// the parent Certificate Authority signs a certificate signing request from +// FetchCertificateAuthorityCsr, this method can complete the activation +// process. +func (c *certificateAuthorityRESTClient) ActivateCertificateAuthority(ctx context.Context, req *privatecapb.ActivateCertificateAuthorityRequest, opts ...gax.CallOption) (*ActivateCertificateAuthorityOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:activate", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &ActivateCertificateAuthorityOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// CreateCertificateAuthority create a new CertificateAuthority in a given Project and Location. +func (c *certificateAuthorityRESTClient) CreateCertificateAuthority(ctx context.Context, req *privatecapb.CreateCertificateAuthorityRequest, opts ...gax.CallOption) (*CreateCertificateAuthorityOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetCertificateAuthority() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/certificateAuthorities", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("certificateAuthorityId", fmt.Sprintf("%v", req.GetCertificateAuthorityId())) + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateCertificateAuthorityOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DisableCertificateAuthority disable a CertificateAuthority. +func (c *certificateAuthorityRESTClient) DisableCertificateAuthority(ctx context.Context, req *privatecapb.DisableCertificateAuthorityRequest, opts ...gax.CallOption) (*DisableCertificateAuthorityOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:disable", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DisableCertificateAuthorityOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// EnableCertificateAuthority enable a CertificateAuthority. +func (c *certificateAuthorityRESTClient) EnableCertificateAuthority(ctx context.Context, req *privatecapb.EnableCertificateAuthorityRequest, opts ...gax.CallOption) (*EnableCertificateAuthorityOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:enable", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &EnableCertificateAuthorityOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// FetchCertificateAuthorityCsr fetch a certificate signing request (CSR) from a CertificateAuthority +// that is in state +// AWAITING_USER_ACTIVATION +// and is of type SUBORDINATE. The +// CSR must then be signed by the desired parent Certificate Authority, which +// could be another CertificateAuthority resource, or could be an on-prem +// certificate authority. See also ActivateCertificateAuthority. +func (c *certificateAuthorityRESTClient) FetchCertificateAuthorityCsr(ctx context.Context, req *privatecapb.FetchCertificateAuthorityCsrRequest, opts ...gax.CallOption) (*privatecapb.FetchCertificateAuthorityCsrResponse, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:fetch", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).FetchCertificateAuthorityCsr[0:len((*c.CallOptions).FetchCertificateAuthorityCsr):len((*c.CallOptions).FetchCertificateAuthorityCsr)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &privatecapb.FetchCertificateAuthorityCsrResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetCertificateAuthority returns a CertificateAuthority. +func (c *certificateAuthorityRESTClient) GetCertificateAuthority(ctx context.Context, req *privatecapb.GetCertificateAuthorityRequest, opts ...gax.CallOption) (*privatecapb.CertificateAuthority, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetCertificateAuthority[0:len((*c.CallOptions).GetCertificateAuthority):len((*c.CallOptions).GetCertificateAuthority)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &privatecapb.CertificateAuthority{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListCertificateAuthorities lists CertificateAuthorities. +func (c *certificateAuthorityRESTClient) ListCertificateAuthorities(ctx context.Context, req *privatecapb.ListCertificateAuthoritiesRequest, opts ...gax.CallOption) *CertificateAuthorityIterator { + it := &CertificateAuthorityIterator{} + req = proto.Clone(req).(*privatecapb.ListCertificateAuthoritiesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*privatecapb.CertificateAuthority, string, error) { + resp := &privatecapb.ListCertificateAuthoritiesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/certificateAuthorities", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetCertificateAuthorities(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// UndeleteCertificateAuthority undelete a CertificateAuthority that has been deleted. +func (c *certificateAuthorityRESTClient) UndeleteCertificateAuthority(ctx context.Context, req *privatecapb.UndeleteCertificateAuthorityRequest, opts ...gax.CallOption) (*UndeleteCertificateAuthorityOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:undelete", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UndeleteCertificateAuthorityOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteCertificateAuthority delete a CertificateAuthority. +func (c *certificateAuthorityRESTClient) DeleteCertificateAuthority(ctx context.Context, req *privatecapb.DeleteCertificateAuthorityRequest, opts ...gax.CallOption) (*DeleteCertificateAuthorityOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetIgnoreActiveCertificates() { + params.Add("ignoreActiveCertificates", fmt.Sprintf("%v", req.GetIgnoreActiveCertificates())) + } + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + if req.GetSkipGracePeriod() { + params.Add("skipGracePeriod", fmt.Sprintf("%v", req.GetSkipGracePeriod())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteCertificateAuthorityOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateCertificateAuthority update a CertificateAuthority. +func (c *certificateAuthorityRESTClient) UpdateCertificateAuthority(ctx context.Context, req *privatecapb.UpdateCertificateAuthorityRequest, opts ...gax.CallOption) (*UpdateCertificateAuthorityOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetCertificateAuthority() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetCertificateAuthority().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "certificate_authority.name", url.QueryEscape(req.GetCertificateAuthority().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateCertificateAuthorityOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// CreateCaPool create a CaPool. +func (c *certificateAuthorityRESTClient) CreateCaPool(ctx context.Context, req *privatecapb.CreateCaPoolRequest, opts ...gax.CallOption) (*CreateCaPoolOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetCaPool() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/caPools", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("caPoolId", fmt.Sprintf("%v", req.GetCaPoolId())) + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateCaPoolOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateCaPool update a CaPool. +func (c *certificateAuthorityRESTClient) UpdateCaPool(ctx context.Context, req *privatecapb.UpdateCaPoolRequest, opts ...gax.CallOption) (*UpdateCaPoolOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetCaPool() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetCaPool().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "ca_pool.name", url.QueryEscape(req.GetCaPool().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateCaPoolOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetCaPool returns a CaPool. +func (c *certificateAuthorityRESTClient) GetCaPool(ctx context.Context, req *privatecapb.GetCaPoolRequest, opts ...gax.CallOption) (*privatecapb.CaPool, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetCaPool[0:len((*c.CallOptions).GetCaPool):len((*c.CallOptions).GetCaPool)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &privatecapb.CaPool{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListCaPools lists CaPools. +func (c *certificateAuthorityRESTClient) ListCaPools(ctx context.Context, req *privatecapb.ListCaPoolsRequest, opts ...gax.CallOption) *CaPoolIterator { + it := &CaPoolIterator{} + req = proto.Clone(req).(*privatecapb.ListCaPoolsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*privatecapb.CaPool, string, error) { + resp := &privatecapb.ListCaPoolsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/caPools", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetCaPools(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// DeleteCaPool delete a CaPool. +func (c *certificateAuthorityRESTClient) DeleteCaPool(ctx context.Context, req *privatecapb.DeleteCaPoolRequest, opts ...gax.CallOption) (*DeleteCaPoolOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteCaPoolOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// FetchCaCerts fetchCaCerts returns the current trust anchor for the CaPool. This will +// include CA certificate chains for all ACTIVE CertificateAuthority +// resources in the CaPool. +func (c *certificateAuthorityRESTClient) FetchCaCerts(ctx context.Context, req *privatecapb.FetchCaCertsRequest, opts ...gax.CallOption) (*privatecapb.FetchCaCertsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:fetchCaCerts", req.GetCaPool()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "ca_pool", url.QueryEscape(req.GetCaPool()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).FetchCaCerts[0:len((*c.CallOptions).FetchCaCerts):len((*c.CallOptions).FetchCaCerts)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &privatecapb.FetchCaCertsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetCertificateRevocationList returns a CertificateRevocationList. +func (c *certificateAuthorityRESTClient) GetCertificateRevocationList(ctx context.Context, req *privatecapb.GetCertificateRevocationListRequest, opts ...gax.CallOption) (*privatecapb.CertificateRevocationList, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetCertificateRevocationList[0:len((*c.CallOptions).GetCertificateRevocationList):len((*c.CallOptions).GetCertificateRevocationList)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &privatecapb.CertificateRevocationList{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListCertificateRevocationLists lists CertificateRevocationLists. +func (c *certificateAuthorityRESTClient) ListCertificateRevocationLists(ctx context.Context, req *privatecapb.ListCertificateRevocationListsRequest, opts ...gax.CallOption) *CertificateRevocationListIterator { + it := &CertificateRevocationListIterator{} + req = proto.Clone(req).(*privatecapb.ListCertificateRevocationListsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*privatecapb.CertificateRevocationList, string, error) { + resp := &privatecapb.ListCertificateRevocationListsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/certificateRevocationLists", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetCertificateRevocationLists(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// UpdateCertificateRevocationList update a CertificateRevocationList. +func (c *certificateAuthorityRESTClient) UpdateCertificateRevocationList(ctx context.Context, req *privatecapb.UpdateCertificateRevocationListRequest, opts ...gax.CallOption) (*UpdateCertificateRevocationListOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetCertificateRevocationList() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetCertificateRevocationList().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "certificate_revocation_list.name", url.QueryEscape(req.GetCertificateRevocationList().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateCertificateRevocationListOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// CreateCertificateTemplate create a new CertificateTemplate in a given Project and Location. +func (c *certificateAuthorityRESTClient) CreateCertificateTemplate(ctx context.Context, req *privatecapb.CreateCertificateTemplateRequest, opts ...gax.CallOption) (*CreateCertificateTemplateOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetCertificateTemplate() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/certificateTemplates", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("certificateTemplateId", fmt.Sprintf("%v", req.GetCertificateTemplateId())) + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateCertificateTemplateOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteCertificateTemplate deleteCertificateTemplate deletes a CertificateTemplate. +func (c *certificateAuthorityRESTClient) DeleteCertificateTemplate(ctx context.Context, req *privatecapb.DeleteCertificateTemplateRequest, opts ...gax.CallOption) (*DeleteCertificateTemplateOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteCertificateTemplateOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetCertificateTemplate returns a CertificateTemplate. +func (c *certificateAuthorityRESTClient) GetCertificateTemplate(ctx context.Context, req *privatecapb.GetCertificateTemplateRequest, opts ...gax.CallOption) (*privatecapb.CertificateTemplate, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetCertificateTemplate[0:len((*c.CallOptions).GetCertificateTemplate):len((*c.CallOptions).GetCertificateTemplate)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &privatecapb.CertificateTemplate{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListCertificateTemplates lists CertificateTemplates. +func (c *certificateAuthorityRESTClient) ListCertificateTemplates(ctx context.Context, req *privatecapb.ListCertificateTemplatesRequest, opts ...gax.CallOption) *CertificateTemplateIterator { + it := &CertificateTemplateIterator{} + req = proto.Clone(req).(*privatecapb.ListCertificateTemplatesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*privatecapb.CertificateTemplate, string, error) { + resp := &privatecapb.ListCertificateTemplatesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/certificateTemplates", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetCertificateTemplates(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// UpdateCertificateTemplate update a CertificateTemplate. +func (c *certificateAuthorityRESTClient) UpdateCertificateTemplate(ctx context.Context, req *privatecapb.UpdateCertificateTemplateRequest, opts ...gax.CallOption) (*UpdateCertificateTemplateOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetCertificateTemplate() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetCertificateTemplate().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "certificate_template.name", url.QueryEscape(req.GetCertificateTemplate().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateCertificateTemplateOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetLocation gets information about a location. +func (c *certificateAuthorityRESTClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) - var resp *locationpb.Location - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.locationsClient.GetLocation(ctx, req, settings.GRPC...) - return err + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil }, opts...) - if err != nil { - return nil, err + if e != nil { + return nil, e } return resp, nil } -func (c *certificateAuthorityGRPCClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) - - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append((*c.CallOptions).ListLocations[0:len((*c.CallOptions).ListLocations):len((*c.CallOptions).ListLocations)], opts...) +// ListLocations lists information about the supported locations for this service. +func (c *certificateAuthorityRESTClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { it := &LocationIterator{} req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { resp := &locationpb.ListLocationsResponse{} if pageToken != "" { @@ -1774,18 +4495,66 @@ func (c *certificateAuthorityGRPCClient) ListLocations(ctx context.Context, req } else if pageSize != 0 { req.PageSize = int32(pageSize) } - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.locationsClient.ListLocations(ctx, req, settings.GRPC...) - return err - }, opts...) + baseUrl, err := url.Parse(c.endpoint) if err != nil { return nil, "", err } + baseUrl.Path += fmt.Sprintf("/v1/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } it.Response = resp return resp.GetLocations(), resp.GetNextPageToken(), nil } + fetch := func(pageSize int, pageToken string) (string, error) { items, nextPageToken, err := it.InternalFetch(pageSize, pageToken) if err != nil { @@ -1802,60 +4571,210 @@ func (c *certificateAuthorityGRPCClient) ListLocations(ctx context.Context, req return it } -func (c *certificateAuthorityGRPCClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { +// GetIamPolicy gets the access control policy for a resource. Returns an empty policy +// if the resource exists and does not have a policy set. +func (c *certificateAuthorityRESTClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:getIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetOptions().GetRequestedPolicyVersion() != 0 { + params.Add("options.requestedPolicyVersion", fmt.Sprintf("%v", req.GetOptions().GetRequestedPolicyVersion())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) - var resp *iampb.Policy - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.iamPolicyClient.GetIamPolicy(ctx, req, settings.GRPC...) - return err + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil }, opts...) - if err != nil { - return nil, err + if e != nil { + return nil, e } return resp, nil } -func (c *certificateAuthorityGRPCClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { +// SetIamPolicy sets the access control policy on the specified resource. Replaces +// any existing policy. +// +// Can return NOT_FOUND, INVALID_ARGUMENT, and PERMISSION_DENIED +// errors. +func (c *certificateAuthorityRESTClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:setIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) - var resp *iampb.Policy - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.iamPolicyClient.SetIamPolicy(ctx, req, settings.GRPC...) - return err + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil }, opts...) - if err != nil { - return nil, err + if e != nil { + return nil, e } return resp, nil } -func (c *certificateAuthorityGRPCClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { +// TestIamPermissions returns permissions that a caller has on the specified resource. If the +// resource does not exist, this will return an empty set of +// permissions, not a NOT_FOUND error. +// +// Note: This operation is designed to be used for building +// permission-aware UIs and command-line tools, not for authorization +// checking. This operation may “fail open” without warning. +func (c *certificateAuthorityRESTClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:testIamPermissions", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) - var resp *iampb.TestIamPermissionsResponse - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.iamPolicyClient.TestIamPermissions(ctx, req, settings.GRPC...) - return err + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.TestIamPermissionsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil }, opts...) - if err != nil { - return nil, err + if e != nil { + return nil, e } return resp, nil } // ActivateCertificateAuthorityOperation manages a long-running operation from ActivateCertificateAuthority. type ActivateCertificateAuthorityOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // ActivateCertificateAuthorityOperation returns a new ActivateCertificateAuthorityOperation from a given name. @@ -1866,10 +4785,21 @@ func (c *certificateAuthorityGRPCClient) ActivateCertificateAuthorityOperation(n } } +// ActivateCertificateAuthorityOperation returns a new ActivateCertificateAuthorityOperation from a given name. +// The name must be that of a previously created ActivateCertificateAuthorityOperation, possibly from a different process. +func (c *certificateAuthorityRESTClient) ActivateCertificateAuthorityOperation(name string) *ActivateCertificateAuthorityOperation { + override := fmt.Sprintf("/v1/%s", name) + return &ActivateCertificateAuthorityOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *ActivateCertificateAuthorityOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*privatecapb.CertificateAuthority, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp privatecapb.CertificateAuthority if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1887,6 +4817,7 @@ func (op *ActivateCertificateAuthorityOperation) Wait(ctx context.Context, opts // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *ActivateCertificateAuthorityOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*privatecapb.CertificateAuthority, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp privatecapb.CertificateAuthority if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1924,7 +4855,8 @@ func (op *ActivateCertificateAuthorityOperation) Name() string { // CreateCaPoolOperation manages a long-running operation from CreateCaPool. type CreateCaPoolOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateCaPoolOperation returns a new CreateCaPoolOperation from a given name. @@ -1935,10 +4867,21 @@ func (c *certificateAuthorityGRPCClient) CreateCaPoolOperation(name string) *Cre } } +// CreateCaPoolOperation returns a new CreateCaPoolOperation from a given name. +// The name must be that of a previously created CreateCaPoolOperation, possibly from a different process. +func (c *certificateAuthorityRESTClient) CreateCaPoolOperation(name string) *CreateCaPoolOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateCaPoolOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateCaPoolOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*privatecapb.CaPool, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp privatecapb.CaPool if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1956,6 +4899,7 @@ func (op *CreateCaPoolOperation) Wait(ctx context.Context, opts ...gax.CallOptio // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateCaPoolOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*privatecapb.CaPool, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp privatecapb.CaPool if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1993,7 +4937,8 @@ func (op *CreateCaPoolOperation) Name() string { // CreateCertificateAuthorityOperation manages a long-running operation from CreateCertificateAuthority. type CreateCertificateAuthorityOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateCertificateAuthorityOperation returns a new CreateCertificateAuthorityOperation from a given name. @@ -2004,10 +4949,21 @@ func (c *certificateAuthorityGRPCClient) CreateCertificateAuthorityOperation(nam } } +// CreateCertificateAuthorityOperation returns a new CreateCertificateAuthorityOperation from a given name. +// The name must be that of a previously created CreateCertificateAuthorityOperation, possibly from a different process. +func (c *certificateAuthorityRESTClient) CreateCertificateAuthorityOperation(name string) *CreateCertificateAuthorityOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateCertificateAuthorityOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateCertificateAuthorityOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*privatecapb.CertificateAuthority, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp privatecapb.CertificateAuthority if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2025,6 +4981,7 @@ func (op *CreateCertificateAuthorityOperation) Wait(ctx context.Context, opts .. // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateCertificateAuthorityOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*privatecapb.CertificateAuthority, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp privatecapb.CertificateAuthority if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2062,7 +5019,8 @@ func (op *CreateCertificateAuthorityOperation) Name() string { // CreateCertificateTemplateOperation manages a long-running operation from CreateCertificateTemplate. type CreateCertificateTemplateOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateCertificateTemplateOperation returns a new CreateCertificateTemplateOperation from a given name. @@ -2073,10 +5031,21 @@ func (c *certificateAuthorityGRPCClient) CreateCertificateTemplateOperation(name } } +// CreateCertificateTemplateOperation returns a new CreateCertificateTemplateOperation from a given name. +// The name must be that of a previously created CreateCertificateTemplateOperation, possibly from a different process. +func (c *certificateAuthorityRESTClient) CreateCertificateTemplateOperation(name string) *CreateCertificateTemplateOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateCertificateTemplateOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateCertificateTemplateOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*privatecapb.CertificateTemplate, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp privatecapb.CertificateTemplate if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2094,6 +5063,7 @@ func (op *CreateCertificateTemplateOperation) Wait(ctx context.Context, opts ... // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateCertificateTemplateOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*privatecapb.CertificateTemplate, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp privatecapb.CertificateTemplate if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2131,7 +5101,8 @@ func (op *CreateCertificateTemplateOperation) Name() string { // DeleteCaPoolOperation manages a long-running operation from DeleteCaPool. type DeleteCaPoolOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteCaPoolOperation returns a new DeleteCaPoolOperation from a given name. @@ -2142,10 +5113,21 @@ func (c *certificateAuthorityGRPCClient) DeleteCaPoolOperation(name string) *Del } } +// DeleteCaPoolOperation returns a new DeleteCaPoolOperation from a given name. +// The name must be that of a previously created DeleteCaPoolOperation, possibly from a different process. +func (c *certificateAuthorityRESTClient) DeleteCaPoolOperation(name string) *DeleteCaPoolOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteCaPoolOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteCaPoolOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -2159,6 +5141,7 @@ func (op *DeleteCaPoolOperation) Wait(ctx context.Context, opts ...gax.CallOptio // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteCaPoolOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -2189,7 +5172,8 @@ func (op *DeleteCaPoolOperation) Name() string { // DeleteCertificateAuthorityOperation manages a long-running operation from DeleteCertificateAuthority. type DeleteCertificateAuthorityOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteCertificateAuthorityOperation returns a new DeleteCertificateAuthorityOperation from a given name. @@ -2200,10 +5184,21 @@ func (c *certificateAuthorityGRPCClient) DeleteCertificateAuthorityOperation(nam } } +// DeleteCertificateAuthorityOperation returns a new DeleteCertificateAuthorityOperation from a given name. +// The name must be that of a previously created DeleteCertificateAuthorityOperation, possibly from a different process. +func (c *certificateAuthorityRESTClient) DeleteCertificateAuthorityOperation(name string) *DeleteCertificateAuthorityOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteCertificateAuthorityOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteCertificateAuthorityOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*privatecapb.CertificateAuthority, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp privatecapb.CertificateAuthority if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2221,6 +5216,7 @@ func (op *DeleteCertificateAuthorityOperation) Wait(ctx context.Context, opts .. // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteCertificateAuthorityOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*privatecapb.CertificateAuthority, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp privatecapb.CertificateAuthority if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2258,7 +5254,8 @@ func (op *DeleteCertificateAuthorityOperation) Name() string { // DeleteCertificateTemplateOperation manages a long-running operation from DeleteCertificateTemplate. type DeleteCertificateTemplateOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteCertificateTemplateOperation returns a new DeleteCertificateTemplateOperation from a given name. @@ -2269,10 +5266,21 @@ func (c *certificateAuthorityGRPCClient) DeleteCertificateTemplateOperation(name } } +// DeleteCertificateTemplateOperation returns a new DeleteCertificateTemplateOperation from a given name. +// The name must be that of a previously created DeleteCertificateTemplateOperation, possibly from a different process. +func (c *certificateAuthorityRESTClient) DeleteCertificateTemplateOperation(name string) *DeleteCertificateTemplateOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteCertificateTemplateOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteCertificateTemplateOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -2286,6 +5294,7 @@ func (op *DeleteCertificateTemplateOperation) Wait(ctx context.Context, opts ... // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteCertificateTemplateOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -2316,7 +5325,8 @@ func (op *DeleteCertificateTemplateOperation) Name() string { // DisableCertificateAuthorityOperation manages a long-running operation from DisableCertificateAuthority. type DisableCertificateAuthorityOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DisableCertificateAuthorityOperation returns a new DisableCertificateAuthorityOperation from a given name. @@ -2327,10 +5337,21 @@ func (c *certificateAuthorityGRPCClient) DisableCertificateAuthorityOperation(na } } +// DisableCertificateAuthorityOperation returns a new DisableCertificateAuthorityOperation from a given name. +// The name must be that of a previously created DisableCertificateAuthorityOperation, possibly from a different process. +func (c *certificateAuthorityRESTClient) DisableCertificateAuthorityOperation(name string) *DisableCertificateAuthorityOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DisableCertificateAuthorityOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DisableCertificateAuthorityOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*privatecapb.CertificateAuthority, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp privatecapb.CertificateAuthority if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2348,6 +5369,7 @@ func (op *DisableCertificateAuthorityOperation) Wait(ctx context.Context, opts . // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DisableCertificateAuthorityOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*privatecapb.CertificateAuthority, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp privatecapb.CertificateAuthority if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2385,7 +5407,8 @@ func (op *DisableCertificateAuthorityOperation) Name() string { // EnableCertificateAuthorityOperation manages a long-running operation from EnableCertificateAuthority. type EnableCertificateAuthorityOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // EnableCertificateAuthorityOperation returns a new EnableCertificateAuthorityOperation from a given name. @@ -2396,10 +5419,21 @@ func (c *certificateAuthorityGRPCClient) EnableCertificateAuthorityOperation(nam } } +// EnableCertificateAuthorityOperation returns a new EnableCertificateAuthorityOperation from a given name. +// The name must be that of a previously created EnableCertificateAuthorityOperation, possibly from a different process. +func (c *certificateAuthorityRESTClient) EnableCertificateAuthorityOperation(name string) *EnableCertificateAuthorityOperation { + override := fmt.Sprintf("/v1/%s", name) + return &EnableCertificateAuthorityOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *EnableCertificateAuthorityOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*privatecapb.CertificateAuthority, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp privatecapb.CertificateAuthority if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2417,6 +5451,7 @@ func (op *EnableCertificateAuthorityOperation) Wait(ctx context.Context, opts .. // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *EnableCertificateAuthorityOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*privatecapb.CertificateAuthority, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp privatecapb.CertificateAuthority if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2454,7 +5489,8 @@ func (op *EnableCertificateAuthorityOperation) Name() string { // UndeleteCertificateAuthorityOperation manages a long-running operation from UndeleteCertificateAuthority. type UndeleteCertificateAuthorityOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UndeleteCertificateAuthorityOperation returns a new UndeleteCertificateAuthorityOperation from a given name. @@ -2465,10 +5501,21 @@ func (c *certificateAuthorityGRPCClient) UndeleteCertificateAuthorityOperation(n } } +// UndeleteCertificateAuthorityOperation returns a new UndeleteCertificateAuthorityOperation from a given name. +// The name must be that of a previously created UndeleteCertificateAuthorityOperation, possibly from a different process. +func (c *certificateAuthorityRESTClient) UndeleteCertificateAuthorityOperation(name string) *UndeleteCertificateAuthorityOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UndeleteCertificateAuthorityOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UndeleteCertificateAuthorityOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*privatecapb.CertificateAuthority, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp privatecapb.CertificateAuthority if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2486,6 +5533,7 @@ func (op *UndeleteCertificateAuthorityOperation) Wait(ctx context.Context, opts // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UndeleteCertificateAuthorityOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*privatecapb.CertificateAuthority, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp privatecapb.CertificateAuthority if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2523,7 +5571,8 @@ func (op *UndeleteCertificateAuthorityOperation) Name() string { // UpdateCaPoolOperation manages a long-running operation from UpdateCaPool. type UpdateCaPoolOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateCaPoolOperation returns a new UpdateCaPoolOperation from a given name. @@ -2534,10 +5583,21 @@ func (c *certificateAuthorityGRPCClient) UpdateCaPoolOperation(name string) *Upd } } +// UpdateCaPoolOperation returns a new UpdateCaPoolOperation from a given name. +// The name must be that of a previously created UpdateCaPoolOperation, possibly from a different process. +func (c *certificateAuthorityRESTClient) UpdateCaPoolOperation(name string) *UpdateCaPoolOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateCaPoolOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateCaPoolOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*privatecapb.CaPool, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp privatecapb.CaPool if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2555,6 +5615,7 @@ func (op *UpdateCaPoolOperation) Wait(ctx context.Context, opts ...gax.CallOptio // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateCaPoolOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*privatecapb.CaPool, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp privatecapb.CaPool if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2592,7 +5653,8 @@ func (op *UpdateCaPoolOperation) Name() string { // UpdateCertificateAuthorityOperation manages a long-running operation from UpdateCertificateAuthority. type UpdateCertificateAuthorityOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateCertificateAuthorityOperation returns a new UpdateCertificateAuthorityOperation from a given name. @@ -2603,10 +5665,21 @@ func (c *certificateAuthorityGRPCClient) UpdateCertificateAuthorityOperation(nam } } +// UpdateCertificateAuthorityOperation returns a new UpdateCertificateAuthorityOperation from a given name. +// The name must be that of a previously created UpdateCertificateAuthorityOperation, possibly from a different process. +func (c *certificateAuthorityRESTClient) UpdateCertificateAuthorityOperation(name string) *UpdateCertificateAuthorityOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateCertificateAuthorityOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateCertificateAuthorityOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*privatecapb.CertificateAuthority, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp privatecapb.CertificateAuthority if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2624,6 +5697,7 @@ func (op *UpdateCertificateAuthorityOperation) Wait(ctx context.Context, opts .. // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateCertificateAuthorityOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*privatecapb.CertificateAuthority, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp privatecapb.CertificateAuthority if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2661,7 +5735,8 @@ func (op *UpdateCertificateAuthorityOperation) Name() string { // UpdateCertificateRevocationListOperation manages a long-running operation from UpdateCertificateRevocationList. type UpdateCertificateRevocationListOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateCertificateRevocationListOperation returns a new UpdateCertificateRevocationListOperation from a given name. @@ -2672,10 +5747,21 @@ func (c *certificateAuthorityGRPCClient) UpdateCertificateRevocationListOperatio } } +// UpdateCertificateRevocationListOperation returns a new UpdateCertificateRevocationListOperation from a given name. +// The name must be that of a previously created UpdateCertificateRevocationListOperation, possibly from a different process. +func (c *certificateAuthorityRESTClient) UpdateCertificateRevocationListOperation(name string) *UpdateCertificateRevocationListOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateCertificateRevocationListOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateCertificateRevocationListOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*privatecapb.CertificateRevocationList, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp privatecapb.CertificateRevocationList if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2693,6 +5779,7 @@ func (op *UpdateCertificateRevocationListOperation) Wait(ctx context.Context, op // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateCertificateRevocationListOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*privatecapb.CertificateRevocationList, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp privatecapb.CertificateRevocationList if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2730,7 +5817,8 @@ func (op *UpdateCertificateRevocationListOperation) Name() string { // UpdateCertificateTemplateOperation manages a long-running operation from UpdateCertificateTemplate. type UpdateCertificateTemplateOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateCertificateTemplateOperation returns a new UpdateCertificateTemplateOperation from a given name. @@ -2741,10 +5829,21 @@ func (c *certificateAuthorityGRPCClient) UpdateCertificateTemplateOperation(name } } +// UpdateCertificateTemplateOperation returns a new UpdateCertificateTemplateOperation from a given name. +// The name must be that of a previously created UpdateCertificateTemplateOperation, possibly from a different process. +func (c *certificateAuthorityRESTClient) UpdateCertificateTemplateOperation(name string) *UpdateCertificateTemplateOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateCertificateTemplateOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateCertificateTemplateOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*privatecapb.CertificateTemplate, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp privatecapb.CertificateTemplate if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2762,6 +5861,7 @@ func (op *UpdateCertificateTemplateOperation) Wait(ctx context.Context, opts ... // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateCertificateTemplateOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*privatecapb.CertificateTemplate, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp privatecapb.CertificateTemplate if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/security/privateca/apiv1/certificate_authority_client_example_test.go b/security/privateca/apiv1/certificate_authority_client_example_test.go index 94563b567b01..d756bdbe7de0 100644 --- a/security/privateca/apiv1/certificate_authority_client_example_test.go +++ b/security/privateca/apiv1/certificate_authority_client_example_test.go @@ -43,6 +43,23 @@ func ExampleNewCertificateAuthorityClient() { _ = c } +func ExampleNewCertificateAuthorityRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := privateca.NewCertificateAuthorityRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleCertificateAuthorityClient_CreateCertificate() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/security/privateca/apiv1/doc.go b/security/privateca/apiv1/doc.go index 7151f2e1a479..31eef3f6826f 100644 --- a/security/privateca/apiv1/doc.go +++ b/security/privateca/apiv1/doc.go @@ -83,6 +83,8 @@ package privateca // import "cloud.google.com/go/security/privateca/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -171,3 +173,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/security/privateca/apiv1/gapic_metadata.json b/security/privateca/apiv1/gapic_metadata.json index 15981b873fd4..9e71852c4026 100644 --- a/security/privateca/apiv1/gapic_metadata.json +++ b/security/privateca/apiv1/gapic_metadata.json @@ -181,6 +181,181 @@ ] } } + }, + "rest": { + "libraryClient": "CertificateAuthorityClient", + "rpcs": { + "ActivateCertificateAuthority": { + "methods": [ + "ActivateCertificateAuthority" + ] + }, + "CreateCaPool": { + "methods": [ + "CreateCaPool" + ] + }, + "CreateCertificate": { + "methods": [ + "CreateCertificate" + ] + }, + "CreateCertificateAuthority": { + "methods": [ + "CreateCertificateAuthority" + ] + }, + "CreateCertificateTemplate": { + "methods": [ + "CreateCertificateTemplate" + ] + }, + "DeleteCaPool": { + "methods": [ + "DeleteCaPool" + ] + }, + "DeleteCertificateAuthority": { + "methods": [ + "DeleteCertificateAuthority" + ] + }, + "DeleteCertificateTemplate": { + "methods": [ + "DeleteCertificateTemplate" + ] + }, + "DisableCertificateAuthority": { + "methods": [ + "DisableCertificateAuthority" + ] + }, + "EnableCertificateAuthority": { + "methods": [ + "EnableCertificateAuthority" + ] + }, + "FetchCaCerts": { + "methods": [ + "FetchCaCerts" + ] + }, + "FetchCertificateAuthorityCsr": { + "methods": [ + "FetchCertificateAuthorityCsr" + ] + }, + "GetCaPool": { + "methods": [ + "GetCaPool" + ] + }, + "GetCertificate": { + "methods": [ + "GetCertificate" + ] + }, + "GetCertificateAuthority": { + "methods": [ + "GetCertificateAuthority" + ] + }, + "GetCertificateRevocationList": { + "methods": [ + "GetCertificateRevocationList" + ] + }, + "GetCertificateTemplate": { + "methods": [ + "GetCertificateTemplate" + ] + }, + "GetIamPolicy": { + "methods": [ + "GetIamPolicy" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "ListCaPools": { + "methods": [ + "ListCaPools" + ] + }, + "ListCertificateAuthorities": { + "methods": [ + "ListCertificateAuthorities" + ] + }, + "ListCertificateRevocationLists": { + "methods": [ + "ListCertificateRevocationLists" + ] + }, + "ListCertificateTemplates": { + "methods": [ + "ListCertificateTemplates" + ] + }, + "ListCertificates": { + "methods": [ + "ListCertificates" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "RevokeCertificate": { + "methods": [ + "RevokeCertificate" + ] + }, + "SetIamPolicy": { + "methods": [ + "SetIamPolicy" + ] + }, + "TestIamPermissions": { + "methods": [ + "TestIamPermissions" + ] + }, + "UndeleteCertificateAuthority": { + "methods": [ + "UndeleteCertificateAuthority" + ] + }, + "UpdateCaPool": { + "methods": [ + "UpdateCaPool" + ] + }, + "UpdateCertificate": { + "methods": [ + "UpdateCertificate" + ] + }, + "UpdateCertificateAuthority": { + "methods": [ + "UpdateCertificateAuthority" + ] + }, + "UpdateCertificateRevocationList": { + "methods": [ + "UpdateCertificateRevocationList" + ] + }, + "UpdateCertificateTemplate": { + "methods": [ + "UpdateCertificateTemplate" + ] + } + } } } } diff --git a/security/privateca/apiv1/privatecapb/resources.pb.go b/security/privateca/apiv1/privatecapb/resources.pb.go index a94ea2902d02..c37027c6a01a 100644 --- a/security/privateca/apiv1/privatecapb/resources.pb.go +++ b/security/privateca/apiv1/privatecapb/resources.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/security/privateca/v1/resources.proto package privatecapb @@ -1035,8 +1035,7 @@ type CertificateRevocationList struct { // Output only. The resource name for this [CertificateRevocationList][google.cloud.security.privateca.v1.CertificateRevocationList] in // the format // `projects/*/locations/*/caPools/*certificateAuthorities/*/ - // - // certificateRevocationLists/*`. + // certificateRevocationLists/*`. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Output only. The CRL sequence number that appears in pem_crl. SequenceNumber int64 `protobuf:"varint,2,opt,name=sequence_number,json=sequenceNumber,proto3" json:"sequence_number,omitempty"` @@ -1175,7 +1174,6 @@ type Certificate struct { // The config used to create a signed X.509 certificate. // // Types that are assignable to CertificateConfig: - // // *Certificate_PemCsr // *Certificate_Config CertificateConfig isCertificate_CertificateConfig `protobuf_oneof:"certificate_config"` @@ -1601,7 +1599,6 @@ type SubordinateConfig struct { unknownFields protoimpl.UnknownFields // Types that are assignable to SubordinateConfig: - // // *SubordinateConfig_CertificateAuthority // *SubordinateConfig_PemIssuerChain SubordinateConfig isSubordinateConfig_SubordinateConfig `protobuf_oneof:"subordinate_config"` @@ -2528,7 +2525,6 @@ type CertificateAuthority_KeyVersionSpec struct { unknownFields protoimpl.UnknownFields // Types that are assignable to KeyVersion: - // // *CertificateAuthority_KeyVersionSpec_CloudKmsKeyVersion // *CertificateAuthority_KeyVersionSpec_Algorithm KeyVersion isCertificateAuthority_KeyVersionSpec_KeyVersion `protobuf_oneof:"KeyVersion"` @@ -2813,7 +2809,6 @@ type CaPool_IssuancePolicy_AllowedKeyType struct { unknownFields protoimpl.UnknownFields // Types that are assignable to KeyType: - // // *CaPool_IssuancePolicy_AllowedKeyType_Rsa // *CaPool_IssuancePolicy_AllowedKeyType_EllipticCurve KeyType isCaPool_IssuancePolicy_AllowedKeyType_KeyType `protobuf_oneof:"key_type"` diff --git a/security/privateca/apiv1/privatecapb/service.pb.go b/security/privateca/apiv1/privatecapb/service.pb.go index ce320628d574..75ab74b373e5 100644 --- a/security/privateca/apiv1/privatecapb/service.pb.go +++ b/security/privateca/apiv1/privatecapb/service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/security/privateca/v1/service.proto package privatecapb diff --git a/security/privateca/apiv1beta1/certificate_authority_client.go b/security/privateca/apiv1beta1/certificate_authority_client.go index 6638327c011d..8cd72a119f3a 100644 --- a/security/privateca/apiv1beta1/certificate_authority_client.go +++ b/security/privateca/apiv1beta1/certificate_authority_client.go @@ -1576,6 +1576,7 @@ func (c *certificateAuthorityRESTClient) CreateCertificate(ctx context.Context, baseUrl.Path += fmt.Sprintf("/v1beta1/%v/certificates", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetCertificateId() != "" { params.Add("certificateId", fmt.Sprintf("%v", req.GetCertificateId())) } @@ -1638,6 +1639,11 @@ func (c *certificateAuthorityRESTClient) GetCertificate(ctx context.Context, req } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1705,6 +1711,7 @@ func (c *certificateAuthorityRESTClient) ListCertificates(ctx context.Context, r baseUrl.Path += fmt.Sprintf("/v1beta1/%v/certificates", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1790,6 +1797,11 @@ func (c *certificateAuthorityRESTClient) RevokeCertificate(ctx context.Context, } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:revoke", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1852,6 +1864,7 @@ func (c *certificateAuthorityRESTClient) UpdateCertificate(ctx context.Context, baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetCertificate().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetRequestId() != "" { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -1929,6 +1942,11 @@ func (c *certificateAuthorityRESTClient) ActivateCertificateAuthority(ctx contex } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:activate", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1994,6 +2012,7 @@ func (c *certificateAuthorityRESTClient) CreateCertificateAuthority(ctx context. baseUrl.Path += fmt.Sprintf("/v1beta1/%v/certificateAuthorities", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("certificateAuthorityId", fmt.Sprintf("%v", req.GetCertificateAuthorityId())) if req.GetRequestId() != "" { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) @@ -2064,6 +2083,11 @@ func (c *certificateAuthorityRESTClient) DisableCertificateAuthority(ctx context } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:disable", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2127,6 +2151,11 @@ func (c *certificateAuthorityRESTClient) EnableCertificateAuthority(ctx context. } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:enable", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2190,6 +2219,11 @@ func (c *certificateAuthorityRESTClient) FetchCertificateAuthorityCsr(ctx contex } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:fetch", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2243,6 +2277,11 @@ func (c *certificateAuthorityRESTClient) GetCertificateAuthority(ctx context.Con } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2310,6 +2349,7 @@ func (c *certificateAuthorityRESTClient) ListCertificateAuthorities(ctx context. baseUrl.Path += fmt.Sprintf("/v1beta1/%v/certificateAuthorities", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -2395,6 +2435,11 @@ func (c *certificateAuthorityRESTClient) RestoreCertificateAuthority(ctx context } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:restore", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2458,6 +2503,11 @@ func (c *certificateAuthorityRESTClient) ScheduleDeleteCertificateAuthority(ctx } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:scheduleDelete", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2523,6 +2573,7 @@ func (c *certificateAuthorityRESTClient) UpdateCertificateAuthority(ctx context. baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetCertificateAuthority().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetRequestId() != "" { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -2593,6 +2644,11 @@ func (c *certificateAuthorityRESTClient) GetCertificateRevocationList(ctx contex } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2660,6 +2716,7 @@ func (c *certificateAuthorityRESTClient) ListCertificateRevocationLists(ctx cont baseUrl.Path += fmt.Sprintf("/v1beta1/%v/certificateRevocationLists", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -2747,6 +2804,7 @@ func (c *certificateAuthorityRESTClient) UpdateCertificateRevocationList(ctx con baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetCertificateRevocationList().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetRequestId() != "" { params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } @@ -2817,6 +2875,11 @@ func (c *certificateAuthorityRESTClient) GetReusableConfig(ctx context.Context, } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2884,6 +2947,7 @@ func (c *certificateAuthorityRESTClient) ListReusableConfigs(ctx context.Context baseUrl.Path += fmt.Sprintf("/v1beta1/%v/reusableConfigs", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } diff --git a/security/privateca/apiv1beta1/privatecapb/resources.pb.go b/security/privateca/apiv1beta1/privatecapb/resources.pb.go index 7ce597be2b09..8ce379b3aa43 100644 --- a/security/privateca/apiv1beta1/privatecapb/resources.pb.go +++ b/security/privateca/apiv1beta1/privatecapb/resources.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/security/privateca/v1beta1/resources.proto package privatecapb @@ -724,8 +724,7 @@ type CertificateRevocationList struct { // Output only. The resource path for this [CertificateRevocationList][google.cloud.security.privateca.v1beta1.CertificateRevocationList] in // the format // `projects/*/locations/*/certificateAuthorities/*/ - // - // certificateRevocationLists/*`. + // certificateRevocationLists/*`. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Output only. The CRL sequence number that appears in pem_crl. SequenceNumber int64 `protobuf:"varint,2,opt,name=sequence_number,json=sequenceNumber,proto3" json:"sequence_number,omitempty"` @@ -853,7 +852,6 @@ type Certificate struct { // The config used to create a signed X.509 certificate. // // Types that are assignable to CertificateConfig: - // // *Certificate_PemCsr // *Certificate_Config CertificateConfig isCertificate_CertificateConfig `protobuf_oneof:"certificate_config"` @@ -1215,7 +1213,6 @@ type ReusableConfigWrapper struct { // Reusable or inline config values. // // Types that are assignable to ConfigValues: - // // *ReusableConfigWrapper_ReusableConfig // *ReusableConfigWrapper_ReusableConfigValues ConfigValues isReusableConfigWrapper_ConfigValues `protobuf_oneof:"config_values"` @@ -1301,7 +1298,6 @@ type SubordinateConfig struct { unknownFields protoimpl.UnknownFields // Types that are assignable to SubordinateConfig: - // // *SubordinateConfig_CertificateAuthority // *SubordinateConfig_PemIssuerChain SubordinateConfig isSubordinateConfig_SubordinateConfig `protobuf_oneof:"subordinate_config"` @@ -2087,7 +2083,6 @@ type CertificateAuthority_CertificateAuthorityPolicy struct { // certificates. // // Types that are assignable to ConfigPolicy: - // // *CertificateAuthority_CertificateAuthorityPolicy_AllowedConfigList_ // *CertificateAuthority_CertificateAuthorityPolicy_OverwriteConfigValues ConfigPolicy isCertificateAuthority_CertificateAuthorityPolicy_ConfigPolicy `protobuf_oneof:"config_policy"` @@ -2295,7 +2290,6 @@ type CertificateAuthority_KeyVersionSpec struct { unknownFields protoimpl.UnknownFields // Types that are assignable to KeyVersion: - // // *CertificateAuthority_KeyVersionSpec_CloudKmsKeyVersion // *CertificateAuthority_KeyVersionSpec_Algorithm KeyVersion isCertificateAuthority_KeyVersionSpec_KeyVersion `protobuf_oneof:"KeyVersion"` diff --git a/security/privateca/apiv1beta1/privatecapb/service.pb.go b/security/privateca/apiv1beta1/privatecapb/service.pb.go index 6b0f77eecef7..390a5ccafdd2 100644 --- a/security/privateca/apiv1beta1/privatecapb/service.pb.go +++ b/security/privateca/apiv1beta1/privatecapb/service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/security/privateca/v1beta1/service.proto package privatecapb diff --git a/security/publicca/apiv1beta1/public_certificate_authority_client.go b/security/publicca/apiv1beta1/public_certificate_authority_client.go index ab28b74ee457..7d9954435a4d 100644 --- a/security/publicca/apiv1beta1/public_certificate_authority_client.go +++ b/security/publicca/apiv1beta1/public_certificate_authority_client.go @@ -329,6 +329,11 @@ func (c *publicCertificateAuthorityRESTClient) CreateExternalAccountKey(ctx cont } baseUrl.Path += fmt.Sprintf("/v1beta1/%v/externalAccountKeys", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) diff --git a/security/publicca/apiv1beta1/publiccapb/resources.pb.go b/security/publicca/apiv1beta1/publiccapb/resources.pb.go index 1410eec19b51..2515d395c6e5 100644 --- a/security/publicca/apiv1beta1/publiccapb/resources.pb.go +++ b/security/publicca/apiv1beta1/publiccapb/resources.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/security/publicca/v1beta1/resources.proto package publiccapb diff --git a/security/publicca/apiv1beta1/publiccapb/service.pb.go b/security/publicca/apiv1beta1/publiccapb/service.pb.go index 5e73765586e7..1c98d7e2c11b 100644 --- a/security/publicca/apiv1beta1/publiccapb/service.pb.go +++ b/security/publicca/apiv1beta1/publiccapb/service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/security/publicca/v1beta1/service.proto package publiccapb diff --git a/securitycenter/apiv1/doc.go b/securitycenter/apiv1/doc.go index c5df6f7d2282..ac9520ba1d79 100644 --- a/securitycenter/apiv1/doc.go +++ b/securitycenter/apiv1/doc.go @@ -86,6 +86,8 @@ package securitycenter // import "cloud.google.com/go/securitycenter/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -174,3 +176,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/securitycenter/apiv1/gapic_metadata.json b/securitycenter/apiv1/gapic_metadata.json index ec9fd5d4ccbc..9cd55256928e 100644 --- a/securitycenter/apiv1/gapic_metadata.json +++ b/securitycenter/apiv1/gapic_metadata.json @@ -211,6 +211,211 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "BulkMuteFindings": { + "methods": [ + "BulkMuteFindings" + ] + }, + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "CreateBigQueryExport": { + "methods": [ + "CreateBigQueryExport" + ] + }, + "CreateFinding": { + "methods": [ + "CreateFinding" + ] + }, + "CreateMuteConfig": { + "methods": [ + "CreateMuteConfig" + ] + }, + "CreateNotificationConfig": { + "methods": [ + "CreateNotificationConfig" + ] + }, + "CreateSource": { + "methods": [ + "CreateSource" + ] + }, + "DeleteBigQueryExport": { + "methods": [ + "DeleteBigQueryExport" + ] + }, + "DeleteMuteConfig": { + "methods": [ + "DeleteMuteConfig" + ] + }, + "DeleteNotificationConfig": { + "methods": [ + "DeleteNotificationConfig" + ] + }, + "DeleteOperation": { + "methods": [ + "DeleteOperation" + ] + }, + "GetBigQueryExport": { + "methods": [ + "GetBigQueryExport" + ] + }, + "GetIamPolicy": { + "methods": [ + "GetIamPolicy" + ] + }, + "GetMuteConfig": { + "methods": [ + "GetMuteConfig" + ] + }, + "GetNotificationConfig": { + "methods": [ + "GetNotificationConfig" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "GetOrganizationSettings": { + "methods": [ + "GetOrganizationSettings" + ] + }, + "GetSource": { + "methods": [ + "GetSource" + ] + }, + "GroupAssets": { + "methods": [ + "GroupAssets" + ] + }, + "GroupFindings": { + "methods": [ + "GroupFindings" + ] + }, + "ListAssets": { + "methods": [ + "ListAssets" + ] + }, + "ListBigQueryExports": { + "methods": [ + "ListBigQueryExports" + ] + }, + "ListFindings": { + "methods": [ + "ListFindings" + ] + }, + "ListMuteConfigs": { + "methods": [ + "ListMuteConfigs" + ] + }, + "ListNotificationConfigs": { + "methods": [ + "ListNotificationConfigs" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "ListSources": { + "methods": [ + "ListSources" + ] + }, + "RunAssetDiscovery": { + "methods": [ + "RunAssetDiscovery" + ] + }, + "SetFindingState": { + "methods": [ + "SetFindingState" + ] + }, + "SetIamPolicy": { + "methods": [ + "SetIamPolicy" + ] + }, + "SetMute": { + "methods": [ + "SetMute" + ] + }, + "TestIamPermissions": { + "methods": [ + "TestIamPermissions" + ] + }, + "UpdateBigQueryExport": { + "methods": [ + "UpdateBigQueryExport" + ] + }, + "UpdateExternalSystem": { + "methods": [ + "UpdateExternalSystem" + ] + }, + "UpdateFinding": { + "methods": [ + "UpdateFinding" + ] + }, + "UpdateMuteConfig": { + "methods": [ + "UpdateMuteConfig" + ] + }, + "UpdateNotificationConfig": { + "methods": [ + "UpdateNotificationConfig" + ] + }, + "UpdateOrganizationSettings": { + "methods": [ + "UpdateOrganizationSettings" + ] + }, + "UpdateSecurityMarks": { + "methods": [ + "UpdateSecurityMarks" + ] + }, + "UpdateSource": { + "methods": [ + "UpdateSource" + ] + } + } } } } diff --git a/securitycenter/apiv1/security_center_client.go b/securitycenter/apiv1/security_center_client.go index fac7e43c46f7..d5f706f0528e 100644 --- a/securitycenter/apiv1/security_center_client.go +++ b/securitycenter/apiv1/security_center_client.go @@ -17,9 +17,12 @@ package securitycenter import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,15 +30,18 @@ import ( lroauto "cloud.google.com/go/longrunning/autogen" securitycenterpb "cloud.google.com/go/securitycenter/apiv1/securitycenterpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" iampb "google.golang.org/genproto/googleapis/iam/v1" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" emptypb "google.golang.org/protobuf/types/known/emptypb" ) @@ -264,6 +270,161 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + BulkMuteFindings: []gax.CallOption{}, + CreateSource: []gax.CallOption{}, + CreateFinding: []gax.CallOption{}, + CreateMuteConfig: []gax.CallOption{}, + CreateNotificationConfig: []gax.CallOption{}, + DeleteMuteConfig: []gax.CallOption{}, + DeleteNotificationConfig: []gax.CallOption{}, + GetBigQueryExport: []gax.CallOption{}, + GetIamPolicy: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + GetMuteConfig: []gax.CallOption{}, + GetNotificationConfig: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + GetOrganizationSettings: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + GetSource: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + GroupAssets: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + GroupFindings: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + ListAssets: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + ListFindings: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + ListMuteConfigs: []gax.CallOption{}, + ListNotificationConfigs: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + ListSources: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + RunAssetDiscovery: []gax.CallOption{}, + SetFindingState: []gax.CallOption{}, + SetMute: []gax.CallOption{}, + SetIamPolicy: []gax.CallOption{}, + TestIamPermissions: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + UpdateExternalSystem: []gax.CallOption{}, + UpdateFinding: []gax.CallOption{}, + UpdateMuteConfig: []gax.CallOption{}, + UpdateNotificationConfig: []gax.CallOption{}, + UpdateOrganizationSettings: []gax.CallOption{}, + UpdateSource: []gax.CallOption{}, + UpdateSecurityMarks: []gax.CallOption{}, + CreateBigQueryExport: []gax.CallOption{}, + DeleteBigQueryExport: []gax.CallOption{}, + UpdateBigQueryExport: []gax.CallOption{}, + ListBigQueryExports: []gax.CallOption{}, + CancelOperation: []gax.CallOption{}, + DeleteOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalClient is an interface that defines the methods available from Security Command Center API. type internalClient interface { Close() error @@ -397,7 +558,7 @@ func (c *Client) DeleteNotificationConfig(ctx context.Context, req *securitycent return c.internalClient.DeleteNotificationConfig(ctx, req, opts...) } -// GetBigQueryExport gets a big query export. +// GetBigQueryExport gets a BigQuery export. func (c *Client) GetBigQueryExport(ctx context.Context, req *securitycenterpb.GetBigQueryExportRequest, opts ...gax.CallOption) (*securitycenterpb.BigQueryExport, error) { return c.internalClient.GetBigQueryExport(ctx, req, opts...) } @@ -545,12 +706,12 @@ func (c *Client) UpdateSecurityMarks(ctx context.Context, req *securitycenterpb. return c.internalClient.UpdateSecurityMarks(ctx, req, opts...) } -// CreateBigQueryExport creates a big query export. +// CreateBigQueryExport creates a BigQuery export. func (c *Client) CreateBigQueryExport(ctx context.Context, req *securitycenterpb.CreateBigQueryExportRequest, opts ...gax.CallOption) (*securitycenterpb.BigQueryExport, error) { return c.internalClient.CreateBigQueryExport(ctx, req, opts...) } -// DeleteBigQueryExport deletes an existing big query export. +// DeleteBigQueryExport deletes an existing BigQuery export. func (c *Client) DeleteBigQueryExport(ctx context.Context, req *securitycenterpb.DeleteBigQueryExportRequest, opts ...gax.CallOption) error { return c.internalClient.DeleteBigQueryExport(ctx, req, opts...) } @@ -689,6 +850,89 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new security center rest client. +// +// V1 APIs for Security Center service. +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://securitycenter.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://securitycenter.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://securitycenter.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) BulkMuteFindings(ctx context.Context, req *securitycenterpb.BulkMuteFindingsRequest, opts ...gax.CallOption) (*BulkMuteFindingsOperation, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1690,79 +1934,2882 @@ func (c *gRPCClient) ListOperations(ctx context.Context, req *longrunningpb.List return it } -// BulkMuteFindingsOperation manages a long-running operation from BulkMuteFindings. -type BulkMuteFindingsOperation struct { - lro *longrunning.Operation -} - -// BulkMuteFindingsOperation returns a new BulkMuteFindingsOperation from a given name. -// The name must be that of a previously created BulkMuteFindingsOperation, possibly from a different process. -func (c *gRPCClient) BulkMuteFindingsOperation(name string) *BulkMuteFindingsOperation { - return &BulkMuteFindingsOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), +// BulkMuteFindings kicks off an LRO to bulk mute findings for a parent based on a filter. The +// parent can be either an organization, folder or project. The findings +// matched by the filter will be muted after the LRO is done. +func (c *restClient) BulkMuteFindings(ctx context.Context, req *securitycenterpb.BulkMuteFindingsRequest, opts ...gax.CallOption) (*BulkMuteFindingsOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err } -} -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *BulkMuteFindingsOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*securitycenterpb.BulkMuteFindingsResponse, error) { - var resp securitycenterpb.BulkMuteFindingsResponse - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - return &resp, nil + baseUrl.Path += fmt.Sprintf("/v1/%v/findings:bulkMute", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &BulkMuteFindingsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil } -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *BulkMuteFindingsOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*securitycenterpb.BulkMuteFindingsResponse, error) { - var resp securitycenterpb.BulkMuteFindingsResponse - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { +// CreateSource creates a source. +func (c *restClient) CreateSource(ctx context.Context, req *securitycenterpb.CreateSourceRequest, opts ...gax.CallOption) (*securitycenterpb.Source, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetSource() + jsonReq, err := m.Marshal(body) + if err != nil { return nil, err } - if !op.Done() { - return nil, nil - } - return &resp, nil -} -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *BulkMuteFindingsOperation) Metadata() (*emptypb.Empty, error) { - var meta emptypb.Empty - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - return &meta, nil -} + baseUrl.Path += fmt.Sprintf("/v1/%v/sources", req.GetParent()) -// Done reports whether the long-running operation has completed. -func (op *BulkMuteFindingsOperation) Done() bool { - return op.lro.Done() -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") -// 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 *BulkMuteFindingsOperation) Name() string { - return op.lro.Name() -} + baseUrl.RawQuery = params.Encode() -// RunAssetDiscoveryOperation manages a long-running operation from RunAssetDiscovery. -type RunAssetDiscoveryOperation struct { - lro *longrunning.Operation -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateSource[0:len((*c.CallOptions).CreateSource):len((*c.CallOptions).CreateSource)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &securitycenterpb.Source{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateFinding creates a finding. The corresponding source must exist for finding creation +// to succeed. +func (c *restClient) CreateFinding(ctx context.Context, req *securitycenterpb.CreateFindingRequest, opts ...gax.CallOption) (*securitycenterpb.Finding, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetFinding() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/findings", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("findingId", fmt.Sprintf("%v", req.GetFindingId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateFinding[0:len((*c.CallOptions).CreateFinding):len((*c.CallOptions).CreateFinding)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &securitycenterpb.Finding{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateMuteConfig creates a mute config. +func (c *restClient) CreateMuteConfig(ctx context.Context, req *securitycenterpb.CreateMuteConfigRequest, opts ...gax.CallOption) (*securitycenterpb.MuteConfig, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetMuteConfig() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/muteConfigs", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("muteConfigId", fmt.Sprintf("%v", req.GetMuteConfigId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateMuteConfig[0:len((*c.CallOptions).CreateMuteConfig):len((*c.CallOptions).CreateMuteConfig)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &securitycenterpb.MuteConfig{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateNotificationConfig creates a notification config. +func (c *restClient) CreateNotificationConfig(ctx context.Context, req *securitycenterpb.CreateNotificationConfigRequest, opts ...gax.CallOption) (*securitycenterpb.NotificationConfig, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetNotificationConfig() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/notificationConfigs", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("configId", fmt.Sprintf("%v", req.GetConfigId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateNotificationConfig[0:len((*c.CallOptions).CreateNotificationConfig):len((*c.CallOptions).CreateNotificationConfig)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &securitycenterpb.NotificationConfig{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteMuteConfig deletes an existing mute config. +func (c *restClient) DeleteMuteConfig(ctx context.Context, req *securitycenterpb.DeleteMuteConfigRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// DeleteNotificationConfig deletes a notification config. +func (c *restClient) DeleteNotificationConfig(ctx context.Context, req *securitycenterpb.DeleteNotificationConfigRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetBigQueryExport gets a BigQuery export. +func (c *restClient) GetBigQueryExport(ctx context.Context, req *securitycenterpb.GetBigQueryExportRequest, opts ...gax.CallOption) (*securitycenterpb.BigQueryExport, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetBigQueryExport[0:len((*c.CallOptions).GetBigQueryExport):len((*c.CallOptions).GetBigQueryExport)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &securitycenterpb.BigQueryExport{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetIamPolicy gets the access control policy on the specified Source. +func (c *restClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:getIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetMuteConfig gets a mute config. +func (c *restClient) GetMuteConfig(ctx context.Context, req *securitycenterpb.GetMuteConfigRequest, opts ...gax.CallOption) (*securitycenterpb.MuteConfig, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetMuteConfig[0:len((*c.CallOptions).GetMuteConfig):len((*c.CallOptions).GetMuteConfig)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &securitycenterpb.MuteConfig{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetNotificationConfig gets a notification config. +func (c *restClient) GetNotificationConfig(ctx context.Context, req *securitycenterpb.GetNotificationConfigRequest, opts ...gax.CallOption) (*securitycenterpb.NotificationConfig, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetNotificationConfig[0:len((*c.CallOptions).GetNotificationConfig):len((*c.CallOptions).GetNotificationConfig)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &securitycenterpb.NotificationConfig{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetOrganizationSettings gets the settings for an organization. +func (c *restClient) GetOrganizationSettings(ctx context.Context, req *securitycenterpb.GetOrganizationSettingsRequest, opts ...gax.CallOption) (*securitycenterpb.OrganizationSettings, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOrganizationSettings[0:len((*c.CallOptions).GetOrganizationSettings):len((*c.CallOptions).GetOrganizationSettings)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &securitycenterpb.OrganizationSettings{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetSource gets a source. +func (c *restClient) GetSource(ctx context.Context, req *securitycenterpb.GetSourceRequest, opts ...gax.CallOption) (*securitycenterpb.Source, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetSource[0:len((*c.CallOptions).GetSource):len((*c.CallOptions).GetSource)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &securitycenterpb.Source{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GroupAssets filters an organization’s assets and groups them by their specified +// properties. +func (c *restClient) GroupAssets(ctx context.Context, req *securitycenterpb.GroupAssetsRequest, opts ...gax.CallOption) *GroupResultIterator { + it := &GroupResultIterator{} + req = proto.Clone(req).(*securitycenterpb.GroupAssetsRequest) + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*securitycenterpb.GroupResult, string, error) { + resp := &securitycenterpb.GroupAssetsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, "", err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/assets:group", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetGroupByResults(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GroupFindings filters an organization or source’s findings and groups them by their +// specified properties. +// +// To group across all sources provide a - as the source id. +// Example: /v1/organizations/{organization_id}/sources/-/findings, +// /v1/folders/{folder_id}/sources/-/findings, +// /v1/projects/{project_id}/sources/-/findings +func (c *restClient) GroupFindings(ctx context.Context, req *securitycenterpb.GroupFindingsRequest, opts ...gax.CallOption) *GroupResultIterator { + it := &GroupResultIterator{} + req = proto.Clone(req).(*securitycenterpb.GroupFindingsRequest) + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*securitycenterpb.GroupResult, string, error) { + resp := &securitycenterpb.GroupFindingsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, "", err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/findings:group", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetGroupByResults(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// ListAssets lists an organization’s assets. +func (c *restClient) ListAssets(ctx context.Context, req *securitycenterpb.ListAssetsRequest, opts ...gax.CallOption) *ListAssetsResponse_ListAssetsResultIterator { + it := &ListAssetsResponse_ListAssetsResultIterator{} + req = proto.Clone(req).(*securitycenterpb.ListAssetsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*securitycenterpb.ListAssetsResponse_ListAssetsResult, string, error) { + resp := &securitycenterpb.ListAssetsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/assets", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetCompareDuration() != nil { + compareDuration, err := protojson.Marshal(req.GetCompareDuration()) + if err != nil { + return nil, "", err + } + params.Add("compareDuration", string(compareDuration)) + } + if req.GetFieldMask() != nil { + fieldMask, err := protojson.Marshal(req.GetFieldMask()) + if err != nil { + return nil, "", err + } + params.Add("fieldMask", string(fieldMask)) + } + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + if req.GetReadTime() != nil { + readTime, err := protojson.Marshal(req.GetReadTime()) + if err != nil { + return nil, "", err + } + params.Add("readTime", string(readTime)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetListAssetsResults(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// ListFindings lists an organization or source’s findings. +// +// To list across all sources provide a - as the source id. +// Example: /v1/organizations/{organization_id}/sources/-/findings +func (c *restClient) ListFindings(ctx context.Context, req *securitycenterpb.ListFindingsRequest, opts ...gax.CallOption) *ListFindingsResponse_ListFindingsResultIterator { + it := &ListFindingsResponse_ListFindingsResultIterator{} + req = proto.Clone(req).(*securitycenterpb.ListFindingsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*securitycenterpb.ListFindingsResponse_ListFindingsResult, string, error) { + resp := &securitycenterpb.ListFindingsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/findings", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetCompareDuration() != nil { + compareDuration, err := protojson.Marshal(req.GetCompareDuration()) + if err != nil { + return nil, "", err + } + params.Add("compareDuration", string(compareDuration)) + } + if req.GetFieldMask() != nil { + fieldMask, err := protojson.Marshal(req.GetFieldMask()) + if err != nil { + return nil, "", err + } + params.Add("fieldMask", string(fieldMask)) + } + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + if req.GetReadTime() != nil { + readTime, err := protojson.Marshal(req.GetReadTime()) + if err != nil { + return nil, "", err + } + params.Add("readTime", string(readTime)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetListFindingsResults(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// ListMuteConfigs lists mute configs. +func (c *restClient) ListMuteConfigs(ctx context.Context, req *securitycenterpb.ListMuteConfigsRequest, opts ...gax.CallOption) *MuteConfigIterator { + it := &MuteConfigIterator{} + req = proto.Clone(req).(*securitycenterpb.ListMuteConfigsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*securitycenterpb.MuteConfig, string, error) { + resp := &securitycenterpb.ListMuteConfigsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/muteConfigs", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetMuteConfigs(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// ListNotificationConfigs lists notification configs. +func (c *restClient) ListNotificationConfigs(ctx context.Context, req *securitycenterpb.ListNotificationConfigsRequest, opts ...gax.CallOption) *NotificationConfigIterator { + it := &NotificationConfigIterator{} + req = proto.Clone(req).(*securitycenterpb.ListNotificationConfigsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*securitycenterpb.NotificationConfig, string, error) { + resp := &securitycenterpb.ListNotificationConfigsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/notificationConfigs", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetNotificationConfigs(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// ListSources lists all sources belonging to an organization. +func (c *restClient) ListSources(ctx context.Context, req *securitycenterpb.ListSourcesRequest, opts ...gax.CallOption) *SourceIterator { + it := &SourceIterator{} + req = proto.Clone(req).(*securitycenterpb.ListSourcesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*securitycenterpb.Source, string, error) { + resp := &securitycenterpb.ListSourcesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/sources", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetSources(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// RunAssetDiscovery runs asset discovery. The discovery is tracked with a long-running +// operation. +// +// This API can only be called with limited frequency for an organization. If +// it is called too frequently the caller will receive a TOO_MANY_REQUESTS +// error. +func (c *restClient) RunAssetDiscovery(ctx context.Context, req *securitycenterpb.RunAssetDiscoveryRequest, opts ...gax.CallOption) (*RunAssetDiscoveryOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/assets:runDiscovery", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &RunAssetDiscoveryOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// SetFindingState updates the state of a finding. +func (c *restClient) SetFindingState(ctx context.Context, req *securitycenterpb.SetFindingStateRequest, opts ...gax.CallOption) (*securitycenterpb.Finding, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:setState", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetFindingState[0:len((*c.CallOptions).SetFindingState):len((*c.CallOptions).SetFindingState)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &securitycenterpb.Finding{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SetMute updates the mute state of a finding. +func (c *restClient) SetMute(ctx context.Context, req *securitycenterpb.SetMuteRequest, opts ...gax.CallOption) (*securitycenterpb.Finding, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:setMute", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetMute[0:len((*c.CallOptions).SetMute):len((*c.CallOptions).SetMute)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &securitycenterpb.Finding{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SetIamPolicy sets the access control policy on the specified Source. +func (c *restClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:setIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// TestIamPermissions returns the permissions that a caller has on the specified source. +func (c *restClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:testIamPermissions", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.TestIamPermissionsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateExternalSystem updates external system. This is for a given finding. +func (c *restClient) UpdateExternalSystem(ctx context.Context, req *securitycenterpb.UpdateExternalSystemRequest, opts ...gax.CallOption) (*securitycenterpb.ExternalSystem, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetExternalSystem() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetExternalSystem().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "external_system.name", url.QueryEscape(req.GetExternalSystem().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateExternalSystem[0:len((*c.CallOptions).UpdateExternalSystem):len((*c.CallOptions).UpdateExternalSystem)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &securitycenterpb.ExternalSystem{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateFinding creates or updates a finding. The corresponding source must exist for a +// finding creation to succeed. +func (c *restClient) UpdateFinding(ctx context.Context, req *securitycenterpb.UpdateFindingRequest, opts ...gax.CallOption) (*securitycenterpb.Finding, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetFinding() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetFinding().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "finding.name", url.QueryEscape(req.GetFinding().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateFinding[0:len((*c.CallOptions).UpdateFinding):len((*c.CallOptions).UpdateFinding)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &securitycenterpb.Finding{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateMuteConfig updates a mute config. +func (c *restClient) UpdateMuteConfig(ctx context.Context, req *securitycenterpb.UpdateMuteConfigRequest, opts ...gax.CallOption) (*securitycenterpb.MuteConfig, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetMuteConfig() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetMuteConfig().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "mute_config.name", url.QueryEscape(req.GetMuteConfig().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateMuteConfig[0:len((*c.CallOptions).UpdateMuteConfig):len((*c.CallOptions).UpdateMuteConfig)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &securitycenterpb.MuteConfig{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateNotificationConfig updates a notification config. The following update +// fields are allowed: description, pubsub_topic, streaming_config.filter +func (c *restClient) UpdateNotificationConfig(ctx context.Context, req *securitycenterpb.UpdateNotificationConfigRequest, opts ...gax.CallOption) (*securitycenterpb.NotificationConfig, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetNotificationConfig() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetNotificationConfig().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "notification_config.name", url.QueryEscape(req.GetNotificationConfig().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateNotificationConfig[0:len((*c.CallOptions).UpdateNotificationConfig):len((*c.CallOptions).UpdateNotificationConfig)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &securitycenterpb.NotificationConfig{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateOrganizationSettings updates an organization’s settings. +func (c *restClient) UpdateOrganizationSettings(ctx context.Context, req *securitycenterpb.UpdateOrganizationSettingsRequest, opts ...gax.CallOption) (*securitycenterpb.OrganizationSettings, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetOrganizationSettings() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetOrganizationSettings().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "organization_settings.name", url.QueryEscape(req.GetOrganizationSettings().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateOrganizationSettings[0:len((*c.CallOptions).UpdateOrganizationSettings):len((*c.CallOptions).UpdateOrganizationSettings)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &securitycenterpb.OrganizationSettings{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateSource updates a source. +func (c *restClient) UpdateSource(ctx context.Context, req *securitycenterpb.UpdateSourceRequest, opts ...gax.CallOption) (*securitycenterpb.Source, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetSource() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetSource().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "source.name", url.QueryEscape(req.GetSource().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateSource[0:len((*c.CallOptions).UpdateSource):len((*c.CallOptions).UpdateSource)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &securitycenterpb.Source{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateSecurityMarks updates security marks. +func (c *restClient) UpdateSecurityMarks(ctx context.Context, req *securitycenterpb.UpdateSecurityMarksRequest, opts ...gax.CallOption) (*securitycenterpb.SecurityMarks, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetSecurityMarks() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetSecurityMarks().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetStartTime() != nil { + startTime, err := protojson.Marshal(req.GetStartTime()) + if err != nil { + return nil, err + } + params.Add("startTime", string(startTime)) + } + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "security_marks.name", url.QueryEscape(req.GetSecurityMarks().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateSecurityMarks[0:len((*c.CallOptions).UpdateSecurityMarks):len((*c.CallOptions).UpdateSecurityMarks)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &securitycenterpb.SecurityMarks{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateBigQueryExport creates a BigQuery export. +func (c *restClient) CreateBigQueryExport(ctx context.Context, req *securitycenterpb.CreateBigQueryExportRequest, opts ...gax.CallOption) (*securitycenterpb.BigQueryExport, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetBigQueryExport() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/bigQueryExports", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("bigQueryExportId", fmt.Sprintf("%v", req.GetBigQueryExportId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateBigQueryExport[0:len((*c.CallOptions).CreateBigQueryExport):len((*c.CallOptions).CreateBigQueryExport)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &securitycenterpb.BigQueryExport{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteBigQueryExport deletes an existing BigQuery export. +func (c *restClient) DeleteBigQueryExport(ctx context.Context, req *securitycenterpb.DeleteBigQueryExportRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// UpdateBigQueryExport updates a BigQuery export. +func (c *restClient) UpdateBigQueryExport(ctx context.Context, req *securitycenterpb.UpdateBigQueryExportRequest, opts ...gax.CallOption) (*securitycenterpb.BigQueryExport, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetBigQueryExport() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetBigQueryExport().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "big_query_export.name", url.QueryEscape(req.GetBigQueryExport().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateBigQueryExport[0:len((*c.CallOptions).UpdateBigQueryExport):len((*c.CallOptions).UpdateBigQueryExport)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &securitycenterpb.BigQueryExport{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListBigQueryExports lists BigQuery exports. Note that when requesting BigQuery exports at a +// given level all exports under that level are also returned e.g. if +// requesting BigQuery exports under a folder, then all BigQuery exports +// immediately under the folder plus the ones created under the projects +// within the folder are returned. +func (c *restClient) ListBigQueryExports(ctx context.Context, req *securitycenterpb.ListBigQueryExportsRequest, opts ...gax.CallOption) *BigQueryExportIterator { + it := &BigQueryExportIterator{} + req = proto.Clone(req).(*securitycenterpb.ListBigQueryExportsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*securitycenterpb.BigQueryExport, string, error) { + resp := &securitycenterpb.ListBigQueryExportsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/bigQueryExports", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetBigQueryExports(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *restClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// DeleteOperation is a utility method from google.longrunning.Operations. +func (c *restClient) DeleteOperation(ctx context.Context, req *longrunningpb.DeleteOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *restClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *restClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// BulkMuteFindingsOperation manages a long-running operation from BulkMuteFindings. +type BulkMuteFindingsOperation struct { + lro *longrunning.Operation + pollPath string +} + +// BulkMuteFindingsOperation returns a new BulkMuteFindingsOperation from a given name. +// The name must be that of a previously created BulkMuteFindingsOperation, possibly from a different process. +func (c *gRPCClient) BulkMuteFindingsOperation(name string) *BulkMuteFindingsOperation { + return &BulkMuteFindingsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// BulkMuteFindingsOperation returns a new BulkMuteFindingsOperation from a given name. +// The name must be that of a previously created BulkMuteFindingsOperation, possibly from a different process. +func (c *restClient) BulkMuteFindingsOperation(name string) *BulkMuteFindingsOperation { + override := fmt.Sprintf("/v1/%s", name) + return &BulkMuteFindingsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *BulkMuteFindingsOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*securitycenterpb.BulkMuteFindingsResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp securitycenterpb.BulkMuteFindingsResponse + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *BulkMuteFindingsOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*securitycenterpb.BulkMuteFindingsResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp securitycenterpb.BulkMuteFindingsResponse + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *BulkMuteFindingsOperation) Metadata() (*emptypb.Empty, error) { + var meta emptypb.Empty + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *BulkMuteFindingsOperation) Done() bool { + return op.lro.Done() +} + +// 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 *BulkMuteFindingsOperation) Name() string { + return op.lro.Name() +} + +// RunAssetDiscoveryOperation manages a long-running operation from RunAssetDiscovery. +type RunAssetDiscoveryOperation struct { + lro *longrunning.Operation + pollPath string +} // RunAssetDiscoveryOperation returns a new RunAssetDiscoveryOperation from a given name. // The name must be that of a previously created RunAssetDiscoveryOperation, possibly from a different process. @@ -1772,10 +4819,21 @@ func (c *gRPCClient) RunAssetDiscoveryOperation(name string) *RunAssetDiscoveryO } } +// RunAssetDiscoveryOperation returns a new RunAssetDiscoveryOperation from a given name. +// The name must be that of a previously created RunAssetDiscoveryOperation, possibly from a different process. +func (c *restClient) RunAssetDiscoveryOperation(name string) *RunAssetDiscoveryOperation { + override := fmt.Sprintf("/v1/%s", name) + return &RunAssetDiscoveryOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *RunAssetDiscoveryOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*securitycenterpb.RunAssetDiscoveryResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp securitycenterpb.RunAssetDiscoveryResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1793,6 +4851,7 @@ func (op *RunAssetDiscoveryOperation) Wait(ctx context.Context, opts ...gax.Call // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *RunAssetDiscoveryOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*securitycenterpb.RunAssetDiscoveryResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp securitycenterpb.RunAssetDiscoveryResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/securitycenter/apiv1/security_center_client_example_test.go b/securitycenter/apiv1/security_center_client_example_test.go index 78d174cb3bb6..e7bfd0865512 100644 --- a/securitycenter/apiv1/security_center_client_example_test.go +++ b/securitycenter/apiv1/security_center_client_example_test.go @@ -43,6 +43,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := securitycenter.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_BulkMuteFindings() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/securitycenter/apiv1/securitycenterpb/access.pb.go b/securitycenter/apiv1/securitycenterpb/access.pb.go index dbfa487e5d20..c5cb447c0dfa 100644 --- a/securitycenter/apiv1/securitycenterpb/access.pb.go +++ b/securitycenter/apiv1/securitycenterpb/access.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/securitycenter/v1/access.proto package securitycenterpb @@ -75,6 +75,7 @@ type Access struct { // This is a scheme-less URI full resource name. For example: // // "//iam.googleapis.com/projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}/keys/{key}" + // ServiceAccountKeyName string `protobuf:"bytes,8,opt,name=service_account_key_name,json=serviceAccountKeyName,proto3" json:"service_account_key_name,omitempty"` // Identity delegation history of an authenticated service account that makes // the request. It contains information on the real authorities that try to diff --git a/securitycenter/apiv1/securitycenterpb/asset.pb.go b/securitycenter/apiv1/securitycenterpb/asset.pb.go index a2a9d0348ccc..cc1f90d4cc43 100644 --- a/securitycenter/apiv1/securitycenterpb/asset.pb.go +++ b/securitycenter/apiv1/securitycenterpb/asset.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/securitycenter/v1/asset.proto package securitycenterpb diff --git a/securitycenter/apiv1/securitycenterpb/bigquery_export.pb.go b/securitycenter/apiv1/securitycenterpb/bigquery_export.pb.go index 027ca1fde73d..818b6ad89278 100644 --- a/securitycenter/apiv1/securitycenterpb/bigquery_export.pb.go +++ b/securitycenter/apiv1/securitycenterpb/bigquery_export.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/securitycenter/v1/bigquery_export.proto package securitycenterpb diff --git a/securitycenter/apiv1/securitycenterpb/compliance.pb.go b/securitycenter/apiv1/securitycenterpb/compliance.pb.go index 8c172704e902..473c7a62e060 100644 --- a/securitycenter/apiv1/securitycenterpb/compliance.pb.go +++ b/securitycenter/apiv1/securitycenterpb/compliance.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/securitycenter/v1/compliance.proto package securitycenterpb diff --git a/securitycenter/apiv1/securitycenterpb/connection.pb.go b/securitycenter/apiv1/securitycenterpb/connection.pb.go index 8b362f9b9cf6..af78c8a3cb61 100644 --- a/securitycenter/apiv1/securitycenterpb/connection.pb.go +++ b/securitycenter/apiv1/securitycenterpb/connection.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/securitycenter/v1/connection.proto package securitycenterpb diff --git a/securitycenter/apiv1/securitycenterpb/contact_details.pb.go b/securitycenter/apiv1/securitycenterpb/contact_details.pb.go index d370fb3118f1..1a23de4a4f02 100644 --- a/securitycenter/apiv1/securitycenterpb/contact_details.pb.go +++ b/securitycenter/apiv1/securitycenterpb/contact_details.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/securitycenter/v1/contact_details.proto package securitycenterpb diff --git a/securitycenter/apiv1/securitycenterpb/container.pb.go b/securitycenter/apiv1/securitycenterpb/container.pb.go index 0763534e558f..f48da0ab70ea 100644 --- a/securitycenter/apiv1/securitycenterpb/container.pb.go +++ b/securitycenter/apiv1/securitycenterpb/container.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/securitycenter/v1/container.proto package securitycenterpb diff --git a/securitycenter/apiv1/securitycenterpb/database.pb.go b/securitycenter/apiv1/securitycenterpb/database.pb.go index 104a5b9a47d3..47a1a28608ae 100644 --- a/securitycenter/apiv1/securitycenterpb/database.pb.go +++ b/securitycenter/apiv1/securitycenterpb/database.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/securitycenter/v1/database.proto package securitycenterpb diff --git a/securitycenter/apiv1/securitycenterpb/exfiltration.pb.go b/securitycenter/apiv1/securitycenterpb/exfiltration.pb.go index cba2232a3034..efa070d1c18d 100644 --- a/securitycenter/apiv1/securitycenterpb/exfiltration.pb.go +++ b/securitycenter/apiv1/securitycenterpb/exfiltration.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/securitycenter/v1/exfiltration.proto package securitycenterpb diff --git a/securitycenter/apiv1/securitycenterpb/external_system.pb.go b/securitycenter/apiv1/securitycenterpb/external_system.pb.go index 238b019fb079..3ea0eaee0dcc 100644 --- a/securitycenter/apiv1/securitycenterpb/external_system.pb.go +++ b/securitycenter/apiv1/securitycenterpb/external_system.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/securitycenter/v1/external_system.proto package securitycenterpb @@ -43,13 +43,10 @@ type ExternalSystem struct { sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields - // External System Name e.g. jira, demisto, etc. - // - // e.g.: - // `organizations/1234/sources/5678/findings/123456/externalSystems/jira` - // - // `folders/1234/sources/5678/findings/123456/externalSystems/jira` - // `projects/1234/sources/5678/findings/123456/externalSystems/jira` + // Full resource name of the external system, for example: + // "organizations/1234/sources/5678/findings/123456/externalSystems/jira", + // "folders/1234/sources/5678/findings/123456/externalSystems/jira", + // "projects/1234/sources/5678/findings/123456/externalSystems/jira" Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // References primary/secondary etc assignees in the external system. Assignees []string `protobuf:"bytes,2,rep,name=assignees,proto3" json:"assignees,omitempty"` diff --git a/securitycenter/apiv1/securitycenterpb/file.pb.go b/securitycenter/apiv1/securitycenterpb/file.pb.go index 8a4ff52b571b..7a0edccc119c 100644 --- a/securitycenter/apiv1/securitycenterpb/file.pb.go +++ b/securitycenter/apiv1/securitycenterpb/file.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/securitycenter/v1/file.proto package securitycenterpb diff --git a/securitycenter/apiv1/securitycenterpb/finding.pb.go b/securitycenter/apiv1/securitycenterpb/finding.pb.go index e22ecb79cfc1..e87961934c23 100644 --- a/securitycenter/apiv1/securitycenterpb/finding.pb.go +++ b/securitycenter/apiv1/securitycenterpb/finding.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/securitycenter/v1/finding.proto package securitycenterpb @@ -399,7 +399,7 @@ type Finding struct { // intrusion. // Reference: https://en.wikipedia.org/wiki/Indicator_of_compromise Indicator *Indicator `protobuf:"bytes,18,opt,name=indicator,proto3" json:"indicator,omitempty"` - // Represents vulnerability specific fields like cve, cvss scores etc. + // Represents vulnerability-specific fields like CVE and CVS scores. // CVE stands for Common Vulnerabilities and Exposures // (https://cve.mitre.org/about/) Vulnerability *Vulnerability `protobuf:"bytes,20,opt,name=vulnerability,proto3" json:"vulnerability,omitempty"` @@ -428,18 +428,18 @@ type Finding struct { // contacts that pertain. Please refer to: // https://cloud.google.com/resource-manager/docs/managing-notification-contacts#notification-categories // - // { - // "security": { - // "contacts": [ - // { - // "email": "person1@company.com" - // }, - // { - // "email": "person2@company.com" - // } - // ] - // } - // } + // { + // "security": { + // "contacts": [ + // { + // "email": "person1@company.com" + // }, + // { + // "email": "person2@company.com" + // } + // ] + // } + // } Contacts map[string]*ContactDetails `protobuf:"bytes,33,rep,name=contacts,proto3" json:"contacts,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` // Contains compliance information for security standards associated to the // finding. @@ -464,6 +464,8 @@ type Finding struct { Database *Database `protobuf:"bytes,44,opt,name=database,proto3" json:"database,omitempty"` // File associated with the finding. Files []*File `protobuf:"bytes,46,rep,name=files,proto3" json:"files,omitempty"` + // Kernel Rootkit signature. + KernelRootkit *KernelRootkit `protobuf:"bytes,50,opt,name=kernel_rootkit,json=kernelRootkit,proto3" json:"kernel_rootkit,omitempty"` } func (x *Finding) Reset() { @@ -736,6 +738,13 @@ func (x *Finding) GetFiles() []*File { return nil } +func (x *Finding) GetKernelRootkit() *KernelRootkit { + if x != nil { + return x.KernelRootkit + } + return nil +} + var File_google_cloud_securitycenter_v1_finding_proto protoreflect.FileDescriptor var file_google_cloud_securitycenter_v1_finding_proto_rawDesc = []byte{ @@ -781,235 +790,243 @@ var file_google_cloud_securitycenter_v1_finding_proto_rawDesc = []byte{ 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2f, 0x73, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x63, 0x65, 0x6e, 0x74, 0x65, 0x72, 0x2f, 0x76, 0x31, 0x2f, 0x69, 0x6e, 0x64, 0x69, 0x63, 0x61, 0x74, 0x6f, 0x72, 0x2e, 0x70, - 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x2f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x63, 0x6c, 0x6f, + 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x33, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2f, 0x73, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x63, 0x65, 0x6e, 0x74, 0x65, - 0x72, 0x2f, 0x76, 0x31, 0x2f, 0x6b, 0x75, 0x62, 0x65, 0x72, 0x6e, 0x65, 0x74, 0x65, 0x73, 0x2e, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x31, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x63, 0x6c, - 0x6f, 0x75, 0x64, 0x2f, 0x73, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x63, 0x65, 0x6e, 0x74, - 0x65, 0x72, 0x2f, 0x76, 0x31, 0x2f, 0x6d, 0x69, 0x74, 0x72, 0x65, 0x5f, 0x61, 0x74, 0x74, 0x61, - 0x63, 0x6b, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x2c, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, - 0x2f, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2f, 0x73, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x63, - 0x65, 0x6e, 0x74, 0x65, 0x72, 0x2f, 0x76, 0x31, 0x2f, 0x70, 0x72, 0x6f, 0x63, 0x65, 0x73, 0x73, - 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x33, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x63, - 0x6c, 0x6f, 0x75, 0x64, 0x2f, 0x73, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x63, 0x65, 0x6e, - 0x74, 0x65, 0x72, 0x2f, 0x76, 0x31, 0x2f, 0x73, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x5f, - 0x6d, 0x61, 0x72, 0x6b, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x32, 0x67, 0x6f, 0x6f, + 0x72, 0x2f, 0x76, 0x31, 0x2f, 0x6b, 0x65, 0x72, 0x6e, 0x65, 0x6c, 0x5f, 0x72, 0x6f, 0x6f, 0x74, + 0x6b, 0x69, 0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x2f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, + 0x65, 0x2f, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2f, 0x73, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, + 0x63, 0x65, 0x6e, 0x74, 0x65, 0x72, 0x2f, 0x76, 0x31, 0x2f, 0x6b, 0x75, 0x62, 0x65, 0x72, 0x6e, + 0x65, 0x74, 0x65, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x31, 0x67, 0x6f, 0x6f, 0x67, + 0x6c, 0x65, 0x2f, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2f, 0x73, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, + 0x79, 0x63, 0x65, 0x6e, 0x74, 0x65, 0x72, 0x2f, 0x76, 0x31, 0x2f, 0x6d, 0x69, 0x74, 0x72, 0x65, + 0x5f, 0x61, 0x74, 0x74, 0x61, 0x63, 0x6b, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x2c, 0x67, + 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2f, 0x73, 0x65, 0x63, 0x75, + 0x72, 0x69, 0x74, 0x79, 0x63, 0x65, 0x6e, 0x74, 0x65, 0x72, 0x2f, 0x76, 0x31, 0x2f, 0x70, 0x72, + 0x6f, 0x63, 0x65, 0x73, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x33, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2f, 0x73, 0x65, 0x63, 0x75, 0x72, 0x69, - 0x74, 0x79, 0x63, 0x65, 0x6e, 0x74, 0x65, 0x72, 0x2f, 0x76, 0x31, 0x2f, 0x76, 0x75, 0x6c, 0x6e, - 0x65, 0x72, 0x61, 0x62, 0x69, 0x6c, 0x69, 0x74, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, - 0x1c, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, - 0x2f, 0x73, 0x74, 0x72, 0x75, 0x63, 0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1f, 0x67, - 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x74, - 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x9b, - 0x18, 0x0a, 0x07, 0x46, 0x69, 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, - 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x16, - 0x0a, 0x06, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, - 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x12, 0x23, 0x0a, 0x0d, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, - 0x63, 0x65, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0c, 0x72, - 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x43, 0x0a, 0x05, 0x73, - 0x74, 0x61, 0x74, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x2d, 0x2e, 0x67, 0x6f, 0x6f, - 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x65, 0x63, 0x75, 0x72, 0x69, - 0x74, 0x79, 0x63, 0x65, 0x6e, 0x74, 0x65, 0x72, 0x2e, 0x76, 0x31, 0x2e, 0x46, 0x69, 0x6e, 0x64, - 0x69, 0x6e, 0x67, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x65, 0x52, 0x05, 0x73, 0x74, 0x61, 0x74, 0x65, - 0x12, 0x1a, 0x0a, 0x08, 0x63, 0x61, 0x74, 0x65, 0x67, 0x6f, 0x72, 0x79, 0x18, 0x05, 0x20, 0x01, - 0x28, 0x09, 0x52, 0x08, 0x63, 0x61, 0x74, 0x65, 0x67, 0x6f, 0x72, 0x79, 0x12, 0x21, 0x0a, 0x0c, - 0x65, 0x78, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x5f, 0x75, 0x72, 0x69, 0x18, 0x06, 0x20, 0x01, - 0x28, 0x09, 0x52, 0x0b, 0x65, 0x78, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x55, 0x72, 0x69, 0x12, - 0x6a, 0x0a, 0x11, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x5f, 0x70, 0x72, 0x6f, 0x70, 0x65, 0x72, - 0x74, 0x69, 0x65, 0x73, 0x18, 0x07, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x3d, 0x2e, 0x67, 0x6f, 0x6f, - 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x65, 0x63, 0x75, 0x72, 0x69, - 0x74, 0x79, 0x63, 0x65, 0x6e, 0x74, 0x65, 0x72, 0x2e, 0x76, 0x31, 0x2e, 0x46, 0x69, 0x6e, 0x64, - 0x69, 0x6e, 0x67, 0x2e, 0x53, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x50, 0x72, 0x6f, 0x70, 0x65, 0x72, - 0x74, 0x69, 0x65, 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x10, 0x73, 0x6f, 0x75, 0x72, 0x63, - 0x65, 0x50, 0x72, 0x6f, 0x70, 0x65, 0x72, 0x74, 0x69, 0x65, 0x73, 0x12, 0x59, 0x0a, 0x0e, 0x73, - 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x5f, 0x6d, 0x61, 0x72, 0x6b, 0x73, 0x18, 0x08, 0x20, - 0x01, 0x28, 0x0b, 0x32, 0x2d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, - 0x75, 0x64, 0x2e, 0x73, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x63, 0x65, 0x6e, 0x74, 0x65, - 0x72, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x4d, 0x61, 0x72, - 0x6b, 0x73, 0x42, 0x03, 0xe0, 0x41, 0x03, 0x52, 0x0d, 0x73, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, - 0x79, 0x4d, 0x61, 0x72, 0x6b, 0x73, 0x12, 0x39, 0x0a, 0x0a, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x5f, - 0x74, 0x69, 0x6d, 0x65, 0x18, 0x09, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, - 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, 0x6d, - 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x09, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x54, 0x69, 0x6d, - 0x65, 0x12, 0x3b, 0x0a, 0x0b, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x5f, 0x74, 0x69, 0x6d, 0x65, - 0x18, 0x0a, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, - 0x6d, 0x70, 0x52, 0x0a, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x4c, - 0x0a, 0x08, 0x73, 0x65, 0x76, 0x65, 0x72, 0x69, 0x74, 0x79, 0x18, 0x0c, 0x20, 0x01, 0x28, 0x0e, - 0x32, 0x30, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, - 0x73, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x63, 0x65, 0x6e, 0x74, 0x65, 0x72, 0x2e, 0x76, - 0x31, 0x2e, 0x46, 0x69, 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x2e, 0x53, 0x65, 0x76, 0x65, 0x72, 0x69, - 0x74, 0x79, 0x52, 0x08, 0x73, 0x65, 0x76, 0x65, 0x72, 0x69, 0x74, 0x79, 0x12, 0x25, 0x0a, 0x0e, - 0x63, 0x61, 0x6e, 0x6f, 0x6e, 0x69, 0x63, 0x61, 0x6c, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x0e, - 0x20, 0x01, 0x28, 0x09, 0x52, 0x0d, 0x63, 0x61, 0x6e, 0x6f, 0x6e, 0x69, 0x63, 0x61, 0x6c, 0x4e, - 0x61, 0x6d, 0x65, 0x12, 0x40, 0x0a, 0x04, 0x6d, 0x75, 0x74, 0x65, 0x18, 0x0f, 0x20, 0x01, 0x28, - 0x0e, 0x32, 0x2c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, - 0x2e, 0x73, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x63, 0x65, 0x6e, 0x74, 0x65, 0x72, 0x2e, - 0x76, 0x31, 0x2e, 0x46, 0x69, 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x2e, 0x4d, 0x75, 0x74, 0x65, 0x52, - 0x04, 0x6d, 0x75, 0x74, 0x65, 0x12, 0x59, 0x0a, 0x0d, 0x66, 0x69, 0x6e, 0x64, 0x69, 0x6e, 0x67, - 0x5f, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x18, 0x11, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x34, 0x2e, 0x67, - 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x65, 0x63, 0x75, - 0x72, 0x69, 0x74, 0x79, 0x63, 0x65, 0x6e, 0x74, 0x65, 0x72, 0x2e, 0x76, 0x31, 0x2e, 0x46, 0x69, - 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x2e, 0x46, 0x69, 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x43, 0x6c, 0x61, - 0x73, 0x73, 0x52, 0x0c, 0x66, 0x69, 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x43, 0x6c, 0x61, 0x73, 0x73, - 0x12, 0x47, 0x0a, 0x09, 0x69, 0x6e, 0x64, 0x69, 0x63, 0x61, 0x74, 0x6f, 0x72, 0x18, 0x12, 0x20, - 0x01, 0x28, 0x0b, 0x32, 0x29, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, - 0x75, 0x64, 0x2e, 0x73, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x63, 0x65, 0x6e, 0x74, 0x65, - 0x72, 0x2e, 0x76, 0x31, 0x2e, 0x49, 0x6e, 0x64, 0x69, 0x63, 0x61, 0x74, 0x6f, 0x72, 0x52, 0x09, - 0x69, 0x6e, 0x64, 0x69, 0x63, 0x61, 0x74, 0x6f, 0x72, 0x12, 0x53, 0x0a, 0x0d, 0x76, 0x75, 0x6c, - 0x6e, 0x65, 0x72, 0x61, 0x62, 0x69, 0x6c, 0x69, 0x74, 0x79, 0x18, 0x14, 0x20, 0x01, 0x28, 0x0b, - 0x32, 0x2d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, - 0x73, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x63, 0x65, 0x6e, 0x74, 0x65, 0x72, 0x2e, 0x76, - 0x31, 0x2e, 0x56, 0x75, 0x6c, 0x6e, 0x65, 0x72, 0x61, 0x62, 0x69, 0x6c, 0x69, 0x74, 0x79, 0x52, - 0x0d, 0x76, 0x75, 0x6c, 0x6e, 0x65, 0x72, 0x61, 0x62, 0x69, 0x6c, 0x69, 0x74, 0x79, 0x12, 0x49, - 0x0a, 0x10, 0x6d, 0x75, 0x74, 0x65, 0x5f, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x5f, 0x74, 0x69, - 0x6d, 0x65, 0x18, 0x15, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, - 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, - 0x74, 0x61, 0x6d, 0x70, 0x42, 0x03, 0xe0, 0x41, 0x03, 0x52, 0x0e, 0x6d, 0x75, 0x74, 0x65, 0x55, - 0x70, 0x64, 0x61, 0x74, 0x65, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x6c, 0x0a, 0x10, 0x65, 0x78, 0x74, - 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x5f, 0x73, 0x79, 0x73, 0x74, 0x65, 0x6d, 0x73, 0x18, 0x16, 0x20, - 0x03, 0x28, 0x0b, 0x32, 0x3c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, - 0x75, 0x64, 0x2e, 0x73, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x63, 0x65, 0x6e, 0x74, 0x65, - 0x72, 0x2e, 0x76, 0x31, 0x2e, 0x46, 0x69, 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x2e, 0x45, 0x78, 0x74, - 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x53, 0x79, 0x73, 0x74, 0x65, 0x6d, 0x73, 0x45, 0x6e, 0x74, 0x72, - 0x79, 0x42, 0x03, 0xe0, 0x41, 0x03, 0x52, 0x0f, 0x65, 0x78, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, - 0x53, 0x79, 0x73, 0x74, 0x65, 0x6d, 0x73, 0x12, 0x4e, 0x0a, 0x0c, 0x6d, 0x69, 0x74, 0x72, 0x65, - 0x5f, 0x61, 0x74, 0x74, 0x61, 0x63, 0x6b, 0x18, 0x19, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2b, 0x2e, - 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x65, 0x63, - 0x75, 0x72, 0x69, 0x74, 0x79, 0x63, 0x65, 0x6e, 0x74, 0x65, 0x72, 0x2e, 0x76, 0x31, 0x2e, 0x4d, - 0x69, 0x74, 0x72, 0x65, 0x41, 0x74, 0x74, 0x61, 0x63, 0x6b, 0x52, 0x0b, 0x6d, 0x69, 0x74, 0x72, - 0x65, 0x41, 0x74, 0x74, 0x61, 0x63, 0x6b, 0x12, 0x3e, 0x0a, 0x06, 0x61, 0x63, 0x63, 0x65, 0x73, - 0x73, 0x18, 0x1a, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x26, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, - 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x63, - 0x65, 0x6e, 0x74, 0x65, 0x72, 0x2e, 0x76, 0x31, 0x2e, 0x41, 0x63, 0x63, 0x65, 0x73, 0x73, 0x52, - 0x06, 0x61, 0x63, 0x63, 0x65, 0x73, 0x73, 0x12, 0x4c, 0x0a, 0x0b, 0x63, 0x6f, 0x6e, 0x6e, 0x65, - 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x1f, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2a, 0x2e, 0x67, - 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x65, 0x63, 0x75, - 0x72, 0x69, 0x74, 0x79, 0x63, 0x65, 0x6e, 0x74, 0x65, 0x72, 0x2e, 0x76, 0x31, 0x2e, 0x43, 0x6f, - 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0b, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, - 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x25, 0x0a, 0x0e, 0x6d, 0x75, 0x74, 0x65, 0x5f, 0x69, 0x6e, - 0x69, 0x74, 0x69, 0x61, 0x74, 0x6f, 0x72, 0x18, 0x1c, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0d, 0x6d, - 0x75, 0x74, 0x65, 0x49, 0x6e, 0x69, 0x74, 0x69, 0x61, 0x74, 0x6f, 0x72, 0x12, 0x45, 0x0a, 0x09, - 0x70, 0x72, 0x6f, 0x63, 0x65, 0x73, 0x73, 0x65, 0x73, 0x18, 0x1e, 0x20, 0x03, 0x28, 0x0b, 0x32, - 0x27, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, + 0x74, 0x79, 0x63, 0x65, 0x6e, 0x74, 0x65, 0x72, 0x2f, 0x76, 0x31, 0x2f, 0x73, 0x65, 0x63, 0x75, + 0x72, 0x69, 0x74, 0x79, 0x5f, 0x6d, 0x61, 0x72, 0x6b, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, + 0x1a, 0x32, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2f, 0x73, + 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x63, 0x65, 0x6e, 0x74, 0x65, 0x72, 0x2f, 0x76, 0x31, + 0x2f, 0x76, 0x75, 0x6c, 0x6e, 0x65, 0x72, 0x61, 0x62, 0x69, 0x6c, 0x69, 0x74, 0x79, 0x2e, 0x70, + 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1c, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, + 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x73, 0x74, 0x72, 0x75, 0x63, 0x74, 0x2e, 0x70, 0x72, 0x6f, + 0x74, 0x6f, 0x1a, 0x1f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, + 0x62, 0x75, 0x66, 0x2f, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x2e, 0x70, 0x72, + 0x6f, 0x74, 0x6f, 0x22, 0xf1, 0x18, 0x0a, 0x07, 0x46, 0x69, 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x12, + 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, + 0x61, 0x6d, 0x65, 0x12, 0x16, 0x0a, 0x06, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x18, 0x02, 0x20, + 0x01, 0x28, 0x09, 0x52, 0x06, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x12, 0x23, 0x0a, 0x0d, 0x72, + 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x03, 0x20, 0x01, + 0x28, 0x09, 0x52, 0x0c, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x4e, 0x61, 0x6d, 0x65, + 0x12, 0x43, 0x0a, 0x05, 0x73, 0x74, 0x61, 0x74, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0e, 0x32, + 0x2d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, + 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x63, 0x65, 0x6e, 0x74, 0x65, 0x72, 0x2e, 0x76, 0x31, + 0x2e, 0x46, 0x69, 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x65, 0x52, 0x05, + 0x73, 0x74, 0x61, 0x74, 0x65, 0x12, 0x1a, 0x0a, 0x08, 0x63, 0x61, 0x74, 0x65, 0x67, 0x6f, 0x72, + 0x79, 0x18, 0x05, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x63, 0x61, 0x74, 0x65, 0x67, 0x6f, 0x72, + 0x79, 0x12, 0x21, 0x0a, 0x0c, 0x65, 0x78, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x5f, 0x75, 0x72, + 0x69, 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x65, 0x78, 0x74, 0x65, 0x72, 0x6e, 0x61, + 0x6c, 0x55, 0x72, 0x69, 0x12, 0x6a, 0x0a, 0x11, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x5f, 0x70, + 0x72, 0x6f, 0x70, 0x65, 0x72, 0x74, 0x69, 0x65, 0x73, 0x18, 0x07, 0x20, 0x03, 0x28, 0x0b, 0x32, + 0x3d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x63, 0x65, 0x6e, 0x74, 0x65, 0x72, 0x2e, 0x76, 0x31, - 0x2e, 0x50, 0x72, 0x6f, 0x63, 0x65, 0x73, 0x73, 0x52, 0x09, 0x70, 0x72, 0x6f, 0x63, 0x65, 0x73, - 0x73, 0x65, 0x73, 0x12, 0x56, 0x0a, 0x08, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x63, 0x74, 0x73, 0x18, - 0x21, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x35, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, + 0x2e, 0x46, 0x69, 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x2e, 0x53, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x50, + 0x72, 0x6f, 0x70, 0x65, 0x72, 0x74, 0x69, 0x65, 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x10, + 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x50, 0x72, 0x6f, 0x70, 0x65, 0x72, 0x74, 0x69, 0x65, 0x73, + 0x12, 0x59, 0x0a, 0x0e, 0x73, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x5f, 0x6d, 0x61, 0x72, + 0x6b, 0x73, 0x18, 0x08, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, + 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, + 0x63, 0x65, 0x6e, 0x74, 0x65, 0x72, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x65, 0x63, 0x75, 0x72, 0x69, + 0x74, 0x79, 0x4d, 0x61, 0x72, 0x6b, 0x73, 0x42, 0x03, 0xe0, 0x41, 0x03, 0x52, 0x0d, 0x73, 0x65, + 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x4d, 0x61, 0x72, 0x6b, 0x73, 0x12, 0x39, 0x0a, 0x0a, 0x65, + 0x76, 0x65, 0x6e, 0x74, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x09, 0x20, 0x01, 0x28, 0x0b, 0x32, + 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, + 0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x09, 0x65, 0x76, 0x65, + 0x6e, 0x74, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x3b, 0x0a, 0x0b, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, + 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, + 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x0a, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x54, + 0x69, 0x6d, 0x65, 0x12, 0x4c, 0x0a, 0x08, 0x73, 0x65, 0x76, 0x65, 0x72, 0x69, 0x74, 0x79, 0x18, + 0x0c, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x30, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x63, 0x65, 0x6e, - 0x74, 0x65, 0x72, 0x2e, 0x76, 0x31, 0x2e, 0x46, 0x69, 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x2e, 0x43, - 0x6f, 0x6e, 0x74, 0x61, 0x63, 0x74, 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x42, 0x03, 0xe0, 0x41, - 0x03, 0x52, 0x08, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x63, 0x74, 0x73, 0x12, 0x4c, 0x0a, 0x0b, 0x63, - 0x6f, 0x6d, 0x70, 0x6c, 0x69, 0x61, 0x6e, 0x63, 0x65, 0x73, 0x18, 0x22, 0x20, 0x03, 0x28, 0x0b, - 0x32, 0x2a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, - 0x73, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x63, 0x65, 0x6e, 0x74, 0x65, 0x72, 0x2e, 0x76, - 0x31, 0x2e, 0x43, 0x6f, 0x6d, 0x70, 0x6c, 0x69, 0x61, 0x6e, 0x63, 0x65, 0x52, 0x0b, 0x63, 0x6f, - 0x6d, 0x70, 0x6c, 0x69, 0x61, 0x6e, 0x63, 0x65, 0x73, 0x12, 0x33, 0x0a, 0x13, 0x70, 0x61, 0x72, - 0x65, 0x6e, 0x74, 0x5f, 0x64, 0x69, 0x73, 0x70, 0x6c, 0x61, 0x79, 0x5f, 0x6e, 0x61, 0x6d, 0x65, - 0x18, 0x24, 0x20, 0x01, 0x28, 0x09, 0x42, 0x03, 0xe0, 0x41, 0x03, 0x52, 0x11, 0x70, 0x61, 0x72, - 0x65, 0x6e, 0x74, 0x44, 0x69, 0x73, 0x70, 0x6c, 0x61, 0x79, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x20, - 0x0a, 0x0b, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x25, 0x20, - 0x01, 0x28, 0x09, 0x52, 0x0b, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, - 0x12, 0x50, 0x0a, 0x0c, 0x65, 0x78, 0x66, 0x69, 0x6c, 0x74, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, - 0x18, 0x26, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, + 0x74, 0x65, 0x72, 0x2e, 0x76, 0x31, 0x2e, 0x46, 0x69, 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x2e, 0x53, + 0x65, 0x76, 0x65, 0x72, 0x69, 0x74, 0x79, 0x52, 0x08, 0x73, 0x65, 0x76, 0x65, 0x72, 0x69, 0x74, + 0x79, 0x12, 0x25, 0x0a, 0x0e, 0x63, 0x61, 0x6e, 0x6f, 0x6e, 0x69, 0x63, 0x61, 0x6c, 0x5f, 0x6e, + 0x61, 0x6d, 0x65, 0x18, 0x0e, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0d, 0x63, 0x61, 0x6e, 0x6f, 0x6e, + 0x69, 0x63, 0x61, 0x6c, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x40, 0x0a, 0x04, 0x6d, 0x75, 0x74, 0x65, + 0x18, 0x0f, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x2c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x63, 0x65, - 0x6e, 0x74, 0x65, 0x72, 0x2e, 0x76, 0x31, 0x2e, 0x45, 0x78, 0x66, 0x69, 0x6c, 0x74, 0x72, 0x61, - 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0c, 0x65, 0x78, 0x66, 0x69, 0x6c, 0x74, 0x72, 0x61, 0x74, 0x69, - 0x6f, 0x6e, 0x12, 0x4d, 0x0a, 0x0c, 0x69, 0x61, 0x6d, 0x5f, 0x62, 0x69, 0x6e, 0x64, 0x69, 0x6e, - 0x67, 0x73, 0x18, 0x27, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, + 0x6e, 0x74, 0x65, 0x72, 0x2e, 0x76, 0x31, 0x2e, 0x46, 0x69, 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x2e, + 0x4d, 0x75, 0x74, 0x65, 0x52, 0x04, 0x6d, 0x75, 0x74, 0x65, 0x12, 0x59, 0x0a, 0x0d, 0x66, 0x69, + 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x5f, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x18, 0x11, 0x20, 0x01, 0x28, + 0x0e, 0x32, 0x34, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, + 0x2e, 0x73, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x63, 0x65, 0x6e, 0x74, 0x65, 0x72, 0x2e, + 0x76, 0x31, 0x2e, 0x46, 0x69, 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x2e, 0x46, 0x69, 0x6e, 0x64, 0x69, + 0x6e, 0x67, 0x43, 0x6c, 0x61, 0x73, 0x73, 0x52, 0x0c, 0x66, 0x69, 0x6e, 0x64, 0x69, 0x6e, 0x67, + 0x43, 0x6c, 0x61, 0x73, 0x73, 0x12, 0x47, 0x0a, 0x09, 0x69, 0x6e, 0x64, 0x69, 0x63, 0x61, 0x74, + 0x6f, 0x72, 0x18, 0x12, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x29, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, - 0x63, 0x65, 0x6e, 0x74, 0x65, 0x72, 0x2e, 0x76, 0x31, 0x2e, 0x49, 0x61, 0x6d, 0x42, 0x69, 0x6e, - 0x64, 0x69, 0x6e, 0x67, 0x52, 0x0b, 0x69, 0x61, 0x6d, 0x42, 0x69, 0x6e, 0x64, 0x69, 0x6e, 0x67, - 0x73, 0x12, 0x1d, 0x0a, 0x0a, 0x6e, 0x65, 0x78, 0x74, 0x5f, 0x73, 0x74, 0x65, 0x70, 0x73, 0x18, - 0x28, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x6e, 0x65, 0x78, 0x74, 0x53, 0x74, 0x65, 0x70, 0x73, - 0x12, 0x49, 0x0a, 0x0a, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x73, 0x18, 0x2a, - 0x20, 0x03, 0x28, 0x0b, 0x32, 0x29, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, + 0x63, 0x65, 0x6e, 0x74, 0x65, 0x72, 0x2e, 0x76, 0x31, 0x2e, 0x49, 0x6e, 0x64, 0x69, 0x63, 0x61, + 0x74, 0x6f, 0x72, 0x52, 0x09, 0x69, 0x6e, 0x64, 0x69, 0x63, 0x61, 0x74, 0x6f, 0x72, 0x12, 0x53, + 0x0a, 0x0d, 0x76, 0x75, 0x6c, 0x6e, 0x65, 0x72, 0x61, 0x62, 0x69, 0x6c, 0x69, 0x74, 0x79, 0x18, + 0x14, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, + 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x63, 0x65, 0x6e, + 0x74, 0x65, 0x72, 0x2e, 0x76, 0x31, 0x2e, 0x56, 0x75, 0x6c, 0x6e, 0x65, 0x72, 0x61, 0x62, 0x69, + 0x6c, 0x69, 0x74, 0x79, 0x52, 0x0d, 0x76, 0x75, 0x6c, 0x6e, 0x65, 0x72, 0x61, 0x62, 0x69, 0x6c, + 0x69, 0x74, 0x79, 0x12, 0x49, 0x0a, 0x10, 0x6d, 0x75, 0x74, 0x65, 0x5f, 0x75, 0x70, 0x64, 0x61, + 0x74, 0x65, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x15, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, + 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, + 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x42, 0x03, 0xe0, 0x41, 0x03, 0x52, 0x0e, + 0x6d, 0x75, 0x74, 0x65, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x6c, + 0x0a, 0x10, 0x65, 0x78, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x5f, 0x73, 0x79, 0x73, 0x74, 0x65, + 0x6d, 0x73, 0x18, 0x16, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x3c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, + 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, + 0x63, 0x65, 0x6e, 0x74, 0x65, 0x72, 0x2e, 0x76, 0x31, 0x2e, 0x46, 0x69, 0x6e, 0x64, 0x69, 0x6e, + 0x67, 0x2e, 0x45, 0x78, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x53, 0x79, 0x73, 0x74, 0x65, 0x6d, + 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x42, 0x03, 0xe0, 0x41, 0x03, 0x52, 0x0f, 0x65, 0x78, 0x74, + 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x53, 0x79, 0x73, 0x74, 0x65, 0x6d, 0x73, 0x12, 0x4e, 0x0a, 0x0c, + 0x6d, 0x69, 0x74, 0x72, 0x65, 0x5f, 0x61, 0x74, 0x74, 0x61, 0x63, 0x6b, 0x18, 0x19, 0x20, 0x01, + 0x28, 0x0b, 0x32, 0x2b, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, + 0x64, 0x2e, 0x73, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x63, 0x65, 0x6e, 0x74, 0x65, 0x72, + 0x2e, 0x76, 0x31, 0x2e, 0x4d, 0x69, 0x74, 0x72, 0x65, 0x41, 0x74, 0x74, 0x61, 0x63, 0x6b, 0x52, + 0x0b, 0x6d, 0x69, 0x74, 0x72, 0x65, 0x41, 0x74, 0x74, 0x61, 0x63, 0x6b, 0x12, 0x3e, 0x0a, 0x06, + 0x61, 0x63, 0x63, 0x65, 0x73, 0x73, 0x18, 0x1a, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x26, 0x2e, 0x67, + 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x65, 0x63, 0x75, + 0x72, 0x69, 0x74, 0x79, 0x63, 0x65, 0x6e, 0x74, 0x65, 0x72, 0x2e, 0x76, 0x31, 0x2e, 0x41, 0x63, + 0x63, 0x65, 0x73, 0x73, 0x52, 0x06, 0x61, 0x63, 0x63, 0x65, 0x73, 0x73, 0x12, 0x4c, 0x0a, 0x0b, + 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x1f, 0x20, 0x03, 0x28, + 0x0b, 0x32, 0x2a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, + 0x2e, 0x73, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x63, 0x65, 0x6e, 0x74, 0x65, 0x72, 0x2e, + 0x76, 0x31, 0x2e, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0b, 0x63, + 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x25, 0x0a, 0x0e, 0x6d, 0x75, + 0x74, 0x65, 0x5f, 0x69, 0x6e, 0x69, 0x74, 0x69, 0x61, 0x74, 0x6f, 0x72, 0x18, 0x1c, 0x20, 0x01, + 0x28, 0x09, 0x52, 0x0d, 0x6d, 0x75, 0x74, 0x65, 0x49, 0x6e, 0x69, 0x74, 0x69, 0x61, 0x74, 0x6f, + 0x72, 0x12, 0x45, 0x0a, 0x09, 0x70, 0x72, 0x6f, 0x63, 0x65, 0x73, 0x73, 0x65, 0x73, 0x18, 0x1e, + 0x20, 0x03, 0x28, 0x0b, 0x32, 0x27, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x63, 0x65, 0x6e, 0x74, - 0x65, 0x72, 0x2e, 0x76, 0x31, 0x2e, 0x43, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x52, - 0x0a, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x73, 0x12, 0x4a, 0x0a, 0x0a, 0x6b, - 0x75, 0x62, 0x65, 0x72, 0x6e, 0x65, 0x74, 0x65, 0x73, 0x18, 0x2b, 0x20, 0x01, 0x28, 0x0b, 0x32, - 0x2a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, - 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x63, 0x65, 0x6e, 0x74, 0x65, 0x72, 0x2e, 0x76, 0x31, - 0x2e, 0x4b, 0x75, 0x62, 0x65, 0x72, 0x6e, 0x65, 0x74, 0x65, 0x73, 0x52, 0x0a, 0x6b, 0x75, 0x62, - 0x65, 0x72, 0x6e, 0x65, 0x74, 0x65, 0x73, 0x12, 0x44, 0x0a, 0x08, 0x64, 0x61, 0x74, 0x61, 0x62, - 0x61, 0x73, 0x65, 0x18, 0x2c, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x28, 0x2e, 0x67, 0x6f, 0x6f, 0x67, + 0x65, 0x72, 0x2e, 0x76, 0x31, 0x2e, 0x50, 0x72, 0x6f, 0x63, 0x65, 0x73, 0x73, 0x52, 0x09, 0x70, + 0x72, 0x6f, 0x63, 0x65, 0x73, 0x73, 0x65, 0x73, 0x12, 0x56, 0x0a, 0x08, 0x63, 0x6f, 0x6e, 0x74, + 0x61, 0x63, 0x74, 0x73, 0x18, 0x21, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x35, 0x2e, 0x67, 0x6f, 0x6f, + 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x65, 0x63, 0x75, 0x72, 0x69, + 0x74, 0x79, 0x63, 0x65, 0x6e, 0x74, 0x65, 0x72, 0x2e, 0x76, 0x31, 0x2e, 0x46, 0x69, 0x6e, 0x64, + 0x69, 0x6e, 0x67, 0x2e, 0x43, 0x6f, 0x6e, 0x74, 0x61, 0x63, 0x74, 0x73, 0x45, 0x6e, 0x74, 0x72, + 0x79, 0x42, 0x03, 0xe0, 0x41, 0x03, 0x52, 0x08, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x63, 0x74, 0x73, + 0x12, 0x4c, 0x0a, 0x0b, 0x63, 0x6f, 0x6d, 0x70, 0x6c, 0x69, 0x61, 0x6e, 0x63, 0x65, 0x73, 0x18, + 0x22, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, + 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x63, 0x65, 0x6e, + 0x74, 0x65, 0x72, 0x2e, 0x76, 0x31, 0x2e, 0x43, 0x6f, 0x6d, 0x70, 0x6c, 0x69, 0x61, 0x6e, 0x63, + 0x65, 0x52, 0x0b, 0x63, 0x6f, 0x6d, 0x70, 0x6c, 0x69, 0x61, 0x6e, 0x63, 0x65, 0x73, 0x12, 0x33, + 0x0a, 0x13, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x5f, 0x64, 0x69, 0x73, 0x70, 0x6c, 0x61, 0x79, + 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x24, 0x20, 0x01, 0x28, 0x09, 0x42, 0x03, 0xe0, 0x41, 0x03, + 0x52, 0x11, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x44, 0x69, 0x73, 0x70, 0x6c, 0x61, 0x79, 0x4e, + 0x61, 0x6d, 0x65, 0x12, 0x20, 0x0a, 0x0b, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, + 0x6f, 0x6e, 0x18, 0x25, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, + 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x50, 0x0a, 0x0c, 0x65, 0x78, 0x66, 0x69, 0x6c, 0x74, 0x72, + 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x26, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2c, 0x2e, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x65, 0x63, 0x75, 0x72, + 0x69, 0x74, 0x79, 0x63, 0x65, 0x6e, 0x74, 0x65, 0x72, 0x2e, 0x76, 0x31, 0x2e, 0x45, 0x78, 0x66, + 0x69, 0x6c, 0x74, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0c, 0x65, 0x78, 0x66, 0x69, 0x6c, + 0x74, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x4d, 0x0a, 0x0c, 0x69, 0x61, 0x6d, 0x5f, 0x62, + 0x69, 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x73, 0x18, 0x27, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2a, 0x2e, + 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x65, 0x63, + 0x75, 0x72, 0x69, 0x74, 0x79, 0x63, 0x65, 0x6e, 0x74, 0x65, 0x72, 0x2e, 0x76, 0x31, 0x2e, 0x49, + 0x61, 0x6d, 0x42, 0x69, 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x52, 0x0b, 0x69, 0x61, 0x6d, 0x42, 0x69, + 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x73, 0x12, 0x1d, 0x0a, 0x0a, 0x6e, 0x65, 0x78, 0x74, 0x5f, 0x73, + 0x74, 0x65, 0x70, 0x73, 0x18, 0x28, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x6e, 0x65, 0x78, 0x74, + 0x53, 0x74, 0x65, 0x70, 0x73, 0x12, 0x49, 0x0a, 0x0a, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, + 0x65, 0x72, 0x73, 0x18, 0x2a, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x29, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, - 0x79, 0x63, 0x65, 0x6e, 0x74, 0x65, 0x72, 0x2e, 0x76, 0x31, 0x2e, 0x44, 0x61, 0x74, 0x61, 0x62, - 0x61, 0x73, 0x65, 0x52, 0x08, 0x64, 0x61, 0x74, 0x61, 0x62, 0x61, 0x73, 0x65, 0x12, 0x3a, 0x0a, - 0x05, 0x66, 0x69, 0x6c, 0x65, 0x73, 0x18, 0x2e, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x24, 0x2e, 0x67, - 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x65, 0x63, 0x75, - 0x72, 0x69, 0x74, 0x79, 0x63, 0x65, 0x6e, 0x74, 0x65, 0x72, 0x2e, 0x76, 0x31, 0x2e, 0x46, 0x69, - 0x6c, 0x65, 0x52, 0x05, 0x66, 0x69, 0x6c, 0x65, 0x73, 0x1a, 0x5b, 0x0a, 0x15, 0x53, 0x6f, 0x75, - 0x72, 0x63, 0x65, 0x50, 0x72, 0x6f, 0x70, 0x65, 0x72, 0x74, 0x69, 0x65, 0x73, 0x45, 0x6e, 0x74, - 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, - 0x03, 0x6b, 0x65, 0x79, 0x12, 0x2c, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, - 0x01, 0x28, 0x0b, 0x32, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, - 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x05, 0x76, 0x61, 0x6c, - 0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x1a, 0x72, 0x0a, 0x14, 0x45, 0x78, 0x74, 0x65, 0x72, 0x6e, - 0x61, 0x6c, 0x53, 0x79, 0x73, 0x74, 0x65, 0x6d, 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, - 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, - 0x12, 0x44, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, - 0x2e, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, - 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x63, 0x65, 0x6e, 0x74, 0x65, 0x72, 0x2e, 0x76, 0x31, - 0x2e, 0x45, 0x78, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x53, 0x79, 0x73, 0x74, 0x65, 0x6d, 0x52, - 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x1a, 0x6b, 0x0a, 0x0d, 0x43, 0x6f, - 0x6e, 0x74, 0x61, 0x63, 0x74, 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x6b, - 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x44, 0x0a, - 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2e, 0x2e, 0x67, - 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x65, 0x63, 0x75, - 0x72, 0x69, 0x74, 0x79, 0x63, 0x65, 0x6e, 0x74, 0x65, 0x72, 0x2e, 0x76, 0x31, 0x2e, 0x43, 0x6f, - 0x6e, 0x74, 0x61, 0x63, 0x74, 0x44, 0x65, 0x74, 0x61, 0x69, 0x6c, 0x73, 0x52, 0x05, 0x76, 0x61, - 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x22, 0x38, 0x0a, 0x05, 0x53, 0x74, 0x61, 0x74, 0x65, - 0x12, 0x15, 0x0a, 0x11, 0x53, 0x54, 0x41, 0x54, 0x45, 0x5f, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, - 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x0a, 0x0a, 0x06, 0x41, 0x43, 0x54, 0x49, 0x56, - 0x45, 0x10, 0x01, 0x12, 0x0c, 0x0a, 0x08, 0x49, 0x4e, 0x41, 0x43, 0x54, 0x49, 0x56, 0x45, 0x10, - 0x02, 0x22, 0x51, 0x0a, 0x08, 0x53, 0x65, 0x76, 0x65, 0x72, 0x69, 0x74, 0x79, 0x12, 0x18, 0x0a, - 0x14, 0x53, 0x45, 0x56, 0x45, 0x52, 0x49, 0x54, 0x59, 0x5f, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, - 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x0c, 0x0a, 0x08, 0x43, 0x52, 0x49, 0x54, 0x49, - 0x43, 0x41, 0x4c, 0x10, 0x01, 0x12, 0x08, 0x0a, 0x04, 0x48, 0x49, 0x47, 0x48, 0x10, 0x02, 0x12, - 0x0a, 0x0a, 0x06, 0x4d, 0x45, 0x44, 0x49, 0x55, 0x4d, 0x10, 0x03, 0x12, 0x07, 0x0a, 0x03, 0x4c, - 0x4f, 0x57, 0x10, 0x04, 0x22, 0x43, 0x0a, 0x04, 0x4d, 0x75, 0x74, 0x65, 0x12, 0x14, 0x0a, 0x10, - 0x4d, 0x55, 0x54, 0x45, 0x5f, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, - 0x10, 0x00, 0x12, 0x09, 0x0a, 0x05, 0x4d, 0x55, 0x54, 0x45, 0x44, 0x10, 0x01, 0x12, 0x0b, 0x0a, - 0x07, 0x55, 0x4e, 0x4d, 0x55, 0x54, 0x45, 0x44, 0x10, 0x02, 0x12, 0x0d, 0x0a, 0x09, 0x55, 0x4e, - 0x44, 0x45, 0x46, 0x49, 0x4e, 0x45, 0x44, 0x10, 0x04, 0x22, 0x82, 0x01, 0x0a, 0x0c, 0x46, 0x69, - 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x43, 0x6c, 0x61, 0x73, 0x73, 0x12, 0x1d, 0x0a, 0x19, 0x46, 0x49, - 0x4e, 0x44, 0x49, 0x4e, 0x47, 0x5f, 0x43, 0x4c, 0x41, 0x53, 0x53, 0x5f, 0x55, 0x4e, 0x53, 0x50, - 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x0a, 0x0a, 0x06, 0x54, 0x48, 0x52, - 0x45, 0x41, 0x54, 0x10, 0x01, 0x12, 0x11, 0x0a, 0x0d, 0x56, 0x55, 0x4c, 0x4e, 0x45, 0x52, 0x41, - 0x42, 0x49, 0x4c, 0x49, 0x54, 0x59, 0x10, 0x02, 0x12, 0x14, 0x0a, 0x10, 0x4d, 0x49, 0x53, 0x43, - 0x4f, 0x4e, 0x46, 0x49, 0x47, 0x55, 0x52, 0x41, 0x54, 0x49, 0x4f, 0x4e, 0x10, 0x03, 0x12, 0x0f, - 0x0a, 0x0b, 0x4f, 0x42, 0x53, 0x45, 0x52, 0x56, 0x41, 0x54, 0x49, 0x4f, 0x4e, 0x10, 0x04, 0x12, - 0x0d, 0x0a, 0x09, 0x53, 0x43, 0x43, 0x5f, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x10, 0x05, 0x3a, 0xdb, - 0x01, 0xea, 0x41, 0xd7, 0x01, 0x0a, 0x25, 0x73, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x63, - 0x65, 0x6e, 0x74, 0x65, 0x72, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, - 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x46, 0x69, 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x12, 0x40, 0x6f, 0x72, - 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x7b, 0x6f, 0x72, 0x67, - 0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x7d, 0x2f, 0x73, 0x6f, 0x75, 0x72, 0x63, - 0x65, 0x73, 0x2f, 0x7b, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x7d, 0x2f, 0x66, 0x69, 0x6e, 0x64, - 0x69, 0x6e, 0x67, 0x73, 0x2f, 0x7b, 0x66, 0x69, 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x7d, 0x12, 0x34, - 0x66, 0x6f, 0x6c, 0x64, 0x65, 0x72, 0x73, 0x2f, 0x7b, 0x66, 0x6f, 0x6c, 0x64, 0x65, 0x72, 0x7d, - 0x2f, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x73, 0x2f, 0x7b, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, - 0x7d, 0x2f, 0x66, 0x69, 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x73, 0x2f, 0x7b, 0x66, 0x69, 0x6e, 0x64, - 0x69, 0x6e, 0x67, 0x7d, 0x12, 0x36, 0x70, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x2f, 0x7b, - 0x70, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74, 0x7d, 0x2f, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x73, - 0x2f, 0x7b, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x7d, 0x2f, 0x66, 0x69, 0x6e, 0x64, 0x69, 0x6e, - 0x67, 0x73, 0x2f, 0x7b, 0x66, 0x69, 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x7d, 0x42, 0xda, 0x01, 0x0a, - 0x22, 0x63, 0x6f, 0x6d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, - 0x64, 0x2e, 0x73, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x63, 0x65, 0x6e, 0x74, 0x65, 0x72, - 0x2e, 0x76, 0x31, 0x50, 0x01, 0x5a, 0x4c, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x67, 0x6f, - 0x6c, 0x61, 0x6e, 0x67, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x67, 0x65, 0x6e, 0x70, 0x72, 0x6f, 0x74, - 0x6f, 0x2f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2f, 0x63, 0x6c, 0x6f, - 0x75, 0x64, 0x2f, 0x73, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x63, 0x65, 0x6e, 0x74, 0x65, - 0x72, 0x2f, 0x76, 0x31, 0x3b, 0x73, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x63, 0x65, 0x6e, - 0x74, 0x65, 0x72, 0xaa, 0x02, 0x1e, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x43, 0x6c, 0x6f, - 0x75, 0x64, 0x2e, 0x53, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x43, 0x65, 0x6e, 0x74, 0x65, - 0x72, 0x2e, 0x56, 0x31, 0xca, 0x02, 0x1e, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x5c, 0x43, 0x6c, - 0x6f, 0x75, 0x64, 0x5c, 0x53, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x43, 0x65, 0x6e, 0x74, - 0x65, 0x72, 0x5c, 0x56, 0x31, 0xea, 0x02, 0x21, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x3a, 0x3a, - 0x43, 0x6c, 0x6f, 0x75, 0x64, 0x3a, 0x3a, 0x53, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x43, - 0x65, 0x6e, 0x74, 0x65, 0x72, 0x3a, 0x3a, 0x56, 0x31, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, - 0x33, + 0x79, 0x63, 0x65, 0x6e, 0x74, 0x65, 0x72, 0x2e, 0x76, 0x31, 0x2e, 0x43, 0x6f, 0x6e, 0x74, 0x61, + 0x69, 0x6e, 0x65, 0x72, 0x52, 0x0a, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x73, + 0x12, 0x4a, 0x0a, 0x0a, 0x6b, 0x75, 0x62, 0x65, 0x72, 0x6e, 0x65, 0x74, 0x65, 0x73, 0x18, 0x2b, + 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, + 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x63, 0x65, 0x6e, 0x74, + 0x65, 0x72, 0x2e, 0x76, 0x31, 0x2e, 0x4b, 0x75, 0x62, 0x65, 0x72, 0x6e, 0x65, 0x74, 0x65, 0x73, + 0x52, 0x0a, 0x6b, 0x75, 0x62, 0x65, 0x72, 0x6e, 0x65, 0x74, 0x65, 0x73, 0x12, 0x44, 0x0a, 0x08, + 0x64, 0x61, 0x74, 0x61, 0x62, 0x61, 0x73, 0x65, 0x18, 0x2c, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x28, + 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x65, + 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x63, 0x65, 0x6e, 0x74, 0x65, 0x72, 0x2e, 0x76, 0x31, 0x2e, + 0x44, 0x61, 0x74, 0x61, 0x62, 0x61, 0x73, 0x65, 0x52, 0x08, 0x64, 0x61, 0x74, 0x61, 0x62, 0x61, + 0x73, 0x65, 0x12, 0x3a, 0x0a, 0x05, 0x66, 0x69, 0x6c, 0x65, 0x73, 0x18, 0x2e, 0x20, 0x03, 0x28, + 0x0b, 0x32, 0x24, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, + 0x2e, 0x73, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x63, 0x65, 0x6e, 0x74, 0x65, 0x72, 0x2e, + 0x76, 0x31, 0x2e, 0x46, 0x69, 0x6c, 0x65, 0x52, 0x05, 0x66, 0x69, 0x6c, 0x65, 0x73, 0x12, 0x54, + 0x0a, 0x0e, 0x6b, 0x65, 0x72, 0x6e, 0x65, 0x6c, 0x5f, 0x72, 0x6f, 0x6f, 0x74, 0x6b, 0x69, 0x74, + 0x18, 0x32, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, + 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x63, 0x65, + 0x6e, 0x74, 0x65, 0x72, 0x2e, 0x76, 0x31, 0x2e, 0x4b, 0x65, 0x72, 0x6e, 0x65, 0x6c, 0x52, 0x6f, + 0x6f, 0x74, 0x6b, 0x69, 0x74, 0x52, 0x0d, 0x6b, 0x65, 0x72, 0x6e, 0x65, 0x6c, 0x52, 0x6f, 0x6f, + 0x74, 0x6b, 0x69, 0x74, 0x1a, 0x5b, 0x0a, 0x15, 0x53, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x50, 0x72, + 0x6f, 0x70, 0x65, 0x72, 0x74, 0x69, 0x65, 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, + 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, + 0x2c, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x16, + 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, + 0x2e, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, + 0x01, 0x1a, 0x72, 0x0a, 0x14, 0x45, 0x78, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x53, 0x79, 0x73, + 0x74, 0x65, 0x6d, 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, + 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x44, 0x0a, 0x05, 0x76, + 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2e, 0x2e, 0x67, 0x6f, 0x6f, + 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x65, 0x63, 0x75, 0x72, 0x69, + 0x74, 0x79, 0x63, 0x65, 0x6e, 0x74, 0x65, 0x72, 0x2e, 0x76, 0x31, 0x2e, 0x45, 0x78, 0x74, 0x65, + 0x72, 0x6e, 0x61, 0x6c, 0x53, 0x79, 0x73, 0x74, 0x65, 0x6d, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, + 0x65, 0x3a, 0x02, 0x38, 0x01, 0x1a, 0x6b, 0x0a, 0x0d, 0x43, 0x6f, 0x6e, 0x74, 0x61, 0x63, 0x74, + 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, + 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x44, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, + 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2e, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, + 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x63, + 0x65, 0x6e, 0x74, 0x65, 0x72, 0x2e, 0x76, 0x31, 0x2e, 0x43, 0x6f, 0x6e, 0x74, 0x61, 0x63, 0x74, + 0x44, 0x65, 0x74, 0x61, 0x69, 0x6c, 0x73, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, + 0x38, 0x01, 0x22, 0x38, 0x0a, 0x05, 0x53, 0x74, 0x61, 0x74, 0x65, 0x12, 0x15, 0x0a, 0x11, 0x53, + 0x54, 0x41, 0x54, 0x45, 0x5f, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, + 0x10, 0x00, 0x12, 0x0a, 0x0a, 0x06, 0x41, 0x43, 0x54, 0x49, 0x56, 0x45, 0x10, 0x01, 0x12, 0x0c, + 0x0a, 0x08, 0x49, 0x4e, 0x41, 0x43, 0x54, 0x49, 0x56, 0x45, 0x10, 0x02, 0x22, 0x51, 0x0a, 0x08, + 0x53, 0x65, 0x76, 0x65, 0x72, 0x69, 0x74, 0x79, 0x12, 0x18, 0x0a, 0x14, 0x53, 0x45, 0x56, 0x45, + 0x52, 0x49, 0x54, 0x59, 0x5f, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, + 0x10, 0x00, 0x12, 0x0c, 0x0a, 0x08, 0x43, 0x52, 0x49, 0x54, 0x49, 0x43, 0x41, 0x4c, 0x10, 0x01, + 0x12, 0x08, 0x0a, 0x04, 0x48, 0x49, 0x47, 0x48, 0x10, 0x02, 0x12, 0x0a, 0x0a, 0x06, 0x4d, 0x45, + 0x44, 0x49, 0x55, 0x4d, 0x10, 0x03, 0x12, 0x07, 0x0a, 0x03, 0x4c, 0x4f, 0x57, 0x10, 0x04, 0x22, + 0x43, 0x0a, 0x04, 0x4d, 0x75, 0x74, 0x65, 0x12, 0x14, 0x0a, 0x10, 0x4d, 0x55, 0x54, 0x45, 0x5f, + 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x09, 0x0a, + 0x05, 0x4d, 0x55, 0x54, 0x45, 0x44, 0x10, 0x01, 0x12, 0x0b, 0x0a, 0x07, 0x55, 0x4e, 0x4d, 0x55, + 0x54, 0x45, 0x44, 0x10, 0x02, 0x12, 0x0d, 0x0a, 0x09, 0x55, 0x4e, 0x44, 0x45, 0x46, 0x49, 0x4e, + 0x45, 0x44, 0x10, 0x04, 0x22, 0x82, 0x01, 0x0a, 0x0c, 0x46, 0x69, 0x6e, 0x64, 0x69, 0x6e, 0x67, + 0x43, 0x6c, 0x61, 0x73, 0x73, 0x12, 0x1d, 0x0a, 0x19, 0x46, 0x49, 0x4e, 0x44, 0x49, 0x4e, 0x47, + 0x5f, 0x43, 0x4c, 0x41, 0x53, 0x53, 0x5f, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, + 0x45, 0x44, 0x10, 0x00, 0x12, 0x0a, 0x0a, 0x06, 0x54, 0x48, 0x52, 0x45, 0x41, 0x54, 0x10, 0x01, + 0x12, 0x11, 0x0a, 0x0d, 0x56, 0x55, 0x4c, 0x4e, 0x45, 0x52, 0x41, 0x42, 0x49, 0x4c, 0x49, 0x54, + 0x59, 0x10, 0x02, 0x12, 0x14, 0x0a, 0x10, 0x4d, 0x49, 0x53, 0x43, 0x4f, 0x4e, 0x46, 0x49, 0x47, + 0x55, 0x52, 0x41, 0x54, 0x49, 0x4f, 0x4e, 0x10, 0x03, 0x12, 0x0f, 0x0a, 0x0b, 0x4f, 0x42, 0x53, + 0x45, 0x52, 0x56, 0x41, 0x54, 0x49, 0x4f, 0x4e, 0x10, 0x04, 0x12, 0x0d, 0x0a, 0x09, 0x53, 0x43, + 0x43, 0x5f, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x10, 0x05, 0x3a, 0xdb, 0x01, 0xea, 0x41, 0xd7, 0x01, + 0x0a, 0x25, 0x73, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x63, 0x65, 0x6e, 0x74, 0x65, 0x72, + 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, + 0x46, 0x69, 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x12, 0x40, 0x6f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, + 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x7b, 0x6f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61, + 0x74, 0x69, 0x6f, 0x6e, 0x7d, 0x2f, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x73, 0x2f, 0x7b, 0x73, + 0x6f, 0x75, 0x72, 0x63, 0x65, 0x7d, 0x2f, 0x66, 0x69, 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x73, 0x2f, + 0x7b, 0x66, 0x69, 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x7d, 0x12, 0x34, 0x66, 0x6f, 0x6c, 0x64, 0x65, + 0x72, 0x73, 0x2f, 0x7b, 0x66, 0x6f, 0x6c, 0x64, 0x65, 0x72, 0x7d, 0x2f, 0x73, 0x6f, 0x75, 0x72, + 0x63, 0x65, 0x73, 0x2f, 0x7b, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x7d, 0x2f, 0x66, 0x69, 0x6e, + 0x64, 0x69, 0x6e, 0x67, 0x73, 0x2f, 0x7b, 0x66, 0x69, 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x7d, 0x12, + 0x36, 0x70, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x2f, 0x7b, 0x70, 0x72, 0x6f, 0x6a, 0x65, + 0x63, 0x74, 0x7d, 0x2f, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x73, 0x2f, 0x7b, 0x73, 0x6f, 0x75, + 0x72, 0x63, 0x65, 0x7d, 0x2f, 0x66, 0x69, 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x73, 0x2f, 0x7b, 0x66, + 0x69, 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x7d, 0x42, 0xda, 0x01, 0x0a, 0x22, 0x63, 0x6f, 0x6d, 0x2e, + 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x65, 0x63, + 0x75, 0x72, 0x69, 0x74, 0x79, 0x63, 0x65, 0x6e, 0x74, 0x65, 0x72, 0x2e, 0x76, 0x31, 0x50, 0x01, + 0x5a, 0x4c, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2e, + 0x6f, 0x72, 0x67, 0x2f, 0x67, 0x65, 0x6e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x67, 0x6f, 0x6f, + 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2f, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2f, 0x73, 0x65, + 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x63, 0x65, 0x6e, 0x74, 0x65, 0x72, 0x2f, 0x76, 0x31, 0x3b, + 0x73, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x63, 0x65, 0x6e, 0x74, 0x65, 0x72, 0xaa, 0x02, + 0x1e, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x43, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x53, 0x65, + 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x43, 0x65, 0x6e, 0x74, 0x65, 0x72, 0x2e, 0x56, 0x31, 0xca, + 0x02, 0x1e, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x5c, 0x43, 0x6c, 0x6f, 0x75, 0x64, 0x5c, 0x53, + 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x43, 0x65, 0x6e, 0x74, 0x65, 0x72, 0x5c, 0x56, 0x31, + 0xea, 0x02, 0x21, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x3a, 0x3a, 0x43, 0x6c, 0x6f, 0x75, 0x64, + 0x3a, 0x3a, 0x53, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x43, 0x65, 0x6e, 0x74, 0x65, 0x72, + 0x3a, 0x3a, 0x56, 0x31, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( @@ -1050,9 +1067,10 @@ var file_google_cloud_securitycenter_v1_finding_proto_goTypes = []interface{}{ (*Kubernetes)(nil), // 20: google.cloud.securitycenter.v1.Kubernetes (*Database)(nil), // 21: google.cloud.securitycenter.v1.Database (*File)(nil), // 22: google.cloud.securitycenter.v1.File - (*structpb.Value)(nil), // 23: google.protobuf.Value - (*ExternalSystem)(nil), // 24: google.cloud.securitycenter.v1.ExternalSystem - (*ContactDetails)(nil), // 25: google.cloud.securitycenter.v1.ContactDetails + (*KernelRootkit)(nil), // 23: google.cloud.securitycenter.v1.KernelRootkit + (*structpb.Value)(nil), // 24: google.protobuf.Value + (*ExternalSystem)(nil), // 25: google.cloud.securitycenter.v1.ExternalSystem + (*ContactDetails)(nil), // 26: google.cloud.securitycenter.v1.ContactDetails } var file_google_cloud_securitycenter_v1_finding_proto_depIdxs = []int32{ 0, // 0: google.cloud.securitycenter.v1.Finding.state:type_name -> google.cloud.securitycenter.v1.Finding.State @@ -1079,14 +1097,15 @@ var file_google_cloud_securitycenter_v1_finding_proto_depIdxs = []int32{ 20, // 21: google.cloud.securitycenter.v1.Finding.kubernetes:type_name -> google.cloud.securitycenter.v1.Kubernetes 21, // 22: google.cloud.securitycenter.v1.Finding.database:type_name -> google.cloud.securitycenter.v1.Database 22, // 23: google.cloud.securitycenter.v1.Finding.files:type_name -> google.cloud.securitycenter.v1.File - 23, // 24: google.cloud.securitycenter.v1.Finding.SourcePropertiesEntry.value:type_name -> google.protobuf.Value - 24, // 25: google.cloud.securitycenter.v1.Finding.ExternalSystemsEntry.value:type_name -> google.cloud.securitycenter.v1.ExternalSystem - 25, // 26: google.cloud.securitycenter.v1.Finding.ContactsEntry.value:type_name -> google.cloud.securitycenter.v1.ContactDetails - 27, // [27:27] is the sub-list for method output_type - 27, // [27:27] is the sub-list for method input_type - 27, // [27:27] is the sub-list for extension type_name - 27, // [27:27] is the sub-list for extension extendee - 0, // [0:27] is the sub-list for field type_name + 23, // 24: google.cloud.securitycenter.v1.Finding.kernel_rootkit:type_name -> google.cloud.securitycenter.v1.KernelRootkit + 24, // 25: google.cloud.securitycenter.v1.Finding.SourcePropertiesEntry.value:type_name -> google.protobuf.Value + 25, // 26: google.cloud.securitycenter.v1.Finding.ExternalSystemsEntry.value:type_name -> google.cloud.securitycenter.v1.ExternalSystem + 26, // 27: google.cloud.securitycenter.v1.Finding.ContactsEntry.value:type_name -> google.cloud.securitycenter.v1.ContactDetails + 28, // [28:28] is the sub-list for method output_type + 28, // [28:28] is the sub-list for method input_type + 28, // [28:28] is the sub-list for extension type_name + 28, // [28:28] is the sub-list for extension extendee + 0, // [0:28] is the sub-list for field type_name } func init() { file_google_cloud_securitycenter_v1_finding_proto_init() } @@ -1105,6 +1124,7 @@ func file_google_cloud_securitycenter_v1_finding_proto_init() { file_google_cloud_securitycenter_v1_file_proto_init() file_google_cloud_securitycenter_v1_iam_binding_proto_init() file_google_cloud_securitycenter_v1_indicator_proto_init() + file_google_cloud_securitycenter_v1_kernel_rootkit_proto_init() file_google_cloud_securitycenter_v1_kubernetes_proto_init() file_google_cloud_securitycenter_v1_mitre_attack_proto_init() file_google_cloud_securitycenter_v1_process_proto_init() diff --git a/securitycenter/apiv1/securitycenterpb/folder.pb.go b/securitycenter/apiv1/securitycenterpb/folder.pb.go index 2aebd79d339c..0a8fbddac3ac 100644 --- a/securitycenter/apiv1/securitycenterpb/folder.pb.go +++ b/securitycenter/apiv1/securitycenterpb/folder.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/securitycenter/v1/folder.proto package securitycenterpb diff --git a/securitycenter/apiv1/securitycenterpb/iam_binding.pb.go b/securitycenter/apiv1/securitycenterpb/iam_binding.pb.go index 7c8d9014eca9..82e618e95a9e 100644 --- a/securitycenter/apiv1/securitycenterpb/iam_binding.pb.go +++ b/securitycenter/apiv1/securitycenterpb/iam_binding.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/securitycenter/v1/iam_binding.proto package securitycenterpb diff --git a/securitycenter/apiv1/securitycenterpb/indicator.pb.go b/securitycenter/apiv1/securitycenterpb/indicator.pb.go index 63c760fa2d8f..e5f7e76e4c59 100644 --- a/securitycenter/apiv1/securitycenterpb/indicator.pb.go +++ b/securitycenter/apiv1/securitycenterpb/indicator.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/securitycenter/v1/indicator.proto package securitycenterpb @@ -122,7 +122,6 @@ type Indicator_ProcessSignature struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Signature: - // // *Indicator_ProcessSignature_MemoryHashSignature_ // *Indicator_ProcessSignature_YaraRuleSignature_ Signature isIndicator_ProcessSignature_Signature `protobuf_oneof:"signature"` diff --git a/securitycenter/apiv1/securitycenterpb/kernel_rootkit.pb.go b/securitycenter/apiv1/securitycenterpb/kernel_rootkit.pb.go new file mode 100644 index 000000000000..9233e15acfd8 --- /dev/null +++ b/securitycenter/apiv1/securitycenterpb/kernel_rootkit.pb.go @@ -0,0 +1,290 @@ +// Copyright 2022 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 +// +// 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. + +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.27.1 +// protoc v3.15.8 +// source: google/cloud/securitycenter/v1/kernel_rootkit.proto + +package securitycenterpb + +import ( + reflect "reflect" + sync "sync" + + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +// Kernel mode rootkit signatures. +type KernelRootkit struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // Rootkit name when available. + Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` + // True if unexpected modifications of kernel code memory are present. + UnexpectedCodeModification bool `protobuf:"varint,2,opt,name=unexpected_code_modification,json=unexpectedCodeModification,proto3" json:"unexpected_code_modification,omitempty"` + // True if unexpected modifications of kernel read-only data memory are + // present. + UnexpectedReadOnlyDataModification bool `protobuf:"varint,3,opt,name=unexpected_read_only_data_modification,json=unexpectedReadOnlyDataModification,proto3" json:"unexpected_read_only_data_modification,omitempty"` + // True if `ftrace` points are present with callbacks pointing to regions + // that are not in the expected kernel or module code range. + UnexpectedFtraceHandler bool `protobuf:"varint,4,opt,name=unexpected_ftrace_handler,json=unexpectedFtraceHandler,proto3" json:"unexpected_ftrace_handler,omitempty"` + // True if `kprobe` points are present with callbacks pointing to regions + // that are not in the expected kernel or module code range. + UnexpectedKprobeHandler bool `protobuf:"varint,5,opt,name=unexpected_kprobe_handler,json=unexpectedKprobeHandler,proto3" json:"unexpected_kprobe_handler,omitempty"` + // True if kernel code pages that are not in the expected kernel or module + // code regions are present. + UnexpectedKernelCodePages bool `protobuf:"varint,6,opt,name=unexpected_kernel_code_pages,json=unexpectedKernelCodePages,proto3" json:"unexpected_kernel_code_pages,omitempty"` + // True if system call handlers that are are not in the expected kernel or + // module code regions are present. + UnexpectedSystemCallHandler bool `protobuf:"varint,7,opt,name=unexpected_system_call_handler,json=unexpectedSystemCallHandler,proto3" json:"unexpected_system_call_handler,omitempty"` + // True if interrupt handlers that are are not in the expected kernel or + // module code regions are present. + UnexpectedInterruptHandler bool `protobuf:"varint,8,opt,name=unexpected_interrupt_handler,json=unexpectedInterruptHandler,proto3" json:"unexpected_interrupt_handler,omitempty"` + // True if unexpected processes in the scheduler run queue are present. Such + // processes are in the run queue, but not in the process task list. + UnexpectedProcessesInRunqueue bool `protobuf:"varint,9,opt,name=unexpected_processes_in_runqueue,json=unexpectedProcessesInRunqueue,proto3" json:"unexpected_processes_in_runqueue,omitempty"` +} + +func (x *KernelRootkit) Reset() { + *x = KernelRootkit{} + if protoimpl.UnsafeEnabled { + mi := &file_google_cloud_securitycenter_v1_kernel_rootkit_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *KernelRootkit) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*KernelRootkit) ProtoMessage() {} + +func (x *KernelRootkit) ProtoReflect() protoreflect.Message { + mi := &file_google_cloud_securitycenter_v1_kernel_rootkit_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use KernelRootkit.ProtoReflect.Descriptor instead. +func (*KernelRootkit) Descriptor() ([]byte, []int) { + return file_google_cloud_securitycenter_v1_kernel_rootkit_proto_rawDescGZIP(), []int{0} +} + +func (x *KernelRootkit) GetName() string { + if x != nil { + return x.Name + } + return "" +} + +func (x *KernelRootkit) GetUnexpectedCodeModification() bool { + if x != nil { + return x.UnexpectedCodeModification + } + return false +} + +func (x *KernelRootkit) GetUnexpectedReadOnlyDataModification() bool { + if x != nil { + return x.UnexpectedReadOnlyDataModification + } + return false +} + +func (x *KernelRootkit) GetUnexpectedFtraceHandler() bool { + if x != nil { + return x.UnexpectedFtraceHandler + } + return false +} + +func (x *KernelRootkit) GetUnexpectedKprobeHandler() bool { + if x != nil { + return x.UnexpectedKprobeHandler + } + return false +} + +func (x *KernelRootkit) GetUnexpectedKernelCodePages() bool { + if x != nil { + return x.UnexpectedKernelCodePages + } + return false +} + +func (x *KernelRootkit) GetUnexpectedSystemCallHandler() bool { + if x != nil { + return x.UnexpectedSystemCallHandler + } + return false +} + +func (x *KernelRootkit) GetUnexpectedInterruptHandler() bool { + if x != nil { + return x.UnexpectedInterruptHandler + } + return false +} + +func (x *KernelRootkit) GetUnexpectedProcessesInRunqueue() bool { + if x != nil { + return x.UnexpectedProcessesInRunqueue + } + return false +} + +var File_google_cloud_securitycenter_v1_kernel_rootkit_proto protoreflect.FileDescriptor + +var file_google_cloud_securitycenter_v1_kernel_rootkit_proto_rawDesc = []byte{ + 0x0a, 0x33, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2f, 0x73, + 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x63, 0x65, 0x6e, 0x74, 0x65, 0x72, 0x2f, 0x76, 0x31, + 0x2f, 0x6b, 0x65, 0x72, 0x6e, 0x65, 0x6c, 0x5f, 0x72, 0x6f, 0x6f, 0x74, 0x6b, 0x69, 0x74, 0x2e, + 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x1e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, + 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x63, 0x65, 0x6e, 0x74, + 0x65, 0x72, 0x2e, 0x76, 0x31, 0x22, 0xc2, 0x04, 0x0a, 0x0d, 0x4b, 0x65, 0x72, 0x6e, 0x65, 0x6c, + 0x52, 0x6f, 0x6f, 0x74, 0x6b, 0x69, 0x74, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, + 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x40, 0x0a, 0x1c, 0x75, + 0x6e, 0x65, 0x78, 0x70, 0x65, 0x63, 0x74, 0x65, 0x64, 0x5f, 0x63, 0x6f, 0x64, 0x65, 0x5f, 0x6d, + 0x6f, 0x64, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x02, 0x20, 0x01, 0x28, + 0x08, 0x52, 0x1a, 0x75, 0x6e, 0x65, 0x78, 0x70, 0x65, 0x63, 0x74, 0x65, 0x64, 0x43, 0x6f, 0x64, + 0x65, 0x4d, 0x6f, 0x64, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x52, 0x0a, + 0x26, 0x75, 0x6e, 0x65, 0x78, 0x70, 0x65, 0x63, 0x74, 0x65, 0x64, 0x5f, 0x72, 0x65, 0x61, 0x64, + 0x5f, 0x6f, 0x6e, 0x6c, 0x79, 0x5f, 0x64, 0x61, 0x74, 0x61, 0x5f, 0x6d, 0x6f, 0x64, 0x69, 0x66, + 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x03, 0x20, 0x01, 0x28, 0x08, 0x52, 0x22, 0x75, + 0x6e, 0x65, 0x78, 0x70, 0x65, 0x63, 0x74, 0x65, 0x64, 0x52, 0x65, 0x61, 0x64, 0x4f, 0x6e, 0x6c, + 0x79, 0x44, 0x61, 0x74, 0x61, 0x4d, 0x6f, 0x64, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, + 0x6e, 0x12, 0x3a, 0x0a, 0x19, 0x75, 0x6e, 0x65, 0x78, 0x70, 0x65, 0x63, 0x74, 0x65, 0x64, 0x5f, + 0x66, 0x74, 0x72, 0x61, 0x63, 0x65, 0x5f, 0x68, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x18, 0x04, + 0x20, 0x01, 0x28, 0x08, 0x52, 0x17, 0x75, 0x6e, 0x65, 0x78, 0x70, 0x65, 0x63, 0x74, 0x65, 0x64, + 0x46, 0x74, 0x72, 0x61, 0x63, 0x65, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x12, 0x3a, 0x0a, + 0x19, 0x75, 0x6e, 0x65, 0x78, 0x70, 0x65, 0x63, 0x74, 0x65, 0x64, 0x5f, 0x6b, 0x70, 0x72, 0x6f, + 0x62, 0x65, 0x5f, 0x68, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x18, 0x05, 0x20, 0x01, 0x28, 0x08, + 0x52, 0x17, 0x75, 0x6e, 0x65, 0x78, 0x70, 0x65, 0x63, 0x74, 0x65, 0x64, 0x4b, 0x70, 0x72, 0x6f, + 0x62, 0x65, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x12, 0x3f, 0x0a, 0x1c, 0x75, 0x6e, 0x65, + 0x78, 0x70, 0x65, 0x63, 0x74, 0x65, 0x64, 0x5f, 0x6b, 0x65, 0x72, 0x6e, 0x65, 0x6c, 0x5f, 0x63, + 0x6f, 0x64, 0x65, 0x5f, 0x70, 0x61, 0x67, 0x65, 0x73, 0x18, 0x06, 0x20, 0x01, 0x28, 0x08, 0x52, + 0x19, 0x75, 0x6e, 0x65, 0x78, 0x70, 0x65, 0x63, 0x74, 0x65, 0x64, 0x4b, 0x65, 0x72, 0x6e, 0x65, + 0x6c, 0x43, 0x6f, 0x64, 0x65, 0x50, 0x61, 0x67, 0x65, 0x73, 0x12, 0x43, 0x0a, 0x1e, 0x75, 0x6e, + 0x65, 0x78, 0x70, 0x65, 0x63, 0x74, 0x65, 0x64, 0x5f, 0x73, 0x79, 0x73, 0x74, 0x65, 0x6d, 0x5f, + 0x63, 0x61, 0x6c, 0x6c, 0x5f, 0x68, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x18, 0x07, 0x20, 0x01, + 0x28, 0x08, 0x52, 0x1b, 0x75, 0x6e, 0x65, 0x78, 0x70, 0x65, 0x63, 0x74, 0x65, 0x64, 0x53, 0x79, + 0x73, 0x74, 0x65, 0x6d, 0x43, 0x61, 0x6c, 0x6c, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x12, + 0x40, 0x0a, 0x1c, 0x75, 0x6e, 0x65, 0x78, 0x70, 0x65, 0x63, 0x74, 0x65, 0x64, 0x5f, 0x69, 0x6e, + 0x74, 0x65, 0x72, 0x72, 0x75, 0x70, 0x74, 0x5f, 0x68, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x18, + 0x08, 0x20, 0x01, 0x28, 0x08, 0x52, 0x1a, 0x75, 0x6e, 0x65, 0x78, 0x70, 0x65, 0x63, 0x74, 0x65, + 0x64, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x72, 0x75, 0x70, 0x74, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, + 0x72, 0x12, 0x47, 0x0a, 0x20, 0x75, 0x6e, 0x65, 0x78, 0x70, 0x65, 0x63, 0x74, 0x65, 0x64, 0x5f, + 0x70, 0x72, 0x6f, 0x63, 0x65, 0x73, 0x73, 0x65, 0x73, 0x5f, 0x69, 0x6e, 0x5f, 0x72, 0x75, 0x6e, + 0x71, 0x75, 0x65, 0x75, 0x65, 0x18, 0x09, 0x20, 0x01, 0x28, 0x08, 0x52, 0x1d, 0x75, 0x6e, 0x65, + 0x78, 0x70, 0x65, 0x63, 0x74, 0x65, 0x64, 0x50, 0x72, 0x6f, 0x63, 0x65, 0x73, 0x73, 0x65, 0x73, + 0x49, 0x6e, 0x52, 0x75, 0x6e, 0x71, 0x75, 0x65, 0x75, 0x65, 0x42, 0xee, 0x01, 0x0a, 0x22, 0x63, + 0x6f, 0x6d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, + 0x73, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x63, 0x65, 0x6e, 0x74, 0x65, 0x72, 0x2e, 0x76, + 0x31, 0x42, 0x12, 0x4b, 0x65, 0x72, 0x6e, 0x65, 0x6c, 0x52, 0x6f, 0x6f, 0x74, 0x6b, 0x69, 0x74, + 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x4c, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, + 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x67, 0x65, 0x6e, 0x70, 0x72, + 0x6f, 0x74, 0x6f, 0x2f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2f, 0x63, + 0x6c, 0x6f, 0x75, 0x64, 0x2f, 0x73, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x63, 0x65, 0x6e, + 0x74, 0x65, 0x72, 0x2f, 0x76, 0x31, 0x3b, 0x73, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x63, + 0x65, 0x6e, 0x74, 0x65, 0x72, 0xaa, 0x02, 0x1e, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x43, + 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x53, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x43, 0x65, 0x6e, + 0x74, 0x65, 0x72, 0x2e, 0x56, 0x31, 0xca, 0x02, 0x1e, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x5c, + 0x43, 0x6c, 0x6f, 0x75, 0x64, 0x5c, 0x53, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x43, 0x65, + 0x6e, 0x74, 0x65, 0x72, 0x5c, 0x56, 0x31, 0xea, 0x02, 0x21, 0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, + 0x3a, 0x3a, 0x43, 0x6c, 0x6f, 0x75, 0x64, 0x3a, 0x3a, 0x53, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, + 0x79, 0x43, 0x65, 0x6e, 0x74, 0x65, 0x72, 0x3a, 0x3a, 0x56, 0x31, 0x62, 0x06, 0x70, 0x72, 0x6f, + 0x74, 0x6f, 0x33, +} + +var ( + file_google_cloud_securitycenter_v1_kernel_rootkit_proto_rawDescOnce sync.Once + file_google_cloud_securitycenter_v1_kernel_rootkit_proto_rawDescData = file_google_cloud_securitycenter_v1_kernel_rootkit_proto_rawDesc +) + +func file_google_cloud_securitycenter_v1_kernel_rootkit_proto_rawDescGZIP() []byte { + file_google_cloud_securitycenter_v1_kernel_rootkit_proto_rawDescOnce.Do(func() { + file_google_cloud_securitycenter_v1_kernel_rootkit_proto_rawDescData = protoimpl.X.CompressGZIP(file_google_cloud_securitycenter_v1_kernel_rootkit_proto_rawDescData) + }) + return file_google_cloud_securitycenter_v1_kernel_rootkit_proto_rawDescData +} + +var file_google_cloud_securitycenter_v1_kernel_rootkit_proto_msgTypes = make([]protoimpl.MessageInfo, 1) +var file_google_cloud_securitycenter_v1_kernel_rootkit_proto_goTypes = []interface{}{ + (*KernelRootkit)(nil), // 0: google.cloud.securitycenter.v1.KernelRootkit +} +var file_google_cloud_securitycenter_v1_kernel_rootkit_proto_depIdxs = []int32{ + 0, // [0:0] is the sub-list for method output_type + 0, // [0:0] is the sub-list for method input_type + 0, // [0:0] is the sub-list for extension type_name + 0, // [0:0] is the sub-list for extension extendee + 0, // [0:0] is the sub-list for field type_name +} + +func init() { file_google_cloud_securitycenter_v1_kernel_rootkit_proto_init() } +func file_google_cloud_securitycenter_v1_kernel_rootkit_proto_init() { + if File_google_cloud_securitycenter_v1_kernel_rootkit_proto != nil { + return + } + if !protoimpl.UnsafeEnabled { + file_google_cloud_securitycenter_v1_kernel_rootkit_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*KernelRootkit); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_google_cloud_securitycenter_v1_kernel_rootkit_proto_rawDesc, + NumEnums: 0, + NumMessages: 1, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_google_cloud_securitycenter_v1_kernel_rootkit_proto_goTypes, + DependencyIndexes: file_google_cloud_securitycenter_v1_kernel_rootkit_proto_depIdxs, + MessageInfos: file_google_cloud_securitycenter_v1_kernel_rootkit_proto_msgTypes, + }.Build() + File_google_cloud_securitycenter_v1_kernel_rootkit_proto = out.File + file_google_cloud_securitycenter_v1_kernel_rootkit_proto_rawDesc = nil + file_google_cloud_securitycenter_v1_kernel_rootkit_proto_goTypes = nil + file_google_cloud_securitycenter_v1_kernel_rootkit_proto_depIdxs = nil +} diff --git a/securitycenter/apiv1/securitycenterpb/kubernetes.pb.go b/securitycenter/apiv1/securitycenterpb/kubernetes.pb.go index a7a579ce758f..d66614ae71f9 100644 --- a/securitycenter/apiv1/securitycenterpb/kubernetes.pb.go +++ b/securitycenter/apiv1/securitycenterpb/kubernetes.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/securitycenter/v1/kubernetes.proto package securitycenterpb diff --git a/securitycenter/apiv1/securitycenterpb/label.pb.go b/securitycenter/apiv1/securitycenterpb/label.pb.go index 3c0c9005d9c6..62361c7e706d 100644 --- a/securitycenter/apiv1/securitycenterpb/label.pb.go +++ b/securitycenter/apiv1/securitycenterpb/label.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/securitycenter/v1/label.proto package securitycenterpb diff --git a/securitycenter/apiv1/securitycenterpb/mitre_attack.pb.go b/securitycenter/apiv1/securitycenterpb/mitre_attack.pb.go index f1201e690684..122be0a20dfd 100644 --- a/securitycenter/apiv1/securitycenterpb/mitre_attack.pb.go +++ b/securitycenter/apiv1/securitycenterpb/mitre_attack.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/securitycenter/v1/mitre_attack.proto package securitycenterpb diff --git a/securitycenter/apiv1/securitycenterpb/mute_config.pb.go b/securitycenter/apiv1/securitycenterpb/mute_config.pb.go index 8926aa72ef9d..f16393c02340 100644 --- a/securitycenter/apiv1/securitycenterpb/mute_config.pb.go +++ b/securitycenter/apiv1/securitycenterpb/mute_config.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/securitycenter/v1/mute_config.proto package securitycenterpb diff --git a/securitycenter/apiv1/securitycenterpb/notification_config.pb.go b/securitycenter/apiv1/securitycenterpb/notification_config.pb.go index c31becfd4de0..c901ec37c812 100644 --- a/securitycenter/apiv1/securitycenterpb/notification_config.pb.go +++ b/securitycenter/apiv1/securitycenterpb/notification_config.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/securitycenter/v1/notification_config.proto package securitycenterpb @@ -48,7 +48,9 @@ type NotificationConfig struct { // The relative resource name of this notification config. See: // https://cloud.google.com/apis/design/resource_names#relative_resource_name // Example: - // "organizations/{organization_id}/notificationConfigs/notify_public_bucket". + // "organizations/{organization_id}/notificationConfigs/notify_public_bucket", + // "folders/{folder_id}/notificationConfigs/notify_public_bucket", + // or "projects/{project_id}/notificationConfigs/notify_public_bucket". Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // The description of the notification config (max of 1024 characters). Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` @@ -61,7 +63,6 @@ type NotificationConfig struct { // The config for triggering notifications. // // Types that are assignable to NotifyConfig: - // // *NotificationConfig_StreamingConfig_ NotifyConfig isNotificationConfig_NotifyConfig `protobuf_oneof:"notify_config"` } diff --git a/securitycenter/apiv1/securitycenterpb/notification_message.pb.go b/securitycenter/apiv1/securitycenterpb/notification_message.pb.go index 068e8f832b06..2b74d1897607 100644 --- a/securitycenter/apiv1/securitycenterpb/notification_message.pb.go +++ b/securitycenter/apiv1/securitycenterpb/notification_message.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/securitycenter/v1/notification_message.proto package securitycenterpb @@ -46,7 +46,6 @@ type NotificationMessage struct { // Notification Event. // // Types that are assignable to Event: - // // *NotificationMessage_Finding Event isNotificationMessage_Event `protobuf_oneof:"event"` // The Cloud resource tied to this notification's Finding. diff --git a/securitycenter/apiv1/securitycenterpb/organization_settings.pb.go b/securitycenter/apiv1/securitycenterpb/organization_settings.pb.go index 63c4dbdbadae..af206d4bc108 100644 --- a/securitycenter/apiv1/securitycenterpb/organization_settings.pb.go +++ b/securitycenter/apiv1/securitycenterpb/organization_settings.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/securitycenter/v1/organization_settings.proto package securitycenterpb diff --git a/securitycenter/apiv1/securitycenterpb/process.pb.go b/securitycenter/apiv1/securitycenterpb/process.pb.go index cee68a67a809..ffe29b45e5e5 100644 --- a/securitycenter/apiv1/securitycenterpb/process.pb.go +++ b/securitycenter/apiv1/securitycenterpb/process.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/securitycenter/v1/process.proto package securitycenterpb diff --git a/securitycenter/apiv1/securitycenterpb/resource.pb.go b/securitycenter/apiv1/securitycenterpb/resource.pb.go index 974da341f31b..b68c845ed7e3 100644 --- a/securitycenter/apiv1/securitycenterpb/resource.pb.go +++ b/securitycenter/apiv1/securitycenterpb/resource.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/securitycenter/v1/resource.proto package securitycenterpb diff --git a/securitycenter/apiv1/securitycenterpb/run_asset_discovery_response.pb.go b/securitycenter/apiv1/securitycenterpb/run_asset_discovery_response.pb.go index c1587ea72105..8d28d03bc935 100644 --- a/securitycenter/apiv1/securitycenterpb/run_asset_discovery_response.pb.go +++ b/securitycenter/apiv1/securitycenterpb/run_asset_discovery_response.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/securitycenter/v1/run_asset_discovery_response.proto package securitycenterpb diff --git a/securitycenter/apiv1/securitycenterpb/security_marks.pb.go b/securitycenter/apiv1/securitycenterpb/security_marks.pb.go index 088a06475b34..758a2dafefac 100644 --- a/securitycenter/apiv1/securitycenterpb/security_marks.pb.go +++ b/securitycenter/apiv1/securitycenterpb/security_marks.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/securitycenter/v1/security_marks.proto package securitycenterpb @@ -54,10 +54,10 @@ type SecurityMarks struct { // Mutable user specified security marks belonging to the parent resource. // Constraints are as follows: // - // - Keys and values are treated as case insensitive - // - Keys must be between 1 - 256 characters (inclusive) - // - Keys must be letters, numbers, underscores, or dashes - // - Values have leading and trailing whitespace trimmed, remaining + // * Keys and values are treated as case insensitive + // * Keys must be between 1 - 256 characters (inclusive) + // * Keys must be letters, numbers, underscores, or dashes + // * Values have leading and trailing whitespace trimmed, remaining // characters must be between 1 - 4096 characters (inclusive) Marks map[string]string `protobuf:"bytes,2,rep,name=marks,proto3" json:"marks,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` // The canonical name of the marks. diff --git a/securitycenter/apiv1/securitycenterpb/securitycenter_service.pb.go b/securitycenter/apiv1/securitycenterpb/securitycenter_service.pb.go index 6c0e90c2659e..f1e1b8c4464c 100644 --- a/securitycenter/apiv1/securitycenterpb/securitycenter_service.pb.go +++ b/securitycenter/apiv1/securitycenterpb/securitycenter_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/securitycenter/v1/securitycenter_service.proto package securitycenterpb @@ -471,8 +471,8 @@ type CreateNotificationConfigRequest struct { Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // Required. // Unique identifier provided by the client within the parent scope. - // It must be between 1 and 128 characters, and contains alphanumeric - // characters, underscores or hyphens only. + // It must be between 1 and 128 characters and contain alphanumeric + // characters, underscores, or hyphens only. ConfigId string `protobuf:"bytes,2,opt,name=config_id,json=configId,proto3" json:"config_id,omitempty"` // Required. The notification config being created. The name and the service // account will be ignored as they are both output only fields on this @@ -652,7 +652,9 @@ type DeleteNotificationConfigRequest struct { unknownFields protoimpl.UnknownFields // Required. Name of the notification config to delete. Its format is - // "organizations/[organization_id]/notificationConfigs/[config_id]". + // "organizations/[organization_id]/notificationConfigs/[config_id]", + // "folders/[folder_id]/notificationConfigs/[config_id]", + // or "projects/[project_id]/notificationConfigs/[config_id]". Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` } @@ -695,13 +697,13 @@ func (x *DeleteNotificationConfigRequest) GetName() string { return "" } -// Request message for retrieving a big query export. +// Request message for retrieving a BigQuery export. type GetBigQueryExportRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields - // Required. Name of the big query export to retrieve. Its format is + // Required. Name of the BigQuery export to retrieve. Its format is // organizations/{organization}/bigQueryExports/{export_id}, // folders/{folder}/bigQueryExports/{export_id}, or // projects/{project}/bigQueryExports/{export_id} @@ -806,7 +808,9 @@ type GetNotificationConfigRequest struct { unknownFields protoimpl.UnknownFields // Required. Name of the notification config to get. Its format is - // "organizations/[organization_id]/notificationConfigs/[config_id]". + // "organizations/[organization_id]/notificationConfigs/[config_id]", + // "folders/[folder_id]/notificationConfigs/[config_id]", + // or "projects/[project_id]/notificationConfigs/[config_id]". Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` } @@ -955,7 +959,7 @@ type GroupAssetsRequest struct { sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields - // Required. Name of the organization to groupBy. Its format is + // Required. The name of the parent to group the assets by. Its format is // "organizations/[organization_id], folders/[folder_id], or // projects/[project_id]". Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` @@ -990,17 +994,17 @@ type GroupAssetsRequest struct { // * name: `=` // * update_time: `=`, `>`, `<`, `>=`, `<=` // - // Usage: This should be milliseconds since epoch or an RFC3339 string. - // Examples: - // `update_time = "2019-06-10T16:07:18-07:00"` - // `update_time = 1560208038000` + // Usage: This should be milliseconds since epoch or an RFC3339 string. + // Examples: + // `update_time = "2019-06-10T16:07:18-07:00"` + // `update_time = 1560208038000` // // * create_time: `=`, `>`, `<`, `>=`, `<=` // - // Usage: This should be milliseconds since epoch or an RFC3339 string. - // Examples: - // `create_time = "2019-06-10T16:07:18-07:00"` - // `create_time = 1560208038000` + // Usage: This should be milliseconds since epoch or an RFC3339 string. + // Examples: + // `create_time = "2019-06-10T16:07:18-07:00"` + // `create_time = 1560208038000` // // * iam_policy.policy_blob: `=`, `:` // * resource_properties: `=`, `:`, `>`, `<`, `>=`, `<=` @@ -1054,13 +1058,13 @@ type GroupAssetsRequest struct { // // Possible "state_change" values when compare_duration is specified: // - // - "ADDED": indicates that the asset was not present at the start of - // compare_duration, but present at reference_time. - // - "REMOVED": indicates that the asset was present at the start of - // compare_duration, but not present at reference_time. - // - "ACTIVE": indicates that the asset was present at both the - // start and the end of the time period defined by - // compare_duration and reference_time. + // * "ADDED": indicates that the asset was not present at the start of + // compare_duration, but present at reference_time. + // * "REMOVED": indicates that the asset was present at the start of + // compare_duration, but not present at reference_time. + // * "ACTIVE": indicates that the asset was present at both the + // start and the end of the time period defined by + // compare_duration and reference_time. // // If compare_duration is not specified, then the only possible state_change // is "UNUSED", which will be the state_change set for all assets present at @@ -1265,9 +1269,9 @@ type GroupFindingsRequest struct { // Restrictions have the form ` ` and may have a `-` // character in front of them to indicate negation. Examples include: // - // - name - // - source_properties.a_property - // - security_marks.marks.marka + // * name + // * source_properties.a_property + // * security_marks.marks.marka // // The supported operators are: // @@ -1291,31 +1295,31 @@ type GroupFindingsRequest struct { // * external_uri: `=`, `:` // * event_time: `=`, `>`, `<`, `>=`, `<=` // - // Usage: This should be milliseconds since epoch or an RFC3339 string. - // Examples: - // `event_time = "2019-06-10T16:07:18-07:00"` - // `event_time = 1560208038000` + // Usage: This should be milliseconds since epoch or an RFC3339 string. + // Examples: + // `event_time = "2019-06-10T16:07:18-07:00"` + // `event_time = 1560208038000` // // * severity: `=`, `:` // * workflow_state: `=`, `:` // * security_marks.marks: `=`, `:` // * source_properties: `=`, `:`, `>`, `<`, `>=`, `<=` // - // For example, `source_properties.size = 100` is a valid filter string. + // For example, `source_properties.size = 100` is a valid filter string. // - // Use a partial match on the empty string to filter based on a property - // existing: `source_properties.my_property : ""` + // Use a partial match on the empty string to filter based on a property + // existing: `source_properties.my_property : ""` // - // Use a negated partial match on the empty string to filter based on a - // property not existing: `-source_properties.my_property : ""` + // Use a negated partial match on the empty string to filter based on a + // property not existing: `-source_properties.my_property : ""` // // * resource: - // - resource.name: `=`, `:` - // - resource.parent_name: `=`, `:` - // - resource.parent_display_name: `=`, `:` - // - resource.project_name: `=`, `:` - // - resource.project_display_name: `=`, `:` - // - resource.type: `=`, `:` + // * resource.name: `=`, `:` + // * resource.parent_name: `=`, `:` + // * resource.parent_display_name: `=`, `:` + // * resource.project_name: `=`, `:` + // * resource.project_display_name: `=`, `:` + // * resource.type: `=`, `:` Filter string `protobuf:"bytes,2,opt,name=filter,proto3" json:"filter,omitempty"` // Required. Expression that defines what assets fields to use for grouping // (including `state_change`). The string value should follow SQL syntax: @@ -1351,18 +1355,18 @@ type GroupFindingsRequest struct { // // Possible "state_change" values when compare_duration is specified: // - // - "CHANGED": indicates that the finding was present and matched the given - // filter at the start of compare_duration, but changed its - // state at read_time. - // - "UNCHANGED": indicates that the finding was present and matched the given - // filter at the start of compare_duration and did not change - // state at read_time. - // - "ADDED": indicates that the finding did not match the given filter or - // was not present at the start of compare_duration, but was - // present at read_time. - // - "REMOVED": indicates that the finding was present and matched the - // filter at the start of compare_duration, but did not match - // the filter at read_time. + // * "CHANGED": indicates that the finding was present and matched the given + // filter at the start of compare_duration, but changed its + // state at read_time. + // * "UNCHANGED": indicates that the finding was present and matched the given + // filter at the start of compare_duration and did not change + // state at read_time. + // * "ADDED": indicates that the finding did not match the given filter or + // was not present at the start of compare_duration, but was + // present at read_time. + // * "REMOVED": indicates that the finding was present and matched the + // filter at the start of compare_duration, but did not match + // the filter at read_time. // // If compare_duration is not specified, then the only possible state_change // is "UNUSED", which will be the state_change set for all findings present @@ -1740,9 +1744,9 @@ type ListNotificationConfigsRequest struct { sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields - // Required. Name of the organization to list notification configs. Its format - // is "organizations/[organization_id]", "folders/[folder_id]", or - // "projects/[project_id]". + // Required. The name of the parent in which to list the notification + // configurations. Its format is "organizations/[organization_id]", + // "folders/[folder_id]", or "projects/[project_id]". Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // The value returned by the last `ListNotificationConfigsResponse`; indicates // that this is a continuation of a prior `ListNotificationConfigs` call, and @@ -2002,8 +2006,8 @@ type ListAssetsRequest struct { sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields - // Required. Name of the organization assets should belong to. Its format is - // "organizations/[organization_id], folders/[folder_id], or + // Required. The name of the parent that the listed assets belong to. Its + // format is "organizations/[organization_id], folders/[folder_id], or // projects/[project_id]". Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // Expression that defines the filter to apply across assets. @@ -2037,17 +2041,17 @@ type ListAssetsRequest struct { // * name: `=` // * update_time: `=`, `>`, `<`, `>=`, `<=` // - // Usage: This should be milliseconds since epoch or an RFC3339 string. - // Examples: - // `update_time = "2019-06-10T16:07:18-07:00"` - // `update_time = 1560208038000` + // Usage: This should be milliseconds since epoch or an RFC3339 string. + // Examples: + // `update_time = "2019-06-10T16:07:18-07:00"` + // `update_time = 1560208038000` // // * create_time: `=`, `>`, `<`, `>=`, `<=` // - // Usage: This should be milliseconds since epoch or an RFC3339 string. - // Examples: - // `create_time = "2019-06-10T16:07:18-07:00"` - // `create_time = 1560208038000` + // Usage: This should be milliseconds since epoch or an RFC3339 string. + // Examples: + // `create_time = "2019-06-10T16:07:18-07:00"` + // `create_time = 1560208038000` // // * iam_policy.policy_blob: `=`, `:` // * resource_properties: `=`, `:`, `>`, `<`, `>=`, `<=` @@ -2109,13 +2113,13 @@ type ListAssetsRequest struct { // // Possible "state_change" values when compare_duration is specified: // - // - "ADDED": indicates that the asset was not present at the start of - // compare_duration, but present at read_time. - // - "REMOVED": indicates that the asset was present at the start of - // compare_duration, but not present at read_time. - // - "ACTIVE": indicates that the asset was present at both the - // start and the end of the time period defined by - // compare_duration and read_time. + // * "ADDED": indicates that the asset was not present at the start of + // compare_duration, but present at read_time. + // * "REMOVED": indicates that the asset was present at the start of + // compare_duration, but not present at read_time. + // * "ACTIVE": indicates that the asset was present at both the + // start and the end of the time period defined by + // compare_duration and read_time. // // If compare_duration is not specified, then the only possible state_change // is "UNUSED", which will be the state_change set for all assets present at @@ -2321,9 +2325,9 @@ type ListFindingsRequest struct { // Restrictions have the form ` ` and may have a `-` // character in front of them to indicate negation. Examples include: // - // - name - // - source_properties.a_property - // - security_marks.marks.marka + // * name + // * source_properties.a_property + // * security_marks.marks.marka // // The supported operators are: // @@ -2347,33 +2351,33 @@ type ListFindingsRequest struct { // * external_uri: `=`, `:` // * event_time: `=`, `>`, `<`, `>=`, `<=` // - // Usage: This should be milliseconds since epoch or an RFC3339 string. - // Examples: - // `event_time = "2019-06-10T16:07:18-07:00"` - // `event_time = 1560208038000` + // Usage: This should be milliseconds since epoch or an RFC3339 string. + // Examples: + // `event_time = "2019-06-10T16:07:18-07:00"` + // `event_time = 1560208038000` // // * severity: `=`, `:` // * workflow_state: `=`, `:` // * security_marks.marks: `=`, `:` // * source_properties: `=`, `:`, `>`, `<`, `>=`, `<=` // - // For example, `source_properties.size = 100` is a valid filter string. + // For example, `source_properties.size = 100` is a valid filter string. // - // Use a partial match on the empty string to filter based on a property - // existing: `source_properties.my_property : ""` + // Use a partial match on the empty string to filter based on a property + // existing: `source_properties.my_property : ""` // - // Use a negated partial match on the empty string to filter based on a - // property not existing: `-source_properties.my_property : ""` + // Use a negated partial match on the empty string to filter based on a + // property not existing: `-source_properties.my_property : ""` // // * resource: - // - resource.name: `=`, `:` - // - resource.parent_name: `=`, `:` - // - resource.parent_display_name: `=`, `:` - // - resource.project_name: `=`, `:` - // - resource.project_display_name: `=`, `:` - // - resource.type: `=`, `:` - // - resource.folders.resource_folder: `=`, `:` - // - resource.display_name: `=`, `:` + // * resource.name: `=`, `:` + // * resource.parent_name: `=`, `:` + // * resource.parent_display_name: `=`, `:` + // * resource.project_name: `=`, `:` + // * resource.project_display_name: `=`, `:` + // * resource.type: `=`, `:` + // * resource.folders.resource_folder: `=`, `:` + // * resource.display_name: `=`, `:` Filter string `protobuf:"bytes,2,opt,name=filter,proto3" json:"filter,omitempty"` // Expression that defines what fields and order to use for sorting. The // string value should follow SQL syntax: comma separated list of fields. For @@ -2413,18 +2417,18 @@ type ListFindingsRequest struct { // // Possible "state_change" values when compare_duration is specified: // - // - "CHANGED": indicates that the finding was present and matched the given - // filter at the start of compare_duration, but changed its - // state at read_time. - // - "UNCHANGED": indicates that the finding was present and matched the given - // filter at the start of compare_duration and did not change - // state at read_time. - // - "ADDED": indicates that the finding did not match the given filter or - // was not present at the start of compare_duration, but was - // present at read_time. - // - "REMOVED": indicates that the finding was present and matched the - // filter at the start of compare_duration, but did not match - // the filter at read_time. + // * "CHANGED": indicates that the finding was present and matched the given + // filter at the start of compare_duration, but changed its + // state at read_time. + // * "UNCHANGED": indicates that the finding was present and matched the given + // filter at the start of compare_duration and did not change + // state at read_time. + // * "ADDED": indicates that the finding did not match the given filter or + // was not present at the start of compare_duration, but was + // present at read_time. + // * "REMOVED": indicates that the finding was present and matched the + // filter at the start of compare_duration, but did not match + // the filter at read_time. // // If compare_duration is not specified, then the only possible state_change // is "UNUSED", which will be the state_change set for all findings present at @@ -2613,10 +2617,12 @@ type SetFindingStateRequest struct { sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields - // Required. The relative resource name of the finding. See: - // https://cloud.google.com/apis/design/resource_names#relative_resource_name - // Example: - // "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}". + // Required. The [relative resource + // name](https://cloud.google.com/apis/design/resource_names#relative_resource_name) + // of the finding. Example: + // "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}", + // "folders/{folder_id}/sources/{source_id}/findings/{finding_id}", + // "projects/{project_id}/sources/{source_id}/findings/{finding_id}". Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Required. The desired State of the finding. State Finding_State `protobuf:"varint,2,opt,name=state,proto3,enum=google.cloud.securitycenter.v1.Finding_State" json:"state,omitempty"` @@ -2683,9 +2689,9 @@ type SetMuteRequest struct { sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields - // Required. The relative resource name of the finding. See: - // https://cloud.google.com/apis/design/resource_names#relative_resource_name - // Example: + // Required. The [relative resource + // name](https://cloud.google.com/apis/design/resource_names#relative_resource_name) + // of the finding. Example: // "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}", // "folders/{folder_id}/sources/{source_id}/findings/{finding_id}", // "projects/{project_id}/sources/{source_id}/findings/{finding_id}". @@ -3232,17 +3238,17 @@ func (x *UpdateSecurityMarksRequest) GetStartTime() *timestamppb.Timestamp { return nil } -// Request message for creating a big query export. +// Request message for creating a BigQuery export. type CreateBigQueryExportRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields - // Required. Resource name of the new big query export's parent. Its format is - // "organizations/[organization_id]", "folders/[folder_id]", or + // Required. The name of the parent resource of the new BigQuery export. Its + // format is "organizations/[organization_id]", "folders/[folder_id]", or // "projects/[project_id]". Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` - // Required. The big query export being created. + // Required. The BigQuery export being created. BigQueryExport *BigQueryExport `protobuf:"bytes,2,opt,name=big_query_export,json=bigQueryExport,proto3" json:"big_query_export,omitempty"` // Required. Unique identifier provided by the client within the parent scope. // It must consist of lower case letters, numbers, and hyphen, with the first @@ -3498,13 +3504,13 @@ func (x *ListBigQueryExportsResponse) GetNextPageToken() string { return "" } -// Request message for deleting a big query export. +// Request message for deleting a BigQuery export. type DeleteBigQueryExportRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields - // Required. Name of the big query export to delete. Its format is + // Required. The name of the BigQuery export to delete. Its format is // organizations/{organization}/bigQueryExports/{export_id}, // folders/{folder}/bigQueryExports/{export_id}, or // projects/{project}/bigQueryExports/{export_id} @@ -5958,7 +5964,7 @@ type SecurityCenterClient interface { DeleteMuteConfig(ctx context.Context, in *DeleteMuteConfigRequest, opts ...grpc.CallOption) (*emptypb.Empty, error) // Deletes a notification config. DeleteNotificationConfig(ctx context.Context, in *DeleteNotificationConfigRequest, opts ...grpc.CallOption) (*emptypb.Empty, error) - // Gets a big query export. + // Gets a BigQuery export. GetBigQueryExport(ctx context.Context, in *GetBigQueryExportRequest, opts ...grpc.CallOption) (*BigQueryExport, error) // Gets the access control policy on the specified Source. GetIamPolicy(ctx context.Context, in *v1.GetIamPolicyRequest, opts ...grpc.CallOption) (*v1.Policy, error) @@ -6016,6 +6022,7 @@ type SecurityCenterClient interface { UpdateFinding(ctx context.Context, in *UpdateFindingRequest, opts ...grpc.CallOption) (*Finding, error) // Updates a mute config. UpdateMuteConfig(ctx context.Context, in *UpdateMuteConfigRequest, opts ...grpc.CallOption) (*MuteConfig, error) + // // Updates a notification config. The following update // fields are allowed: description, pubsub_topic, streaming_config.filter UpdateNotificationConfig(ctx context.Context, in *UpdateNotificationConfigRequest, opts ...grpc.CallOption) (*NotificationConfig, error) @@ -6025,9 +6032,9 @@ type SecurityCenterClient interface { UpdateSource(ctx context.Context, in *UpdateSourceRequest, opts ...grpc.CallOption) (*Source, error) // Updates security marks. UpdateSecurityMarks(ctx context.Context, in *UpdateSecurityMarksRequest, opts ...grpc.CallOption) (*SecurityMarks, error) - // Creates a big query export. + // Creates a BigQuery export. CreateBigQueryExport(ctx context.Context, in *CreateBigQueryExportRequest, opts ...grpc.CallOption) (*BigQueryExport, error) - // Deletes an existing big query export. + // Deletes an existing BigQuery export. DeleteBigQueryExport(ctx context.Context, in *DeleteBigQueryExportRequest, opts ...grpc.CallOption) (*emptypb.Empty, error) // Updates a BigQuery export. UpdateBigQueryExport(ctx context.Context, in *UpdateBigQueryExportRequest, opts ...grpc.CallOption) (*BigQueryExport, error) @@ -6390,7 +6397,7 @@ type SecurityCenterServer interface { DeleteMuteConfig(context.Context, *DeleteMuteConfigRequest) (*emptypb.Empty, error) // Deletes a notification config. DeleteNotificationConfig(context.Context, *DeleteNotificationConfigRequest) (*emptypb.Empty, error) - // Gets a big query export. + // Gets a BigQuery export. GetBigQueryExport(context.Context, *GetBigQueryExportRequest) (*BigQueryExport, error) // Gets the access control policy on the specified Source. GetIamPolicy(context.Context, *v1.GetIamPolicyRequest) (*v1.Policy, error) @@ -6448,6 +6455,7 @@ type SecurityCenterServer interface { UpdateFinding(context.Context, *UpdateFindingRequest) (*Finding, error) // Updates a mute config. UpdateMuteConfig(context.Context, *UpdateMuteConfigRequest) (*MuteConfig, error) + // // Updates a notification config. The following update // fields are allowed: description, pubsub_topic, streaming_config.filter UpdateNotificationConfig(context.Context, *UpdateNotificationConfigRequest) (*NotificationConfig, error) @@ -6457,9 +6465,9 @@ type SecurityCenterServer interface { UpdateSource(context.Context, *UpdateSourceRequest) (*Source, error) // Updates security marks. UpdateSecurityMarks(context.Context, *UpdateSecurityMarksRequest) (*SecurityMarks, error) - // Creates a big query export. + // Creates a BigQuery export. CreateBigQueryExport(context.Context, *CreateBigQueryExportRequest) (*BigQueryExport, error) - // Deletes an existing big query export. + // Deletes an existing BigQuery export. DeleteBigQueryExport(context.Context, *DeleteBigQueryExportRequest) (*emptypb.Empty, error) // Updates a BigQuery export. UpdateBigQueryExport(context.Context, *UpdateBigQueryExportRequest) (*BigQueryExport, error) diff --git a/securitycenter/apiv1/securitycenterpb/source.pb.go b/securitycenter/apiv1/securitycenterpb/source.pb.go index 16b49f7f061f..8e44312137bd 100644 --- a/securitycenter/apiv1/securitycenterpb/source.pb.go +++ b/securitycenter/apiv1/securitycenterpb/source.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/securitycenter/v1/source.proto package securitycenterpb diff --git a/securitycenter/apiv1/securitycenterpb/vulnerability.pb.go b/securitycenter/apiv1/securitycenterpb/vulnerability.pb.go index 2a366b378198..8b230d1cdcca 100644 --- a/securitycenter/apiv1/securitycenterpb/vulnerability.pb.go +++ b/securitycenter/apiv1/securitycenterpb/vulnerability.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/securitycenter/v1/vulnerability.proto package securitycenterpb diff --git a/securitycenter/apiv1beta1/security_center_client.go b/securitycenter/apiv1beta1/security_center_client.go index 3b6b6164a021..49754c5a739a 100644 --- a/securitycenter/apiv1beta1/security_center_client.go +++ b/securitycenter/apiv1beta1/security_center_client.go @@ -1202,6 +1202,11 @@ func (c *restClient) CreateSource(ctx context.Context, req *securitycenterpb.Cre } baseUrl.Path += fmt.Sprintf("/v1beta1/%v/sources", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1264,6 +1269,7 @@ func (c *restClient) CreateFinding(ctx context.Context, req *securitycenterpb.Cr baseUrl.Path += fmt.Sprintf("/v1beta1/%v/findings", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("findingId", fmt.Sprintf("%v", req.GetFindingId())) baseUrl.RawQuery = params.Encode() @@ -1327,6 +1333,11 @@ func (c *restClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRe } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:getIamPolicy", req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) @@ -1380,6 +1391,11 @@ func (c *restClient) GetOrganizationSettings(ctx context.Context, req *securityc } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1433,6 +1449,11 @@ func (c *restClient) GetSource(ctx context.Context, req *securitycenterpb.GetSou } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1506,6 +1527,11 @@ func (c *restClient) GroupAssets(ctx context.Context, req *securitycenterpb.Grou } baseUrl.Path += fmt.Sprintf("/v1beta1/%v/assets:group", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { @@ -1593,6 +1619,11 @@ func (c *restClient) GroupFindings(ctx context.Context, req *securitycenterpb.Gr } baseUrl.Path += fmt.Sprintf("/v1beta1/%v/findings:group", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { @@ -1671,6 +1702,7 @@ func (c *restClient) ListAssets(ctx context.Context, req *securitycenterpb.ListA baseUrl.Path += fmt.Sprintf("/v1beta1/%v/assets", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetCompareDuration() != nil { compareDuration, err := protojson.Marshal(req.GetCompareDuration()) if err != nil { @@ -1788,6 +1820,7 @@ func (c *restClient) ListFindings(ctx context.Context, req *securitycenterpb.Lis baseUrl.Path += fmt.Sprintf("/v1beta1/%v/findings", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFieldMask() != nil { fieldMask, err := protojson.Marshal(req.GetFieldMask()) if err != nil { @@ -1895,6 +1928,7 @@ func (c *restClient) ListSources(ctx context.Context, req *securitycenterpb.List baseUrl.Path += fmt.Sprintf("/v1beta1/%v/sources", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -1979,6 +2013,11 @@ func (c *restClient) RunAssetDiscovery(ctx context.Context, req *securitycenterp } baseUrl.Path += fmt.Sprintf("/v1beta1/%v/assets:runDiscovery", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -2042,6 +2081,11 @@ func (c *restClient) SetFindingState(ctx context.Context, req *securitycenterpb. } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:setState", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2101,6 +2145,11 @@ func (c *restClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRe } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:setIamPolicy", req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) @@ -2160,6 +2209,11 @@ func (c *restClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamP } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:testIamPermissions", req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) @@ -2222,6 +2276,7 @@ func (c *restClient) UpdateFinding(ctx context.Context, req *securitycenterpb.Up baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetFinding().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -2293,6 +2348,7 @@ func (c *restClient) UpdateOrganizationSettings(ctx context.Context, req *securi baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetOrganizationSettings().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -2364,6 +2420,7 @@ func (c *restClient) UpdateSource(ctx context.Context, req *securitycenterpb.Upd baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetSource().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -2435,6 +2492,7 @@ func (c *restClient) UpdateSecurityMarks(ctx context.Context, req *securitycente baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetSecurityMarks().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetStartTime() != nil { startTime, err := protojson.Marshal(req.GetStartTime()) if err != nil { diff --git a/securitycenter/apiv1beta1/securitycenterpb/asset.pb.go b/securitycenter/apiv1beta1/securitycenterpb/asset.pb.go index 18c627757d17..4fd8b897200c 100644 --- a/securitycenter/apiv1beta1/securitycenterpb/asset.pb.go +++ b/securitycenter/apiv1beta1/securitycenterpb/asset.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/securitycenter/v1beta1/asset.proto package securitycenterpb diff --git a/securitycenter/apiv1beta1/securitycenterpb/finding.pb.go b/securitycenter/apiv1beta1/securitycenterpb/finding.pb.go index 1b486779a617..7ea0b09e069d 100644 --- a/securitycenter/apiv1beta1/securitycenterpb/finding.pb.go +++ b/securitycenter/apiv1beta1/securitycenterpb/finding.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/securitycenter/v1beta1/finding.proto package securitycenterpb diff --git a/securitycenter/apiv1beta1/securitycenterpb/organization_settings.pb.go b/securitycenter/apiv1beta1/securitycenterpb/organization_settings.pb.go index b065f75763f8..0580a8d653b7 100644 --- a/securitycenter/apiv1beta1/securitycenterpb/organization_settings.pb.go +++ b/securitycenter/apiv1beta1/securitycenterpb/organization_settings.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/securitycenter/v1beta1/organization_settings.proto package securitycenterpb diff --git a/securitycenter/apiv1beta1/securitycenterpb/run_asset_discovery_response.pb.go b/securitycenter/apiv1beta1/securitycenterpb/run_asset_discovery_response.pb.go index 2607e0681acc..3ec1aba7a30f 100644 --- a/securitycenter/apiv1beta1/securitycenterpb/run_asset_discovery_response.pb.go +++ b/securitycenter/apiv1beta1/securitycenterpb/run_asset_discovery_response.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/securitycenter/v1beta1/run_asset_discovery_response.proto package securitycenterpb diff --git a/securitycenter/apiv1beta1/securitycenterpb/security_marks.pb.go b/securitycenter/apiv1beta1/securitycenterpb/security_marks.pb.go index 07d16cc576d8..086ffff16658 100644 --- a/securitycenter/apiv1beta1/securitycenterpb/security_marks.pb.go +++ b/securitycenter/apiv1beta1/securitycenterpb/security_marks.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/securitycenter/v1beta1/security_marks.proto package securitycenterpb @@ -54,10 +54,10 @@ type SecurityMarks struct { // Mutable user specified security marks belonging to the parent resource. // Constraints are as follows: // - // - Keys and values are treated as case insensitive - // - Keys must be between 1 - 256 characters (inclusive) - // - Keys must be letters, numbers, underscores, or dashes - // - Values have leading and trailing whitespace trimmed, remaining + // * Keys and values are treated as case insensitive + // * Keys must be between 1 - 256 characters (inclusive) + // * Keys must be letters, numbers, underscores, or dashes + // * Values have leading and trailing whitespace trimmed, remaining // characters must be between 1 - 4096 characters (inclusive) Marks map[string]string `protobuf:"bytes,2,rep,name=marks,proto3" json:"marks,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` } diff --git a/securitycenter/apiv1beta1/securitycenterpb/securitycenter_service.pb.go b/securitycenter/apiv1beta1/securitycenterpb/securitycenter_service.pb.go index 1108ba38e030..f76fbb6e4368 100644 --- a/securitycenter/apiv1beta1/securitycenterpb/securitycenter_service.pb.go +++ b/securitycenter/apiv1beta1/securitycenterpb/securitycenter_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/securitycenter/v1beta1/securitycenter_service.proto package securitycenterpb @@ -407,13 +407,13 @@ type GroupAssetsRequest struct { // // Possible "state" values when compare_duration is specified: // - // - "ADDED": indicates that the asset was not present before - // compare_duration, but present at reference_time. - // - "REMOVED": indicates that the asset was present at the start of - // compare_duration, but not present at reference_time. - // - "ACTIVE": indicates that the asset was present at both the - // start and the end of the time period defined by - // compare_duration and reference_time. + // * "ADDED": indicates that the asset was not present before + // compare_duration, but present at reference_time. + // * "REMOVED": indicates that the asset was present at the start of + // compare_duration, but not present at reference_time. + // * "ACTIVE": indicates that the asset was present at both the + // start and the end of the time period defined by + // compare_duration and reference_time. // // This field is ignored if `state` is not a field in `group_by`. CompareDuration *durationpb.Duration `protobuf:"bytes,4,opt,name=compare_duration,json=compareDuration,proto3" json:"compare_duration,omitempty"` @@ -601,9 +601,9 @@ type GroupFindingsRequest struct { // Restrictions have the form ` ` and may have a `-` // character in front of them to indicate negation. Examples include: // - // - name - // - source_properties.a_property - // - security_marks.marks.marka + // * name + // * source_properties.a_property + // * security_marks.marks.marka // // The supported operators are: // @@ -1041,13 +1041,13 @@ type ListAssetsRequest struct { // // Possible "state" values when compare_duration is specified: // - // - "ADDED": indicates that the asset was not present before - // compare_duration, but present at read_time. - // - "REMOVED": indicates that the asset was present at the start of - // compare_duration, but not present at read_time. - // - "ACTIVE": indicates that the asset was present at both the - // start and the end of the time period defined by - // compare_duration and read_time. + // * "ADDED": indicates that the asset was not present before + // compare_duration, but present at read_time. + // * "REMOVED": indicates that the asset was present at the start of + // compare_duration, but not present at read_time. + // * "ACTIVE": indicates that the asset was present at both the + // start and the end of the time period defined by + // compare_duration and read_time. // // If compare_duration is not specified, then the only possible state is // "UNUSED", which indicates that the asset is present at read_time. @@ -1249,9 +1249,9 @@ type ListFindingsRequest struct { // Restrictions have the form ` ` and may have a `-` // character in front of them to indicate negation. Examples include: // - // - name - // - source_properties.a_property - // - security_marks.marks.marka + // * name + // * source_properties.a_property + // * security_marks.marks.marka // // The supported operators are: // diff --git a/securitycenter/apiv1beta1/securitycenterpb/source.pb.go b/securitycenter/apiv1beta1/securitycenterpb/source.pb.go index fc8d3282bacc..8d4889f4d383 100644 --- a/securitycenter/apiv1beta1/securitycenterpb/source.pb.go +++ b/securitycenter/apiv1beta1/securitycenterpb/source.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/securitycenter/v1beta1/source.proto package securitycenterpb diff --git a/securitycenter/apiv1p1beta1/security_center_client.go b/securitycenter/apiv1p1beta1/security_center_client.go index 4b1d70295d68..252eced728a8 100644 --- a/securitycenter/apiv1p1beta1/security_center_client.go +++ b/securitycenter/apiv1p1beta1/security_center_client.go @@ -1421,6 +1421,11 @@ func (c *restClient) CreateSource(ctx context.Context, req *securitycenterpb.Cre } baseUrl.Path += fmt.Sprintf("/v1p1beta1/%v/sources", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1483,6 +1488,7 @@ func (c *restClient) CreateFinding(ctx context.Context, req *securitycenterpb.Cr baseUrl.Path += fmt.Sprintf("/v1p1beta1/%v/findings", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("findingId", fmt.Sprintf("%v", req.GetFindingId())) baseUrl.RawQuery = params.Encode() @@ -1548,6 +1554,7 @@ func (c *restClient) CreateNotificationConfig(ctx context.Context, req *security baseUrl.Path += fmt.Sprintf("/v1p1beta1/%v/notificationConfigs", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("configId", fmt.Sprintf("%v", req.GetConfigId())) baseUrl.RawQuery = params.Encode() @@ -1605,6 +1612,11 @@ func (c *restClient) DeleteNotificationConfig(ctx context.Context, req *security } baseUrl.Path += fmt.Sprintf("/v1p1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1646,6 +1658,11 @@ func (c *restClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRe } baseUrl.Path += fmt.Sprintf("/v1p1beta1/%v:getIamPolicy", req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) @@ -1699,6 +1716,11 @@ func (c *restClient) GetNotificationConfig(ctx context.Context, req *securitycen } baseUrl.Path += fmt.Sprintf("/v1p1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1752,6 +1774,11 @@ func (c *restClient) GetOrganizationSettings(ctx context.Context, req *securityc } baseUrl.Path += fmt.Sprintf("/v1p1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1805,6 +1832,11 @@ func (c *restClient) GetSource(ctx context.Context, req *securitycenterpb.GetSou } baseUrl.Path += fmt.Sprintf("/v1p1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1878,6 +1910,11 @@ func (c *restClient) GroupAssets(ctx context.Context, req *securitycenterpb.Grou } baseUrl.Path += fmt.Sprintf("/v1p1beta1/%v/assets:group", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { @@ -1967,6 +2004,11 @@ func (c *restClient) GroupFindings(ctx context.Context, req *securitycenterpb.Gr } baseUrl.Path += fmt.Sprintf("/v1p1beta1/%v/findings:group", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { @@ -2045,6 +2087,7 @@ func (c *restClient) ListAssets(ctx context.Context, req *securitycenterpb.ListA baseUrl.Path += fmt.Sprintf("/v1p1beta1/%v/assets", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetCompareDuration() != nil { compareDuration, err := protojson.Marshal(req.GetCompareDuration()) if err != nil { @@ -2162,6 +2205,7 @@ func (c *restClient) ListFindings(ctx context.Context, req *securitycenterpb.Lis baseUrl.Path += fmt.Sprintf("/v1p1beta1/%v/findings", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetCompareDuration() != nil { compareDuration, err := protojson.Marshal(req.GetCompareDuration()) if err != nil { @@ -2276,6 +2320,7 @@ func (c *restClient) ListNotificationConfigs(ctx context.Context, req *securityc baseUrl.Path += fmt.Sprintf("/v1p1beta1/%v/notificationConfigs", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -2363,6 +2408,7 @@ func (c *restClient) ListSources(ctx context.Context, req *securitycenterpb.List baseUrl.Path += fmt.Sprintf("/v1p1beta1/%v/sources", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -2447,6 +2493,11 @@ func (c *restClient) RunAssetDiscovery(ctx context.Context, req *securitycenterp } baseUrl.Path += fmt.Sprintf("/v1p1beta1/%v/assets:runDiscovery", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -2510,6 +2561,11 @@ func (c *restClient) SetFindingState(ctx context.Context, req *securitycenterpb. } baseUrl.Path += fmt.Sprintf("/v1p1beta1/%v:setState", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2569,6 +2625,11 @@ func (c *restClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRe } baseUrl.Path += fmt.Sprintf("/v1p1beta1/%v:setIamPolicy", req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) @@ -2628,6 +2689,11 @@ func (c *restClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamP } baseUrl.Path += fmt.Sprintf("/v1p1beta1/%v:testIamPermissions", req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) @@ -2690,6 +2756,7 @@ func (c *restClient) UpdateFinding(ctx context.Context, req *securitycenterpb.Up baseUrl.Path += fmt.Sprintf("/v1p1beta1/%v", req.GetFinding().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -2762,6 +2829,7 @@ func (c *restClient) UpdateNotificationConfig(ctx context.Context, req *security baseUrl.Path += fmt.Sprintf("/v1p1beta1/%v", req.GetNotificationConfig().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -2833,6 +2901,7 @@ func (c *restClient) UpdateOrganizationSettings(ctx context.Context, req *securi baseUrl.Path += fmt.Sprintf("/v1p1beta1/%v", req.GetOrganizationSettings().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -2904,6 +2973,7 @@ func (c *restClient) UpdateSource(ctx context.Context, req *securitycenterpb.Upd baseUrl.Path += fmt.Sprintf("/v1p1beta1/%v", req.GetSource().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -2975,6 +3045,7 @@ func (c *restClient) UpdateSecurityMarks(ctx context.Context, req *securitycente baseUrl.Path += fmt.Sprintf("/v1p1beta1/%v", req.GetSecurityMarks().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetStartTime() != nil { startTime, err := protojson.Marshal(req.GetStartTime()) if err != nil { diff --git a/securitycenter/apiv1p1beta1/securitycenterpb/asset.pb.go b/securitycenter/apiv1p1beta1/securitycenterpb/asset.pb.go index a61383114d25..381559ed121e 100644 --- a/securitycenter/apiv1p1beta1/securitycenterpb/asset.pb.go +++ b/securitycenter/apiv1p1beta1/securitycenterpb/asset.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/securitycenter/v1p1beta1/asset.proto package securitycenterpb diff --git a/securitycenter/apiv1p1beta1/securitycenterpb/finding.pb.go b/securitycenter/apiv1p1beta1/securitycenterpb/finding.pb.go index ffd47438bba5..8543af875013 100644 --- a/securitycenter/apiv1p1beta1/securitycenterpb/finding.pb.go +++ b/securitycenter/apiv1p1beta1/securitycenterpb/finding.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/securitycenter/v1p1beta1/finding.proto package securitycenterpb diff --git a/securitycenter/apiv1p1beta1/securitycenterpb/folder.pb.go b/securitycenter/apiv1p1beta1/securitycenterpb/folder.pb.go index 4c3fc8802d67..cfb4f40f404a 100644 --- a/securitycenter/apiv1p1beta1/securitycenterpb/folder.pb.go +++ b/securitycenter/apiv1p1beta1/securitycenterpb/folder.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/securitycenter/v1p1beta1/folder.proto package securitycenterpb diff --git a/securitycenter/apiv1p1beta1/securitycenterpb/notification_config.pb.go b/securitycenter/apiv1p1beta1/securitycenterpb/notification_config.pb.go index b9396661c898..59f44ebf9e01 100644 --- a/securitycenter/apiv1p1beta1/securitycenterpb/notification_config.pb.go +++ b/securitycenter/apiv1p1beta1/securitycenterpb/notification_config.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/securitycenter/v1p1beta1/notification_config.proto package securitycenterpb @@ -113,7 +113,6 @@ type NotificationConfig struct { // The config for triggering notifications. // // Types that are assignable to NotifyConfig: - // // *NotificationConfig_StreamingConfig_ NotifyConfig isNotificationConfig_NotifyConfig `protobuf_oneof:"notify_config"` } diff --git a/securitycenter/apiv1p1beta1/securitycenterpb/notification_message.pb.go b/securitycenter/apiv1p1beta1/securitycenterpb/notification_message.pb.go index a9d7637fa2da..53bd84667174 100644 --- a/securitycenter/apiv1p1beta1/securitycenterpb/notification_message.pb.go +++ b/securitycenter/apiv1p1beta1/securitycenterpb/notification_message.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/securitycenter/v1p1beta1/notification_message.proto package securitycenterpb @@ -46,7 +46,6 @@ type NotificationMessage struct { // Notification Event. // // Types that are assignable to Event: - // // *NotificationMessage_Finding Event isNotificationMessage_Event `protobuf_oneof:"event"` // The Cloud resource tied to the notification. diff --git a/securitycenter/apiv1p1beta1/securitycenterpb/organization_settings.pb.go b/securitycenter/apiv1p1beta1/securitycenterpb/organization_settings.pb.go index 69ee06d30711..5ebf4305234c 100644 --- a/securitycenter/apiv1p1beta1/securitycenterpb/organization_settings.pb.go +++ b/securitycenter/apiv1p1beta1/securitycenterpb/organization_settings.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/securitycenter/v1p1beta1/organization_settings.proto package securitycenterpb diff --git a/securitycenter/apiv1p1beta1/securitycenterpb/resource.pb.go b/securitycenter/apiv1p1beta1/securitycenterpb/resource.pb.go index bfdb4987f0dc..0ade816edb06 100644 --- a/securitycenter/apiv1p1beta1/securitycenterpb/resource.pb.go +++ b/securitycenter/apiv1p1beta1/securitycenterpb/resource.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/securitycenter/v1p1beta1/resource.proto package securitycenterpb diff --git a/securitycenter/apiv1p1beta1/securitycenterpb/run_asset_discovery_response.pb.go b/securitycenter/apiv1p1beta1/securitycenterpb/run_asset_discovery_response.pb.go index df254c64c4db..e07dbe6cbb78 100644 --- a/securitycenter/apiv1p1beta1/securitycenterpb/run_asset_discovery_response.pb.go +++ b/securitycenter/apiv1p1beta1/securitycenterpb/run_asset_discovery_response.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/securitycenter/v1p1beta1/run_asset_discovery_response.proto package securitycenterpb diff --git a/securitycenter/apiv1p1beta1/securitycenterpb/security_marks.pb.go b/securitycenter/apiv1p1beta1/securitycenterpb/security_marks.pb.go index 1813378d18e2..b29ee54126a9 100644 --- a/securitycenter/apiv1p1beta1/securitycenterpb/security_marks.pb.go +++ b/securitycenter/apiv1p1beta1/securitycenterpb/security_marks.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/securitycenter/v1p1beta1/security_marks.proto package securitycenterpb @@ -54,10 +54,10 @@ type SecurityMarks struct { // Mutable user specified security marks belonging to the parent resource. // Constraints are as follows: // - // - Keys and values are treated as case insensitive - // - Keys must be between 1 - 256 characters (inclusive) - // - Keys must be letters, numbers, underscores, or dashes - // - Values have leading and trailing whitespace trimmed, remaining + // * Keys and values are treated as case insensitive + // * Keys must be between 1 - 256 characters (inclusive) + // * Keys must be letters, numbers, underscores, or dashes + // * Values have leading and trailing whitespace trimmed, remaining // characters must be between 1 - 4096 characters (inclusive) Marks map[string]string `protobuf:"bytes,2,rep,name=marks,proto3" json:"marks,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` // The canonical name of the marks. diff --git a/securitycenter/apiv1p1beta1/securitycenterpb/securitycenter_service.pb.go b/securitycenter/apiv1p1beta1/securitycenterpb/securitycenter_service.pb.go index 9bbb89fa39d3..337e8760e2c9 100644 --- a/securitycenter/apiv1p1beta1/securitycenterpb/securitycenter_service.pb.go +++ b/securitycenter/apiv1p1beta1/securitycenterpb/securitycenter_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/securitycenter/v1p1beta1/securitycenter_service.proto package securitycenterpb @@ -621,17 +621,17 @@ type GroupAssetsRequest struct { // * name: `=` // * update_time: `=`, `>`, `<`, `>=`, `<=` // - // Usage: This should be milliseconds since epoch or an RFC3339 string. - // Examples: - // `update_time = "2019-06-10T16:07:18-07:00"` - // `update_time = 1560208038000` + // Usage: This should be milliseconds since epoch or an RFC3339 string. + // Examples: + // `update_time = "2019-06-10T16:07:18-07:00"` + // `update_time = 1560208038000` // // * create_time: `=`, `>`, `<`, `>=`, `<=` // - // Usage: This should be milliseconds since epoch or an RFC3339 string. - // Examples: - // `create_time = "2019-06-10T16:07:18-07:00"` - // `create_time = 1560208038000` + // Usage: This should be milliseconds since epoch or an RFC3339 string. + // Examples: + // `create_time = "2019-06-10T16:07:18-07:00"` + // `create_time = 1560208038000` // // * iam_policy.policy_blob: `=`, `:` // * resource_properties: `=`, `:`, `>`, `<`, `>=`, `<=` @@ -685,13 +685,13 @@ type GroupAssetsRequest struct { // // Possible "state_change" values when compare_duration is specified: // - // - "ADDED": indicates that the asset was not present at the start of - // compare_duration, but present at reference_time. - // - "REMOVED": indicates that the asset was present at the start of - // compare_duration, but not present at reference_time. - // - "ACTIVE": indicates that the asset was present at both the - // start and the end of the time period defined by - // compare_duration and reference_time. + // * "ADDED": indicates that the asset was not present at the start of + // compare_duration, but present at reference_time. + // * "REMOVED": indicates that the asset was present at the start of + // compare_duration, but not present at reference_time. + // * "ACTIVE": indicates that the asset was present at both the + // start and the end of the time period defined by + // compare_duration and reference_time. // // If compare_duration is not specified, then the only possible state_change // is "UNUSED", which will be the state_change set for all assets present at @@ -896,9 +896,9 @@ type GroupFindingsRequest struct { // Restrictions have the form ` ` and may have a `-` // character in front of them to indicate negation. Examples include: // - // - name - // - source_properties.a_property - // - security_marks.marks.marka + // * name + // * source_properties.a_property + // * security_marks.marks.marka // // The supported operators are: // @@ -923,10 +923,10 @@ type GroupFindingsRequest struct { // * event_time: `=`, `>`, `<`, `>=`, `<=` // * severity: `=`, `:` // - // Usage: This should be milliseconds since epoch or an RFC3339 string. - // Examples: - // `event_time = "2019-06-10T16:07:18-07:00"` - // `event_time = 1560208038000` + // Usage: This should be milliseconds since epoch or an RFC3339 string. + // Examples: + // `event_time = "2019-06-10T16:07:18-07:00"` + // `event_time = 1560208038000` // // * security_marks.marks: `=`, `:` // * source_properties: `=`, `:`, `>`, `<`, `>=`, `<=` @@ -973,18 +973,18 @@ type GroupFindingsRequest struct { // // Possible "state_change" values when compare_duration is specified: // - // - "CHANGED": indicates that the finding was present and matched the given - // filter at the start of compare_duration, but changed its - // state at read_time. - // - "UNCHANGED": indicates that the finding was present and matched the given - // filter at the start of compare_duration and did not change - // state at read_time. - // - "ADDED": indicates that the finding did not match the given filter or - // was not present at the start of compare_duration, but was - // present at read_time. - // - "REMOVED": indicates that the finding was present and matched the - // filter at the start of compare_duration, but did not match - // the filter at read_time. + // * "CHANGED": indicates that the finding was present and matched the given + // filter at the start of compare_duration, but changed its + // state at read_time. + // * "UNCHANGED": indicates that the finding was present and matched the given + // filter at the start of compare_duration and did not change + // state at read_time. + // * "ADDED": indicates that the finding did not match the given filter or + // was not present at the start of compare_duration, but was + // present at read_time. + // * "REMOVED": indicates that the finding was present and matched the + // filter at the start of compare_duration, but did not match + // the filter at read_time. // // If compare_duration is not specified, then the only possible state_change // is "UNUSED", which will be the state_change set for all findings present @@ -1522,17 +1522,17 @@ type ListAssetsRequest struct { // * name: `=` // * update_time: `=`, `>`, `<`, `>=`, `<=` // - // Usage: This should be milliseconds since epoch or an RFC3339 string. - // Examples: - // `update_time = "2019-06-10T16:07:18-07:00"` - // `update_time = 1560208038000` + // Usage: This should be milliseconds since epoch or an RFC3339 string. + // Examples: + // `update_time = "2019-06-10T16:07:18-07:00"` + // `update_time = 1560208038000` // // * create_time: `=`, `>`, `<`, `>=`, `<=` // - // Usage: This should be milliseconds since epoch or an RFC3339 string. - // Examples: - // `create_time = "2019-06-10T16:07:18-07:00"` - // `create_time = 1560208038000` + // Usage: This should be milliseconds since epoch or an RFC3339 string. + // Examples: + // `create_time = "2019-06-10T16:07:18-07:00"` + // `create_time = 1560208038000` // // * iam_policy.policy_blob: `=`, `:` // * resource_properties: `=`, `:`, `>`, `<`, `>=`, `<=` @@ -1594,13 +1594,13 @@ type ListAssetsRequest struct { // // Possible "state_change" values when compare_duration is specified: // - // - "ADDED": indicates that the asset was not present at the start of - // compare_duration, but present at read_time. - // - "REMOVED": indicates that the asset was present at the start of - // compare_duration, but not present at read_time. - // - "ACTIVE": indicates that the asset was present at both the - // start and the end of the time period defined by - // compare_duration and read_time. + // * "ADDED": indicates that the asset was not present at the start of + // compare_duration, but present at read_time. + // * "REMOVED": indicates that the asset was present at the start of + // compare_duration, but not present at read_time. + // * "ACTIVE": indicates that the asset was present at both the + // start and the end of the time period defined by + // compare_duration and read_time. // // If compare_duration is not specified, then the only possible state_change // is "UNUSED", which will be the state_change set for all assets present at @@ -1806,9 +1806,9 @@ type ListFindingsRequest struct { // Restrictions have the form ` ` and may have a `-` // character in front of them to indicate negation. Examples include: // - // - name - // - source_properties.a_property - // - security_marks.marks.marka + // * name + // * source_properties.a_property + // * security_marks.marks.marka // // The supported operators are: // @@ -1833,10 +1833,10 @@ type ListFindingsRequest struct { // * event_time: `=`, `>`, `<`, `>=`, `<=` // * severity: `=`, `:` // - // Usage: This should be milliseconds since epoch or an RFC3339 string. - // Examples: - // `event_time = "2019-06-10T16:07:18-07:00"` - // `event_time = 1560208038000` + // Usage: This should be milliseconds since epoch or an RFC3339 string. + // Examples: + // `event_time = "2019-06-10T16:07:18-07:00"` + // `event_time = 1560208038000` // // security_marks.marks: `=`, `:` // source_properties: `=`, `:`, `>`, `<`, `>=`, `<=` @@ -1887,18 +1887,18 @@ type ListFindingsRequest struct { // // Possible "state_change" values when compare_duration is specified: // - // - "CHANGED": indicates that the finding was present and matched the given - // filter at the start of compare_duration, but changed its - // state at read_time. - // - "UNCHANGED": indicates that the finding was present and matched the given - // filter at the start of compare_duration and did not change - // state at read_time. - // - "ADDED": indicates that the finding did not match the given filter or - // was not present at the start of compare_duration, but was - // present at read_time. - // - "REMOVED": indicates that the finding was present and matched the - // filter at the start of compare_duration, but did not match - // the filter at read_time. + // * "CHANGED": indicates that the finding was present and matched the given + // filter at the start of compare_duration, but changed its + // state at read_time. + // * "UNCHANGED": indicates that the finding was present and matched the given + // filter at the start of compare_duration and did not change + // state at read_time. + // * "ADDED": indicates that the finding did not match the given filter or + // was not present at the start of compare_duration, but was + // present at read_time. + // * "REMOVED": indicates that the finding was present and matched the + // filter at the start of compare_duration, but did not match + // the filter at read_time. // // If compare_duration is not specified, then the only possible state_change // is "UNUSED", which will be the state_change set for all findings present at diff --git a/securitycenter/apiv1p1beta1/securitycenterpb/source.pb.go b/securitycenter/apiv1p1beta1/securitycenterpb/source.pb.go index 961b8bbb3a65..0d811ff0e365 100644 --- a/securitycenter/apiv1p1beta1/securitycenterpb/source.pb.go +++ b/securitycenter/apiv1p1beta1/securitycenterpb/source.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/securitycenter/v1p1beta1/source.proto package securitycenterpb diff --git a/securitycenter/settings/apiv1beta1/security_center_settings_client.go b/securitycenter/settings/apiv1beta1/security_center_settings_client.go index 8698f8528682..b2c1c5f22cbe 100644 --- a/securitycenter/settings/apiv1beta1/security_center_settings_client.go +++ b/securitycenter/settings/apiv1beta1/security_center_settings_client.go @@ -1263,8 +1263,10 @@ func (c *securityCenterSettingsRESTClient) BatchGetSettings(ctx context.Context, baseUrl.Path += fmt.Sprintf("/settings/v1beta1/%v/settings:batchGet", req.GetParent()) params := url.Values{} - if req.GetNames() != nil { - params.Add("names", fmt.Sprintf("%v", req.GetNames())) + if items := req.GetNames(); len(items) > 0 { + for _, item := range items { + params.Add("names", fmt.Sprintf("%v", item)) + } } baseUrl.RawQuery = params.Encode() diff --git a/securitycenter/settings/apiv1beta1/settingspb/billing_settings.pb.go b/securitycenter/settings/apiv1beta1/settingspb/billing_settings.pb.go index 22d6484528f8..e32fe93d71c0 100644 --- a/securitycenter/settings/apiv1beta1/settingspb/billing_settings.pb.go +++ b/securitycenter/settings/apiv1beta1/settingspb/billing_settings.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/securitycenter/settings/v1beta1/billing_settings.proto package settingspb diff --git a/securitycenter/settings/apiv1beta1/settingspb/component_settings.pb.go b/securitycenter/settings/apiv1beta1/settingspb/component_settings.pb.go index facef1fb4194..80c9c57f8597 100644 --- a/securitycenter/settings/apiv1beta1/settingspb/component_settings.pb.go +++ b/securitycenter/settings/apiv1beta1/settingspb/component_settings.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/securitycenter/settings/v1beta1/component_settings.proto package settingspb @@ -102,12 +102,12 @@ type ComponentSettings struct { // The relative resource name of the component settings. // Formats: - // - `organizations/{organization}/components/{component}/settings` - // - `folders/{folder}/components/{component}/settings` - // - `projects/{project}/components/{component}/settings` - // - `projects/{project}/locations/{location}/clusters/{cluster}/components/{component}/settings` - // - `projects/{project}/regions/{region}/clusters/{cluster}/components/{component}/settings` - // - `projects/{project}/zones/{zone}/clusters/{cluster}/components/{component}/settings` + // * `organizations/{organization}/components/{component}/settings` + // * `folders/{folder}/components/{component}/settings` + // * `projects/{project}/components/{component}/settings` + // * `projects/{project}/locations/{location}/clusters/{cluster}/components/{component}/settings` + // * `projects/{project}/regions/{region}/clusters/{cluster}/components/{component}/settings` + // * `projects/{project}/zones/{zone}/clusters/{cluster}/components/{component}/settings` Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // ENABLE to enable component, DISABLE to disable and INHERIT to inherit // setting from ancestors. @@ -128,7 +128,6 @@ type ComponentSettings struct { // Component specific settings. This must match the component value. // // Types that are assignable to SpecificSettings: - // // *ComponentSettings_ContainerThreatDetectionSettings // *ComponentSettings_EventThreatDetectionSettings // *ComponentSettings_SecurityHealthAnalyticsSettings @@ -516,10 +515,9 @@ type SecurityHealthAnalyticsSettings_NonOrgIamMemberSettings struct { // permissions on a project or the organization. Otherwise a finding will // be created. // A valid identity can be: - // - a domain that starts with "@", e.g. "@yourdomain.com". - // - a fully specified email address that does not start with "@", e.g. - // "abc@gmail.com" - // + // * a domain that starts with "@", e.g. "@yourdomain.com". + // * a fully specified email address that does not start with "@", e.g. + // "abc@gmail.com" // Regular expressions are not supported. // Service accounts are not examined by the scanner and will be omitted if // added to the list. @@ -576,12 +574,11 @@ type SecurityHealthAnalyticsSettings_AdminServiceAccountSettings struct { // allowed to have Admin, Owner or Editor roles granted to them. Otherwise // a finding will be created. // A valid identity can be: - // - a partilly specified service account that starts with "@", e.g. - // "@myproject.iam.gserviceaccount.com". This approves all the service - // accounts suffixed with the specified identity. - // - a fully specified service account that does not start with "@", e.g. - // "myadmin@myproject.iam.gserviceaccount.com". - // + // * a partilly specified service account that starts with "@", e.g. + // "@myproject.iam.gserviceaccount.com". This approves all the service + // accounts suffixed with the specified identity. + // * a fully specified service account that does not start with "@", e.g. + // "myadmin@myproject.iam.gserviceaccount.com". // Google-created service accounts are all approved. ApprovedIdentities []string `protobuf:"bytes,1,rep,name=approved_identities,json=approvedIdentities,proto3" json:"approved_identities,omitempty"` } diff --git a/securitycenter/settings/apiv1beta1/settingspb/detector.pb.go b/securitycenter/settings/apiv1beta1/settingspb/detector.pb.go index 517f3c873f29..080b0f0278f6 100644 --- a/securitycenter/settings/apiv1beta1/settingspb/detector.pb.go +++ b/securitycenter/settings/apiv1beta1/settingspb/detector.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/securitycenter/settings/v1beta1/detector.proto package settingspb diff --git a/securitycenter/settings/apiv1beta1/settingspb/securitycenter_settings_service.pb.go b/securitycenter/settings/apiv1beta1/settingspb/securitycenter_settings_service.pb.go index 4f9ede0b13e7..2ac51171b9dc 100644 --- a/securitycenter/settings/apiv1beta1/settingspb/securitycenter_settings_service.pb.go +++ b/securitycenter/settings/apiv1beta1/settingspb/securitycenter_settings_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/securitycenter/settings/v1beta1/securitycenter_settings_service.proto package settingspb @@ -50,7 +50,7 @@ type GetServiceAccountRequest struct { // Required. The relative resource name of the service account resource. // Format: - // - `organizations/{organization}/serviceAccount` + // * `organizations/{organization}/serviceAccount` Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` } @@ -102,7 +102,7 @@ type ServiceAccount struct { // The relative resource name of the service account resource. // Format: - // - `organizations/{organization}/serviceAccount` + // * `organizations/{organization}/serviceAccount` Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Security Center managed service account for the organization // example service-org-1234@scc.iam.gserviceaccount.com @@ -165,12 +165,12 @@ type GetSettingsRequest struct { // Required. The name of the settings to retrieve. // Formats: - // - `organizations/{organization}/settings` - // - `folders/{folder}/settings` - // - `projects/{project}/settings` - // - `projects/{project}/locations/{location}/clusters/{cluster}/settings` - // - `projects/{project}/regions/{region}/clusters/{cluster}/settings` - // - `projects/{project}/zones/{zone}/clusters/{cluster}/settings` + // * `organizations/{organization}/settings` + // * `folders/{folder}/settings` + // * `projects/{project}/settings` + // * `projects/{project}/locations/{location}/clusters/{cluster}/settings` + // * `projects/{project}/regions/{region}/clusters/{cluster}/settings` + // * `projects/{project}/zones/{zone}/clusters/{cluster}/settings` Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` } @@ -223,12 +223,12 @@ type UpdateSettingsRequest struct { // // The settings' `name` field is used to identify the settings to be updated. // Formats: - // - `organizations/{organization}/settings` - // - `folders/{folder}/settings` - // - `projects/{project}/settings` - // - `projects/{project}/locations/{location}/clusters/{cluster}/settings` - // - `projects/{project}/regions/{region}/clusters/{cluster}/settings` - // - `projects/{project}/zones/{zone}/clusters/{cluster}/settings` + // * `organizations/{organization}/settings` + // * `folders/{folder}/settings` + // * `projects/{project}/settings` + // * `projects/{project}/locations/{location}/clusters/{cluster}/settings` + // * `projects/{project}/regions/{region}/clusters/{cluster}/settings` + // * `projects/{project}/zones/{zone}/clusters/{cluster}/settings` Settings *Settings `protobuf:"bytes,1,opt,name=settings,proto3" json:"settings,omitempty"` // The list of fields to be updated on the settings. UpdateMask *fieldmaskpb.FieldMask `protobuf:"bytes,2,opt,name=update_mask,json=updateMask,proto3" json:"update_mask,omitempty"` @@ -288,12 +288,12 @@ type ResetSettingsRequest struct { // Required. The name of the settings to reset. // Formats: - // - `organizations/{organization}/settings` - // - `folders/{folder}/settings` - // - `projects/{project}/settings` - // - `projects/{project}/locations/{location}/clusters/{cluster}/settings` - // - `projects/{project}/regions/{region}/clusters/{cluster}/settings` - // - `projects/{project}/zones/{zone}/clusters/{cluster}/settings` + // * `organizations/{organization}/settings` + // * `folders/{folder}/settings` + // * `projects/{project}/settings` + // * `projects/{project}/locations/{location}/clusters/{cluster}/settings` + // * `projects/{project}/regions/{region}/clusters/{cluster}/settings` + // * `projects/{project}/zones/{zone}/clusters/{cluster}/settings` Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // A fingerprint used for optimistic concurrency. If none is provided, // then the existing settings will be blindly overwritten. @@ -355,17 +355,17 @@ type BatchGetSettingsRequest struct { // Required. The relative resource name of the organization shared by all of the // settings being retrieved. // Format: - // - `organizations/{organization}` + // * `organizations/{organization}` Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // The names of the settings to retrieve. // A maximum of 1000 settings can be retrieved in a batch. // Formats: - // - `organizations/{organization}/settings` - // - `folders/{folder}/settings` - // - `projects/{project}/settings` - // - `projects/{project}/locations/{location}/clusters/{cluster}/settings` - // - `projects/{project}/regions/{region}/clusters/{cluster}/settings` - // - `projects/{project}/zones/{zone}/clusters/{cluster}/settings` + // * `organizations/{organization}/settings` + // * `folders/{folder}/settings` + // * `projects/{project}/settings` + // * `projects/{project}/locations/{location}/clusters/{cluster}/settings` + // * `projects/{project}/regions/{region}/clusters/{cluster}/settings` + // * `projects/{project}/zones/{zone}/clusters/{cluster}/settings` Names []string `protobuf:"bytes,2,rep,name=names,proto3" json:"names,omitempty"` } @@ -472,12 +472,12 @@ type CalculateEffectiveSettingsRequest struct { // Required. The name of the effective settings to retrieve. // Formats: - // - `organizations/{organization}/effectiveSettings` - // - `folders/{folder}/effectiveSettings` - // - `projects/{project}/effectiveSettings` - // - `projects/{project}/locations/{location}/clusters/{cluster}/effectiveSettings` - // - `projects/{project}/regions/{region}/clusters/{cluster}/effectiveSettings` - // - `projects/{project}/zones/{zone}/clusters/{cluster}/effectiveSettings` + // * `organizations/{organization}/effectiveSettings` + // * `folders/{folder}/effectiveSettings` + // * `projects/{project}/effectiveSettings` + // * `projects/{project}/locations/{location}/clusters/{cluster}/effectiveSettings` + // * `projects/{project}/regions/{region}/clusters/{cluster}/effectiveSettings` + // * `projects/{project}/zones/{zone}/clusters/{cluster}/effectiveSettings` Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` } @@ -529,7 +529,7 @@ type BatchCalculateEffectiveSettingsRequest struct { // Required. The relative resource name of the organization shared by all of the // settings being retrieved. // Format: - // - `organizations/{organization}` + // * `organizations/{organization}` Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // The requests specifying the effective settings to retrieve. // A maximum of 1000 effective settings can be retrieved in a batch. @@ -640,12 +640,12 @@ type GetComponentSettingsRequest struct { // Required. The component settings to retrieve. // // Formats: - // - `organizations/{organization}/components/{component}/settings` - // - `folders/{folder}/components/{component}/settings` - // - `projects/{project}/components/{component}/settings` - // - `projects/{project}/locations/{location}/clusters/{cluster}/components/{component}/settings` - // - `projects/{project}/regions/{region}/clusters/{cluster}/components/{component}/settings` - // - `projects/{project}/zones/{zone}/clusters/{cluster}/components/{component}/settings` + // * `organizations/{organization}/components/{component}/settings` + // * `folders/{folder}/components/{component}/settings` + // * `projects/{project}/components/{component}/settings` + // * `projects/{project}/locations/{location}/clusters/{cluster}/components/{component}/settings` + // * `projects/{project}/regions/{region}/clusters/{cluster}/components/{component}/settings` + // * `projects/{project}/zones/{zone}/clusters/{cluster}/components/{component}/settings` Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` } @@ -698,12 +698,12 @@ type UpdateComponentSettingsRequest struct { // // The component settings' `name` field is used to identify the component // settings to be updated. Formats: - // - `organizations/{organization}/components/{component}/settings` - // - `folders/{folder}/components/{component}/settings` - // - `projects/{project}/components/{component}/settings` - // - `projects/{project}/locations/{location}/clusters/{cluster}/components/{component}/settings` - // - `projects/{project}/regions/{region}/clusters/{cluster}/components/{component}/settings` - // - `projects/{project}/zones/{zone}/clusters/{cluster}/components/{component}/settings` + // * `organizations/{organization}/components/{component}/settings` + // * `folders/{folder}/components/{component}/settings` + // * `projects/{project}/components/{component}/settings` + // * `projects/{project}/locations/{location}/clusters/{cluster}/components/{component}/settings` + // * `projects/{project}/regions/{region}/clusters/{cluster}/components/{component}/settings` + // * `projects/{project}/zones/{zone}/clusters/{cluster}/components/{component}/settings` ComponentSettings *ComponentSettings `protobuf:"bytes,1,opt,name=component_settings,json=componentSettings,proto3" json:"component_settings,omitempty"` // The list of fields to be updated on the component settings resource. UpdateMask *fieldmaskpb.FieldMask `protobuf:"bytes,2,opt,name=update_mask,json=updateMask,proto3" json:"update_mask,omitempty"` @@ -764,12 +764,12 @@ type ResetComponentSettingsRequest struct { // Required. The component settings to reset. // // Formats: - // - `organizations/{organization}/components/{component}/settings` - // - `folders/{folder}/components/{component}/settings` - // - `projects/{project}/components/{component}/settings` - // - `projects/{project}/locations/{location}/clusters/{cluster}/components/{component}/settings` - // - `projects/{project}/regions/{region}/clusters/{cluster}/components/{component}/settings` - // - `projects/{project}/zones/{zone}/clusters/{cluster}/components/{component}/settings` + // * `organizations/{organization}/components/{component}/settings` + // * `folders/{folder}/components/{component}/settings` + // * `projects/{project}/components/{component}/settings` + // * `projects/{project}/locations/{location}/clusters/{cluster}/components/{component}/settings` + // * `projects/{project}/regions/{region}/clusters/{cluster}/components/{component}/settings` + // * `projects/{project}/zones/{zone}/clusters/{cluster}/components/{component}/settings` Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // An fingerprint used for optimistic concurrency. If none is provided, // then the existing settings will be blindly overwritten. @@ -831,12 +831,12 @@ type CalculateEffectiveComponentSettingsRequest struct { // Required. The effective component settings to retrieve. // // Formats: - // - `organizations/{organization}/components/{component}/settings` - // - `folders/{folder}/components/{component}/settings` - // - `projects/{project}/components/{component}/settings` - // - `projects/{project}/locations/{location}/clusters/{cluster}/components/{component}/settings` - // - `projects/{project}/regions/{region}/clusters/{cluster}/components/{component}/settings` - // - `projects/{project}/zones/{zone}/clusters/{cluster}/components/{component}/settings` + // * `organizations/{organization}/components/{component}/settings` + // * `folders/{folder}/components/{component}/settings` + // * `projects/{project}/components/{component}/settings` + // * `projects/{project}/locations/{location}/clusters/{cluster}/components/{component}/settings` + // * `projects/{project}/regions/{region}/clusters/{cluster}/components/{component}/settings` + // * `projects/{project}/zones/{zone}/clusters/{cluster}/components/{component}/settings` Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` } @@ -887,12 +887,12 @@ type ListDetectorsRequest struct { // Required. The parent, which owns this collection of detectors. // Format: - // - `organizations/{organization}` + // * `organizations/{organization}` Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // Filters to apply on the response. Filters can be applied on: - // - components - // - labels - // - billing tiers + // * components + // * labels + // * billing tiers // // Component filters will retrieve only detectors for the components // specified. Label filters will retrieve only detectors that match one of the @@ -1040,7 +1040,7 @@ type ListComponentsRequest struct { // Required. The parent, which owns this collection of components. // Format: - // - `organizations/{organization}` + // * `organizations/{organization}` Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // The maximum number of components to return. The service may return fewer // than this value. If unspecified, at most 100 components will be returned. @@ -2162,14 +2162,14 @@ type SecurityCenterSettingsServiceClient interface { // CalculateEffectiveSettings looks up all of the Security Center // Settings resources in the GCP resource hierarchy, and calculates the // effective settings on that resource by applying the following rules: - // - Settings provided closer to the target resource take precedence over - // those further away (e.g. folder will override organization level - // settings). - // - Product defaults can be overridden at org, folder, project, and cluster - // levels. - // - Detectors will be filtered out if they belong to a billing tier the - // customer - // has not configured. + // * Settings provided closer to the target resource take precedence over + // those further away (e.g. folder will override organization level + // settings). + // * Product defaults can be overridden at org, folder, project, and cluster + // levels. + // * Detectors will be filtered out if they belong to a billing tier the + // customer + // has not configured. CalculateEffectiveSettings(ctx context.Context, in *CalculateEffectiveSettingsRequest, opts ...grpc.CallOption) (*Settings, error) // Gets a list of effective settings. BatchCalculateEffectiveSettings(ctx context.Context, in *BatchCalculateEffectiveSettingsRequest, opts ...grpc.CallOption) (*BatchCalculateEffectiveSettingsResponse, error) @@ -2349,14 +2349,14 @@ type SecurityCenterSettingsServiceServer interface { // CalculateEffectiveSettings looks up all of the Security Center // Settings resources in the GCP resource hierarchy, and calculates the // effective settings on that resource by applying the following rules: - // - Settings provided closer to the target resource take precedence over - // those further away (e.g. folder will override organization level - // settings). - // - Product defaults can be overridden at org, folder, project, and cluster - // levels. - // - Detectors will be filtered out if they belong to a billing tier the - // customer - // has not configured. + // * Settings provided closer to the target resource take precedence over + // those further away (e.g. folder will override organization level + // settings). + // * Product defaults can be overridden at org, folder, project, and cluster + // levels. + // * Detectors will be filtered out if they belong to a billing tier the + // customer + // has not configured. CalculateEffectiveSettings(context.Context, *CalculateEffectiveSettingsRequest) (*Settings, error) // Gets a list of effective settings. BatchCalculateEffectiveSettings(context.Context, *BatchCalculateEffectiveSettingsRequest) (*BatchCalculateEffectiveSettingsResponse, error) diff --git a/securitycenter/settings/apiv1beta1/settingspb/settings.pb.go b/securitycenter/settings/apiv1beta1/settingspb/settings.pb.go index c3ce475e7801..ecba333c9dbd 100644 --- a/securitycenter/settings/apiv1beta1/settingspb/settings.pb.go +++ b/securitycenter/settings/apiv1beta1/settingspb/settings.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/securitycenter/settings/v1beta1/settings.proto package settingspb @@ -119,12 +119,12 @@ type Settings struct { // The relative resource name of the settings resource. // Formats: - // - `organizations/{organization}/settings` - // - `folders/{folder}/settings` - // - `projects/{project}/settings` - // - `projects/{project}/locations/{location}/clusters/{cluster}/settings` - // - `projects/{project}/regions/{region}/clusters/{cluster}/settings` - // - `projects/{project}/zones/{zone}/clusters/{cluster}/settings` + // * `organizations/{organization}/settings` + // * `folders/{folder}/settings` + // * `projects/{project}/settings` + // * `projects/{project}/locations/{location}/clusters/{cluster}/settings` + // * `projects/{project}/regions/{region}/clusters/{cluster}/settings` + // * `projects/{project}/zones/{zone}/clusters/{cluster}/settings` Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Billing settings BillingSettings *BillingSettings `protobuf:"bytes,2,opt,name=billing_settings,json=billingSettings,proto3" json:"billing_settings,omitempty"` diff --git a/securitycenter/settings/apiv1beta1/settingspb/sink_settings.pb.go b/securitycenter/settings/apiv1beta1/settingspb/sink_settings.pb.go index 9f83aab3dad9..5f0e9af158e6 100644 --- a/securitycenter/settings/apiv1beta1/settingspb/sink_settings.pb.go +++ b/securitycenter/settings/apiv1beta1/settingspb/sink_settings.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/securitycenter/settings/v1beta1/sink_settings.proto package settingspb diff --git a/servicecontrol/apiv1/doc.go b/servicecontrol/apiv1/doc.go index bd6d29ca2e27..d0a1179448f3 100644 --- a/servicecontrol/apiv1/doc.go +++ b/servicecontrol/apiv1/doc.go @@ -81,6 +81,8 @@ package servicecontrol // import "cloud.google.com/go/servicecontrol/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -170,3 +172,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/servicecontrol/apiv1/gapic_metadata.json b/servicecontrol/apiv1/gapic_metadata.json index 6ae772250050..6d0adb927e6f 100644 --- a/servicecontrol/apiv1/gapic_metadata.json +++ b/servicecontrol/apiv1/gapic_metadata.json @@ -16,6 +16,16 @@ ] } } + }, + "rest": { + "libraryClient": "QuotaControllerClient", + "rpcs": { + "AllocateQuota": { + "methods": [ + "AllocateQuota" + ] + } + } } } }, @@ -35,6 +45,21 @@ ] } } + }, + "rest": { + "libraryClient": "ServiceControllerClient", + "rpcs": { + "Check": { + "methods": [ + "Check" + ] + }, + "Report": { + "methods": [ + "Report" + ] + } + } } } } diff --git a/servicecontrol/apiv1/quota_controller_client.go b/servicecontrol/apiv1/quota_controller_client.go index 4fe33cc3b230..2b44cd3ec209 100644 --- a/servicecontrol/apiv1/quota_controller_client.go +++ b/servicecontrol/apiv1/quota_controller_client.go @@ -17,18 +17,24 @@ package servicecontrol import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" servicecontrolpb "cloud.google.com/go/servicecontrol/apiv1/servicecontrolpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" ) var newQuotaControllerClientHook clientHook @@ -56,6 +62,12 @@ func defaultQuotaControllerCallOptions() *QuotaControllerCallOptions { } } +func defaultQuotaControllerRESTCallOptions() *QuotaControllerCallOptions { + return &QuotaControllerCallOptions{ + AllocateQuota: []gax.CallOption{}, + } +} + // internalQuotaControllerClient is an interface that defines the methods available from Service Control API. type internalQuotaControllerClient interface { Close() error @@ -201,6 +213,77 @@ func (c *quotaControllerGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type quotaControllerRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing QuotaControllerClient + CallOptions **QuotaControllerCallOptions +} + +// NewQuotaControllerRESTClient creates a new quota controller rest client. +// +// Google Quota Control API (at /service-control/overview) +// +// Allows clients to allocate and release quota against a managed +// service (at https://cloud.google.com/service-management/reference/rpc/google.api/servicemanagement.v1#google.api.servicemanagement.v1.ManagedService). +func NewQuotaControllerRESTClient(ctx context.Context, opts ...option.ClientOption) (*QuotaControllerClient, error) { + clientOpts := append(defaultQuotaControllerRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultQuotaControllerRESTCallOptions() + c := "aControllerRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &QuotaControllerClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultQuotaControllerRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://servicecontrol.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://servicecontrol.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://servicecontrol.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *quotaControllerRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *quotaControllerRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *quotaControllerRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *quotaControllerGRPCClient) AllocateQuota(ctx context.Context, req *servicecontrolpb.AllocateQuotaRequest, opts ...gax.CallOption) (*servicecontrolpb.AllocateQuotaResponse, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "service_name", url.QueryEscape(req.GetServiceName()))) @@ -217,3 +300,77 @@ func (c *quotaControllerGRPCClient) AllocateQuota(ctx context.Context, req *serv } return resp, nil } + +// AllocateQuota attempts to allocate quota for the specified consumer. It should be called +// before the operation is executed. +// +// This method requires the servicemanagement.services.quota +// permission on the specified service. For more information, see +// Cloud IAM (at https://cloud.google.com/iam). +// +// NOTE: The client must fail-open on server errors INTERNAL, +// UNKNOWN, DEADLINE_EXCEEDED, and UNAVAILABLE. To ensure system +// reliability, the server may inject these errors to prohibit any hard +// dependency on the quota functionality. +func (c *quotaControllerRESTClient) AllocateQuota(ctx context.Context, req *servicecontrolpb.AllocateQuotaRequest, opts ...gax.CallOption) (*servicecontrolpb.AllocateQuotaResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/services/%v:allocateQuota", req.GetServiceName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "service_name", url.QueryEscape(req.GetServiceName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).AllocateQuota[0:len((*c.CallOptions).AllocateQuota):len((*c.CallOptions).AllocateQuota)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &servicecontrolpb.AllocateQuotaResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} diff --git a/servicecontrol/apiv1/quota_controller_client_example_test.go b/servicecontrol/apiv1/quota_controller_client_example_test.go index 61c44527b9b2..df2bc422a6b9 100644 --- a/servicecontrol/apiv1/quota_controller_client_example_test.go +++ b/servicecontrol/apiv1/quota_controller_client_example_test.go @@ -40,6 +40,23 @@ func ExampleNewQuotaControllerClient() { _ = c } +func ExampleNewQuotaControllerRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := servicecontrol.NewQuotaControllerRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleQuotaControllerClient_AllocateQuota() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/servicecontrol/apiv1/service_controller_client.go b/servicecontrol/apiv1/service_controller_client.go index 26b806ea35b6..a05d5b3bf2c6 100644 --- a/servicecontrol/apiv1/service_controller_client.go +++ b/servicecontrol/apiv1/service_controller_client.go @@ -17,18 +17,24 @@ package servicecontrol import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" servicecontrolpb "cloud.google.com/go/servicecontrol/apiv1/servicecontrolpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" ) var newServiceControllerClientHook clientHook @@ -58,6 +64,13 @@ func defaultServiceControllerCallOptions() *ServiceControllerCallOptions { } } +func defaultServiceControllerRESTCallOptions() *ServiceControllerCallOptions { + return &ServiceControllerCallOptions{ + Check: []gax.CallOption{}, + Report: []gax.CallOption{}, + } +} + // internalServiceControllerClient is an interface that defines the methods available from Service Control API. type internalServiceControllerClient interface { Close() error @@ -229,6 +242,77 @@ func (c *serviceControllerGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type serviceControllerRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing ServiceControllerClient + CallOptions **ServiceControllerCallOptions +} + +// NewServiceControllerRESTClient creates a new service controller rest client. +// +// Google Service Control API (at /service-control/overview) +// +// Lets clients check and report operations against a managed +// service (at https://cloud.google.com/service-management/reference/rpc/google.api/servicemanagement.v1#google.api.servicemanagement.v1.ManagedService). +func NewServiceControllerRESTClient(ctx context.Context, opts ...option.ClientOption) (*ServiceControllerClient, error) { + clientOpts := append(defaultServiceControllerRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultServiceControllerRESTCallOptions() + c := &serviceControllerRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &ServiceControllerClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultServiceControllerRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://servicecontrol.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://servicecontrol.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://servicecontrol.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *serviceControllerRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *serviceControllerRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *serviceControllerRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *serviceControllerGRPCClient) Check(ctx context.Context, req *servicecontrolpb.CheckRequest, opts ...gax.CallOption) (*servicecontrolpb.CheckResponse, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "service_name", url.QueryEscape(req.GetServiceName()))) @@ -262,3 +346,161 @@ func (c *serviceControllerGRPCClient) Report(ctx context.Context, req *serviceco } return resp, nil } + +// Check checks whether an operation on a service should be allowed to proceed +// based on the configuration of the service and related policies. It must be +// called before the operation is executed. +// +// If feasible, the client should cache the check results and reuse them for +// 60 seconds. In case of any server errors, the client should rely on the +// cached results for much longer time to avoid outage. +// WARNING: There is general 60s delay for the configuration and policy +// propagation, therefore callers MUST NOT depend on the Check method having +// the latest policy information. +// +// NOTE: the CheckRequest has +// the size limit (wire-format byte size) of 1MB. +// +// This method requires the servicemanagement.services.check permission +// on the specified service. For more information, see +// Cloud IAM (at https://cloud.google.com/iam). +func (c *serviceControllerRESTClient) Check(ctx context.Context, req *servicecontrolpb.CheckRequest, opts ...gax.CallOption) (*servicecontrolpb.CheckResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/services/%v:check", req.GetServiceName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "service_name", url.QueryEscape(req.GetServiceName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).Check[0:len((*c.CallOptions).Check):len((*c.CallOptions).Check)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &servicecontrolpb.CheckResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// Report reports operation results to Google Service Control, such as logs and +// metrics. It should be called after an operation is completed. +// +// If feasible, the client should aggregate reporting data for up to 5 +// seconds to reduce API traffic. Limiting aggregation to 5 seconds is to +// reduce data loss during client crashes. Clients should carefully choose +// the aggregation time window to avoid data loss risk more than 0.01% +// for business and compliance reasons. +// +// NOTE: the ReportRequest has +// the size limit (wire-format byte size) of 1MB. +// +// This method requires the servicemanagement.services.report permission +// on the specified service. For more information, see +// Google Cloud IAM (at https://cloud.google.com/iam). +func (c *serviceControllerRESTClient) Report(ctx context.Context, req *servicecontrolpb.ReportRequest, opts ...gax.CallOption) (*servicecontrolpb.ReportResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/services/%v:report", req.GetServiceName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "service_name", url.QueryEscape(req.GetServiceName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).Report[0:len((*c.CallOptions).Report):len((*c.CallOptions).Report)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &servicecontrolpb.ReportResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} diff --git a/servicecontrol/apiv1/service_controller_client_example_test.go b/servicecontrol/apiv1/service_controller_client_example_test.go index 33fe7e72aab7..6ff8d85156ec 100644 --- a/servicecontrol/apiv1/service_controller_client_example_test.go +++ b/servicecontrol/apiv1/service_controller_client_example_test.go @@ -40,6 +40,23 @@ func ExampleNewServiceControllerClient() { _ = c } +func ExampleNewServiceControllerRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := servicecontrol.NewServiceControllerRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleServiceControllerClient_Check() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/servicecontrol/apiv1/servicecontrolpb/check_error.pb.go b/servicecontrol/apiv1/servicecontrolpb/check_error.pb.go index 64921c782035..04f4499d0833 100644 --- a/servicecontrol/apiv1/servicecontrolpb/check_error.pb.go +++ b/servicecontrol/apiv1/servicecontrolpb/check_error.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/api/servicecontrol/v1/check_error.proto package servicecontrolpb diff --git a/servicecontrol/apiv1/servicecontrolpb/distribution.pb.go b/servicecontrol/apiv1/servicecontrolpb/distribution.pb.go index 40ecf2396c8d..a3ee2d9d89d0 100644 --- a/servicecontrol/apiv1/servicecontrolpb/distribution.pb.go +++ b/servicecontrol/apiv1/servicecontrolpb/distribution.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/api/servicecontrol/v1/distribution.proto package servicecontrolpb @@ -59,9 +59,7 @@ type Distribution struct { // The maximum of the population of values. Ignored if `count` is zero. Maximum float64 `protobuf:"fixed64,4,opt,name=maximum,proto3" json:"maximum,omitempty"` // The sum of squared deviations from the mean: - // - // Sum[i=1..count]((x_i - mean)^2) - // + // Sum[i=1..count]((x_i - mean)^2) // where each x_i is a sample values. If `count` is zero then this field // must be zero, otherwise validation of the request fails. SumOfSquaredDeviation float64 `protobuf:"fixed64,5,opt,name=sum_of_squared_deviation,json=sumOfSquaredDeviation,proto3" json:"sum_of_squared_deviation,omitempty"` @@ -90,9 +88,9 @@ type Distribution struct { // buckets because they have finite lower and upper bounds. As described // below, there are three ways to define the finite buckets. // - // (1) Buckets with constant width. - // (2) Buckets with exponentially growing widths. - // (3) Buckets with arbitrary user-provided widths. + // (1) Buckets with constant width. + // (2) Buckets with exponentially growing widths. + // (3) Buckets with arbitrary user-provided widths. // // In all cases, the buckets cover the entire real number line (-inf, // +inf). Bucket upper bounds are exclusive and lower bounds are @@ -102,7 +100,6 @@ type Distribution struct { // bucket. // // Types that are assignable to BucketOption: - // // *Distribution_LinearBuckets_ // *Distribution_ExponentialBuckets_ // *Distribution_ExplicitBuckets_ @@ -256,16 +253,12 @@ type Distribution_LinearBuckets struct { // See comments on `bucket_options` for details. NumFiniteBuckets int32 `protobuf:"varint,1,opt,name=num_finite_buckets,json=numFiniteBuckets,proto3" json:"num_finite_buckets,omitempty"` // The i'th linear bucket covers the interval - // - // [offset + (i-1) * width, offset + i * width) - // + // [offset + (i-1) * width, offset + i * width) // where i ranges from 1 to num_finite_buckets, inclusive. // Must be strictly positive. Width float64 `protobuf:"fixed64,2,opt,name=width,proto3" json:"width,omitempty"` // The i'th linear bucket covers the interval - // - // [offset + (i-1) * width, offset + i * width) - // + // [offset + (i-1) * width, offset + i * width) // where i ranges from 1 to num_finite_buckets, inclusive. Offset float64 `protobuf:"fixed64,3,opt,name=offset,proto3" json:"offset,omitempty"` } @@ -334,16 +327,12 @@ type Distribution_ExponentialBuckets struct { // See comments on `bucket_options` for details. NumFiniteBuckets int32 `protobuf:"varint,1,opt,name=num_finite_buckets,json=numFiniteBuckets,proto3" json:"num_finite_buckets,omitempty"` // The i'th exponential bucket covers the interval - // - // [scale * growth_factor^(i-1), scale * growth_factor^i) - // + // [scale * growth_factor^(i-1), scale * growth_factor^i) // where i ranges from 1 to num_finite_buckets inclusive. // Must be larger than 1.0. GrowthFactor float64 `protobuf:"fixed64,2,opt,name=growth_factor,json=growthFactor,proto3" json:"growth_factor,omitempty"` // The i'th exponential bucket covers the interval - // - // [scale * growth_factor^(i-1), scale * growth_factor^i) - // + // [scale * growth_factor^(i-1), scale * growth_factor^i) // where i ranges from 1 to num_finite_buckets inclusive. // Must be > 0. Scale float64 `protobuf:"fixed64,3,opt,name=scale,proto3" json:"scale,omitempty"` @@ -413,19 +402,16 @@ type Distribution_ExplicitBuckets struct { // of fenceposting. See comments on `bucket_options` for details. // // The i'th finite bucket covers the interval - // - // [bound[i-1], bound[i]) - // + // [bound[i-1], bound[i]) // where i ranges from 1 to bound_size() - 1. Note that there are no // finite buckets at all if 'bound' only contains a single element; in // that special case the single bound defines the boundary between the // underflow and overflow buckets. // // bucket number lower bound upper bound - // - // i == 0 (underflow) -inf bound[i] - // 0 < i < bound_size() bound[i-1] bound[i] - // i == bound_size() (overflow) bound[i-1] +inf + // i == 0 (underflow) -inf bound[i] + // 0 < i < bound_size() bound[i-1] bound[i] + // i == bound_size() (overflow) bound[i-1] +inf Bounds []float64 `protobuf:"fixed64,1,rep,packed,name=bounds,proto3" json:"bounds,omitempty"` } diff --git a/servicecontrol/apiv1/servicecontrolpb/http_request.pb.go b/servicecontrol/apiv1/servicecontrolpb/http_request.pb.go index e5c48870cc90..fd272f934379 100644 --- a/servicecontrol/apiv1/servicecontrolpb/http_request.pb.go +++ b/servicecontrol/apiv1/servicecontrolpb/http_request.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/api/servicecontrol/v1/http_request.proto package servicecontrolpb diff --git a/servicecontrol/apiv1/servicecontrolpb/log_entry.pb.go b/servicecontrol/apiv1/servicecontrolpb/log_entry.pb.go index cff6883a69e8..634a410617f1 100644 --- a/servicecontrol/apiv1/servicecontrolpb/log_entry.pb.go +++ b/servicecontrol/apiv1/servicecontrolpb/log_entry.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/api/servicecontrol/v1/log_entry.proto package servicecontrolpb @@ -71,7 +71,6 @@ type LogEntry struct { // The log entry payload, which can be one of multiple types. // // Types that are assignable to Payload: - // // *LogEntry_ProtoPayload // *LogEntry_TextPayload // *LogEntry_StructPayload @@ -134,7 +133,7 @@ func (x *LogEntry) GetSeverity() _type.LogSeverity { if x != nil { return x.Severity } - return _type.LogSeverity_DEFAULT + return _type.LogSeverity(0) } func (x *LogEntry) GetHttpRequest() *HttpRequest { diff --git a/servicecontrol/apiv1/servicecontrolpb/metric_value.pb.go b/servicecontrol/apiv1/servicecontrolpb/metric_value.pb.go index f66a8349e1f7..e7bf01929303 100644 --- a/servicecontrol/apiv1/servicecontrolpb/metric_value.pb.go +++ b/servicecontrol/apiv1/servicecontrolpb/metric_value.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/api/servicecontrol/v1/metric_value.proto package servicecontrolpb @@ -62,7 +62,6 @@ type MetricValue struct { // the MetricValue is rejected. // // Types that are assignable to Value: - // // *MetricValue_BoolValue // *MetricValue_Int64Value // *MetricValue_DoubleValue diff --git a/servicecontrol/apiv1/servicecontrolpb/operation.pb.go b/servicecontrol/apiv1/servicecontrolpb/operation.pb.go index 77a36e525ee1..44593f31cb8c 100644 --- a/servicecontrol/apiv1/servicecontrolpb/operation.pb.go +++ b/servicecontrol/apiv1/servicecontrolpb/operation.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/api/servicecontrol/v1/operation.proto package servicecontrolpb @@ -113,12 +113,12 @@ type Operation struct { // not related to a specific consumer. // // - This can be in one of the following formats: - // - project:PROJECT_ID, - // - project`_`number:PROJECT_NUMBER, - // - projects/PROJECT_ID or PROJECT_NUMBER, - // - folders/FOLDER_NUMBER, - // - organizations/ORGANIZATION_NUMBER, - // - api`_`key:API_KEY. + // - project:PROJECT_ID, + // - project`_`number:PROJECT_NUMBER, + // - projects/PROJECT_ID or PROJECT_NUMBER, + // - folders/FOLDER_NUMBER, + // - organizations/ORGANIZATION_NUMBER, + // - api`_`key:API_KEY. ConsumerId string `protobuf:"bytes,3,opt,name=consumer_id,json=consumerId,proto3" json:"consumer_id,omitempty"` // Required. Start time of the operation. StartTime *timestamppb.Timestamp `protobuf:"bytes,4,opt,name=start_time,json=startTime,proto3" json:"start_time,omitempty"` @@ -130,20 +130,20 @@ type Operation struct { EndTime *timestamppb.Timestamp `protobuf:"bytes,5,opt,name=end_time,json=endTime,proto3" json:"end_time,omitempty"` // Labels describing the operation. Only the following labels are allowed: // - // - Labels describing monitored resources as defined in - // the service configuration. - // - Default labels of metric values. When specified, labels defined in the - // metric value override these default. - // - The following labels defined by Google Cloud Platform: - // - `cloud.googleapis.com/location` describing the location where the - // operation happened, - // - `servicecontrol.googleapis.com/user_agent` describing the user agent - // of the API request, - // - `servicecontrol.googleapis.com/service_agent` describing the service - // used to handle the API request (e.g. ESP), - // - `servicecontrol.googleapis.com/platform` describing the platform - // where the API is served, such as App Engine, Compute Engine, or - // Kubernetes Engine. + // - Labels describing monitored resources as defined in + // the service configuration. + // - Default labels of metric values. When specified, labels defined in the + // metric value override these default. + // - The following labels defined by Google Cloud Platform: + // - `cloud.googleapis.com/location` describing the location where the + // operation happened, + // - `servicecontrol.googleapis.com/user_agent` describing the user agent + // of the API request, + // - `servicecontrol.googleapis.com/service_agent` describing the service + // used to handle the API request (e.g. ESP), + // - `servicecontrol.googleapis.com/platform` describing the platform + // where the API is served, such as App Engine, Compute Engine, or + // Kubernetes Engine. Labels map[string]string `protobuf:"bytes,6,rep,name=labels,proto3" json:"labels,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` // Represents information about this operation. Each MetricValueSet // corresponds to a metric defined in the service configuration. diff --git a/servicecontrol/apiv1/servicecontrolpb/quota_controller.pb.go b/servicecontrol/apiv1/servicecontrolpb/quota_controller.pb.go index 2886c6583bd9..6d025618e50f 100644 --- a/servicecontrol/apiv1/servicecontrolpb/quota_controller.pb.go +++ b/servicecontrol/apiv1/servicecontrolpb/quota_controller.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/api/servicecontrol/v1/quota_controller.proto package servicecontrolpb @@ -295,17 +295,16 @@ type QuotaOperation struct { // (1) the quota operation is performed on non-API resources. // (2) quota_metrics is set because the caller is doing quota override. // - // Example of an RPC method name: // - // google.example.library.v1.LibraryService.CreateShelf + // Example of an RPC method name: + // google.example.library.v1.LibraryService.CreateShelf MethodName string `protobuf:"bytes,2,opt,name=method_name,json=methodName,proto3" json:"method_name,omitempty"` // Identity of the consumer for whom this quota operation is being performed. // // This can be in one of the following formats: - // - // project:, - // project_number:, - // api_key:. + // project:, + // project_number:, + // api_key:. ConsumerId string `protobuf:"bytes,3,opt,name=consumer_id,json=consumerId,proto3" json:"consumer_id,omitempty"` // Labels describing the operation. Labels map[string]string `protobuf:"bytes,4,rep,name=labels,proto3" json:"labels,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` @@ -416,13 +415,11 @@ type AllocateQuotaResponse struct { // // 1. Per quota group or per quota metric incremental usage will be specified // using the following delta metric : - // - // "serviceruntime.googleapis.com/api/consumer/quota_used_count" + // "serviceruntime.googleapis.com/api/consumer/quota_used_count" // // 2. The quota limit reached condition will be specified using the following // boolean metric : - // - // "serviceruntime.googleapis.com/quota/exceeded" + // "serviceruntime.googleapis.com/quota/exceeded" QuotaMetrics []*MetricValueSet `protobuf:"bytes,3,rep,name=quota_metrics,json=quotaMetrics,proto3" json:"quota_metrics,omitempty"` // ID of the actual config used to process the request. ServiceConfigId string `protobuf:"bytes,4,opt,name=service_config_id,json=serviceConfigId,proto3" json:"service_config_id,omitempty"` diff --git a/servicecontrol/apiv1/servicecontrolpb/service_controller.pb.go b/servicecontrol/apiv1/servicecontrolpb/service_controller.pb.go index 622e2b863f99..304602e051a5 100644 --- a/servicecontrol/apiv1/servicecontrolpb/service_controller.pb.go +++ b/servicecontrol/apiv1/servicecontrolpb/service_controller.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/api/servicecontrol/v1/service_controller.proto package servicecontrolpb @@ -367,17 +367,17 @@ type ReportResponse struct { // Partial failures, one for each `Operation` in the request that failed // processing. There are three possible combinations of the RPC status: // - // 1. The combination of a successful RPC status and an empty `report_errors` - // list indicates a complete success where all `Operations` in the - // request are processed successfully. - // 2. The combination of a successful RPC status and a non-empty - // `report_errors` list indicates a partial success where some - // `Operations` in the request succeeded. Each - // `Operation` that failed processing has a corresponding item - // in this list. - // 3. A failed RPC status indicates a general non-deterministic failure. - // When this happens, it's impossible to know which of the - // 'Operations' in the request succeeded or failed. + // 1. The combination of a successful RPC status and an empty `report_errors` + // list indicates a complete success where all `Operations` in the + // request are processed successfully. + // 2. The combination of a successful RPC status and a non-empty + // `report_errors` list indicates a partial success where some + // `Operations` in the request succeeded. Each + // `Operation` that failed processing has a corresponding item + // in this list. + // 3. A failed RPC status indicates a general non-deterministic failure. + // When this happens, it's impossible to know which of the + // 'Operations' in the request succeeded or failed. ReportErrors []*ReportResponse_ReportError `protobuf:"bytes,1,rep,name=report_errors,json=reportErrors,proto3" json:"report_errors,omitempty"` // The actual config id used to process the request. ServiceConfigId string `protobuf:"bytes,2,opt,name=service_config_id,json=serviceConfigId,proto3" json:"service_config_id,omitempty"` diff --git a/servicedirectory/apiv1/doc.go b/servicedirectory/apiv1/doc.go index 1581ec992c79..f7c5f853d117 100644 --- a/servicedirectory/apiv1/doc.go +++ b/servicedirectory/apiv1/doc.go @@ -81,6 +81,8 @@ package servicedirectory // import "cloud.google.com/go/servicedirectory/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -169,3 +171,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/servicedirectory/apiv1/gapic_metadata.json b/servicedirectory/apiv1/gapic_metadata.json index 0cfd6fd3345d..3cfb9a4cc8b5 100644 --- a/servicedirectory/apiv1/gapic_metadata.json +++ b/servicedirectory/apiv1/gapic_metadata.json @@ -16,6 +16,16 @@ ] } } + }, + "rest": { + "libraryClient": "LookupClient", + "rpcs": { + "ResolveService": { + "methods": [ + "ResolveService" + ] + } + } } } }, @@ -115,6 +125,101 @@ ] } } + }, + "rest": { + "libraryClient": "RegistrationClient", + "rpcs": { + "CreateEndpoint": { + "methods": [ + "CreateEndpoint" + ] + }, + "CreateNamespace": { + "methods": [ + "CreateNamespace" + ] + }, + "CreateService": { + "methods": [ + "CreateService" + ] + }, + "DeleteEndpoint": { + "methods": [ + "DeleteEndpoint" + ] + }, + "DeleteNamespace": { + "methods": [ + "DeleteNamespace" + ] + }, + "DeleteService": { + "methods": [ + "DeleteService" + ] + }, + "GetEndpoint": { + "methods": [ + "GetEndpoint" + ] + }, + "GetIamPolicy": { + "methods": [ + "GetIamPolicy" + ] + }, + "GetNamespace": { + "methods": [ + "GetNamespace" + ] + }, + "GetService": { + "methods": [ + "GetService" + ] + }, + "ListEndpoints": { + "methods": [ + "ListEndpoints" + ] + }, + "ListNamespaces": { + "methods": [ + "ListNamespaces" + ] + }, + "ListServices": { + "methods": [ + "ListServices" + ] + }, + "SetIamPolicy": { + "methods": [ + "SetIamPolicy" + ] + }, + "TestIamPermissions": { + "methods": [ + "TestIamPermissions" + ] + }, + "UpdateEndpoint": { + "methods": [ + "UpdateEndpoint" + ] + }, + "UpdateNamespace": { + "methods": [ + "UpdateNamespace" + ] + }, + "UpdateService": { + "methods": [ + "UpdateService" + ] + } + } } } } diff --git a/servicedirectory/apiv1/lookup_client.go b/servicedirectory/apiv1/lookup_client.go index 36802a4ff966..322bf7e0f10f 100644 --- a/servicedirectory/apiv1/lookup_client.go +++ b/servicedirectory/apiv1/lookup_client.go @@ -17,20 +17,26 @@ package servicedirectory import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" servicedirectorypb "cloud.google.com/go/servicedirectory/apiv1/servicedirectorypb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" ) var newLookupClientHook clientHook @@ -69,6 +75,22 @@ func defaultLookupCallOptions() *LookupCallOptions { } } +func defaultLookupRESTCallOptions() *LookupCallOptions { + return &LookupCallOptions{ + ResolveService: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusInternalServerError) + }), + }, + } +} + // internalLookupClient is an interface that defines the methods available from Service Directory API. type internalLookupClient interface { Close() error @@ -200,6 +222,74 @@ func (c *lookupGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type lookupRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing LookupClient + CallOptions **LookupCallOptions +} + +// NewLookupRESTClient creates a new lookup service rest client. +// +// Service Directory API for looking up service data at runtime. +func NewLookupRESTClient(ctx context.Context, opts ...option.ClientOption) (*LookupClient, error) { + clientOpts := append(defaultLookupRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultLookupRESTCallOptions() + c := &lookupRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &LookupClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultLookupRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://servicedirectory.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://servicedirectory.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://servicedirectory.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *lookupRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *lookupRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *lookupRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *lookupGRPCClient) ResolveService(ctx context.Context, req *servicedirectorypb.ResolveServiceRequest, opts ...gax.CallOption) (*servicedirectorypb.ResolveServiceResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 15000*time.Millisecond) @@ -221,3 +311,69 @@ func (c *lookupGRPCClient) ResolveService(ctx context.Context, req *servicedirec } return resp, nil } + +// ResolveService returns a service and its +// associated endpoints. +// Resolving a service is not considered an active developer method. +func (c *lookupRESTClient) ResolveService(ctx context.Context, req *servicedirectorypb.ResolveServiceRequest, opts ...gax.CallOption) (*servicedirectorypb.ResolveServiceResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:resolve", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).ResolveService[0:len((*c.CallOptions).ResolveService):len((*c.CallOptions).ResolveService)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &servicedirectorypb.ResolveServiceResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} diff --git a/servicedirectory/apiv1/lookup_client_example_test.go b/servicedirectory/apiv1/lookup_client_example_test.go index d33ac680c40d..9e03215cedf5 100644 --- a/servicedirectory/apiv1/lookup_client_example_test.go +++ b/servicedirectory/apiv1/lookup_client_example_test.go @@ -40,6 +40,23 @@ func ExampleNewLookupClient() { _ = c } +func ExampleNewLookupRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := servicedirectory.NewLookupRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleLookupClient_ResolveService() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/servicedirectory/apiv1/registration_client.go b/servicedirectory/apiv1/registration_client.go index 82d00de1ae60..9e1483eb25e9 100644 --- a/servicedirectory/apiv1/registration_client.go +++ b/servicedirectory/apiv1/registration_client.go @@ -17,22 +17,28 @@ package servicedirectory import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" servicedirectorypb "cloud.google.com/go/servicedirectory/apiv1/servicedirectorypb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" iampb "google.golang.org/genproto/googleapis/iam/v1" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -293,6 +299,209 @@ func defaultRegistrationCallOptions() *RegistrationCallOptions { } } +func defaultRegistrationRESTCallOptions() *RegistrationCallOptions { + return &RegistrationCallOptions{ + CreateNamespace: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusInternalServerError) + }), + }, + ListNamespaces: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusInternalServerError) + }), + }, + GetNamespace: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusInternalServerError) + }), + }, + UpdateNamespace: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusInternalServerError) + }), + }, + DeleteNamespace: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusInternalServerError) + }), + }, + CreateService: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusInternalServerError) + }), + }, + ListServices: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusInternalServerError) + }), + }, + GetService: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusInternalServerError) + }), + }, + UpdateService: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusInternalServerError) + }), + }, + DeleteService: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusInternalServerError) + }), + }, + CreateEndpoint: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusInternalServerError) + }), + }, + ListEndpoints: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusInternalServerError) + }), + }, + GetEndpoint: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusInternalServerError) + }), + }, + UpdateEndpoint: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusInternalServerError) + }), + }, + DeleteEndpoint: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusInternalServerError) + }), + }, + GetIamPolicy: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusInternalServerError) + }), + }, + SetIamPolicy: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusInternalServerError) + }), + }, + TestIamPermissions: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusInternalServerError) + }), + }, + } +} + // internalRegistrationClient is an interface that defines the methods available from Service Directory API. type internalRegistrationClient interface { Close() error @@ -554,6 +763,88 @@ func (c *registrationGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type registrationRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing RegistrationClient + CallOptions **RegistrationCallOptions +} + +// NewRegistrationRESTClient creates a new registration service rest client. +// +// Service Directory API for registering services. It defines the following +// resource model: +// +// The API has a collection of +// Namespace +// resources, named projects/*/locations/*/namespaces/*. +// +// Each Namespace has a collection of +// Service resources, named +// projects/*/locations/*/namespaces/*/services/*. +// +// Each Service has a collection of +// Endpoint +// resources, named +// projects/*/locations/*/namespaces/*/services/*/endpoints/*. +func NewRegistrationRESTClient(ctx context.Context, opts ...option.ClientOption) (*RegistrationClient, error) { + clientOpts := append(defaultRegistrationRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRegistrationRESTCallOptions() + c := ®istrationRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &RegistrationClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRegistrationRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://servicedirectory.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://servicedirectory.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://servicedirectory.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *registrationRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *registrationRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *registrationRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *registrationGRPCClient) CreateNamespace(ctx context.Context, req *servicedirectorypb.CreateNamespaceRequest, opts ...gax.CallOption) (*servicedirectorypb.Namespace, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 15000*time.Millisecond) @@ -1007,6 +1298,1190 @@ func (c *registrationGRPCClient) TestIamPermissions(ctx context.Context, req *ia return resp, nil } +// CreateNamespace creates a namespace, and returns the new Namespace. +func (c *registrationRESTClient) CreateNamespace(ctx context.Context, req *servicedirectorypb.CreateNamespaceRequest, opts ...gax.CallOption) (*servicedirectorypb.Namespace, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetNamespace() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/namespaces", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("namespaceId", fmt.Sprintf("%v", req.GetNamespaceId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateNamespace[0:len((*c.CallOptions).CreateNamespace):len((*c.CallOptions).CreateNamespace)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &servicedirectorypb.Namespace{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListNamespaces lists all namespaces. +func (c *registrationRESTClient) ListNamespaces(ctx context.Context, req *servicedirectorypb.ListNamespacesRequest, opts ...gax.CallOption) *NamespaceIterator { + it := &NamespaceIterator{} + req = proto.Clone(req).(*servicedirectorypb.ListNamespacesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*servicedirectorypb.Namespace, string, error) { + resp := &servicedirectorypb.ListNamespacesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/namespaces", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetNamespaces(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetNamespace gets a namespace. +func (c *registrationRESTClient) GetNamespace(ctx context.Context, req *servicedirectorypb.GetNamespaceRequest, opts ...gax.CallOption) (*servicedirectorypb.Namespace, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetNamespace[0:len((*c.CallOptions).GetNamespace):len((*c.CallOptions).GetNamespace)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &servicedirectorypb.Namespace{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateNamespace updates a namespace. +func (c *registrationRESTClient) UpdateNamespace(ctx context.Context, req *servicedirectorypb.UpdateNamespaceRequest, opts ...gax.CallOption) (*servicedirectorypb.Namespace, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetNamespace() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetNamespace().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "namespace.name", url.QueryEscape(req.GetNamespace().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateNamespace[0:len((*c.CallOptions).UpdateNamespace):len((*c.CallOptions).UpdateNamespace)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &servicedirectorypb.Namespace{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteNamespace deletes a namespace. This also deletes all services and endpoints in +// the namespace. +func (c *registrationRESTClient) DeleteNamespace(ctx context.Context, req *servicedirectorypb.DeleteNamespaceRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// CreateService creates a service, and returns the new Service. +func (c *registrationRESTClient) CreateService(ctx context.Context, req *servicedirectorypb.CreateServiceRequest, opts ...gax.CallOption) (*servicedirectorypb.Service, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetService() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/services", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("serviceId", fmt.Sprintf("%v", req.GetServiceId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateService[0:len((*c.CallOptions).CreateService):len((*c.CallOptions).CreateService)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &servicedirectorypb.Service{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListServices lists all services belonging to a namespace. +func (c *registrationRESTClient) ListServices(ctx context.Context, req *servicedirectorypb.ListServicesRequest, opts ...gax.CallOption) *ServiceIterator { + it := &ServiceIterator{} + req = proto.Clone(req).(*servicedirectorypb.ListServicesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*servicedirectorypb.Service, string, error) { + resp := &servicedirectorypb.ListServicesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/services", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetServices(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetService gets a service. +func (c *registrationRESTClient) GetService(ctx context.Context, req *servicedirectorypb.GetServiceRequest, opts ...gax.CallOption) (*servicedirectorypb.Service, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetService[0:len((*c.CallOptions).GetService):len((*c.CallOptions).GetService)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &servicedirectorypb.Service{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateService updates a service. +func (c *registrationRESTClient) UpdateService(ctx context.Context, req *servicedirectorypb.UpdateServiceRequest, opts ...gax.CallOption) (*servicedirectorypb.Service, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetService() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetService().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "service.name", url.QueryEscape(req.GetService().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateService[0:len((*c.CallOptions).UpdateService):len((*c.CallOptions).UpdateService)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &servicedirectorypb.Service{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteService deletes a service. This also deletes all endpoints associated with +// the service. +func (c *registrationRESTClient) DeleteService(ctx context.Context, req *servicedirectorypb.DeleteServiceRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// CreateEndpoint creates a endpoint, and returns the new Endpoint. +func (c *registrationRESTClient) CreateEndpoint(ctx context.Context, req *servicedirectorypb.CreateEndpointRequest, opts ...gax.CallOption) (*servicedirectorypb.Endpoint, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetEndpoint() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/endpoints", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("endpointId", fmt.Sprintf("%v", req.GetEndpointId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateEndpoint[0:len((*c.CallOptions).CreateEndpoint):len((*c.CallOptions).CreateEndpoint)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &servicedirectorypb.Endpoint{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListEndpoints lists all endpoints. +func (c *registrationRESTClient) ListEndpoints(ctx context.Context, req *servicedirectorypb.ListEndpointsRequest, opts ...gax.CallOption) *EndpointIterator { + it := &EndpointIterator{} + req = proto.Clone(req).(*servicedirectorypb.ListEndpointsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*servicedirectorypb.Endpoint, string, error) { + resp := &servicedirectorypb.ListEndpointsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/endpoints", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetEndpoints(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetEndpoint gets a endpoint. +func (c *registrationRESTClient) GetEndpoint(ctx context.Context, req *servicedirectorypb.GetEndpointRequest, opts ...gax.CallOption) (*servicedirectorypb.Endpoint, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetEndpoint[0:len((*c.CallOptions).GetEndpoint):len((*c.CallOptions).GetEndpoint)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &servicedirectorypb.Endpoint{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateEndpoint updates a endpoint. +func (c *registrationRESTClient) UpdateEndpoint(ctx context.Context, req *servicedirectorypb.UpdateEndpointRequest, opts ...gax.CallOption) (*servicedirectorypb.Endpoint, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetEndpoint() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetEndpoint().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "endpoint.name", url.QueryEscape(req.GetEndpoint().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateEndpoint[0:len((*c.CallOptions).UpdateEndpoint):len((*c.CallOptions).UpdateEndpoint)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &servicedirectorypb.Endpoint{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteEndpoint deletes a endpoint. +func (c *registrationRESTClient) DeleteEndpoint(ctx context.Context, req *servicedirectorypb.DeleteEndpointRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetIamPolicy gets the IAM Policy for a resource (namespace or service only). +func (c *registrationRESTClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:getIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SetIamPolicy sets the IAM Policy for a resource (namespace or service only). +func (c *registrationRESTClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:setIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// TestIamPermissions tests IAM permissions for a resource (namespace or service only). +func (c *registrationRESTClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:testIamPermissions", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.TestIamPermissionsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + // EndpointIterator manages a stream of *servicedirectorypb.Endpoint. type EndpointIterator struct { items []*servicedirectorypb.Endpoint diff --git a/servicedirectory/apiv1/registration_client_example_test.go b/servicedirectory/apiv1/registration_client_example_test.go index 414282903972..4602c2c81081 100644 --- a/servicedirectory/apiv1/registration_client_example_test.go +++ b/servicedirectory/apiv1/registration_client_example_test.go @@ -42,6 +42,23 @@ func ExampleNewRegistrationClient() { _ = c } +func ExampleNewRegistrationRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := servicedirectory.NewRegistrationRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleRegistrationClient_CreateNamespace() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/servicedirectory/apiv1/servicedirectorypb/endpoint.pb.go b/servicedirectory/apiv1/servicedirectorypb/endpoint.pb.go index 46bc12f534e0..db0c26f52387 100644 --- a/servicedirectory/apiv1/servicedirectorypb/endpoint.pb.go +++ b/servicedirectory/apiv1/servicedirectorypb/endpoint.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/servicedirectory/v1/endpoint.proto package servicedirectorypb @@ -49,35 +49,32 @@ type Endpoint struct { Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Optional. An IPv4 or IPv6 address. Service Directory will reject bad // addresses like: - // - // "8.8.8" - // "8.8.8.8:53" - // "test:bad:address" - // "[::1]" - // "[::1]:8080" - // + // "8.8.8" + // "8.8.8.8:53" + // "test:bad:address" + // "[::1]" + // "[::1]:8080" // Limited to 45 characters. Address string `protobuf:"bytes,2,opt,name=address,proto3" json:"address,omitempty"` // Optional. Service Directory will reject values outside of [0, 65535]. Port int32 `protobuf:"varint,3,opt,name=port,proto3" json:"port,omitempty"` // Optional. Annotations for the endpoint. This data can be consumed by // service clients. Restrictions: - // - The entire annotations dictionary may contain up to 512 characters, - // spread accoss all key-value pairs. Annotations that goes beyond any - // these limits will be rejected. - // - Valid annotation keys have two segments: an optional prefix and name, - // separated by a slash (/). The name segment is required and must be 63 - // characters or less, beginning and ending with an alphanumeric character - // ([a-z0-9A-Z]) with dashes (-), underscores (_), dots (.), and - // alphanumerics between. The prefix is optional. If specified, the prefix - // must be a DNS subdomain: a series of DNS labels separated by dots (.), - // not longer than 253 characters in total, followed by a slash (/). - // Annotations that fails to meet these requirements will be rejected. - // - The '(*.)google.com/' and '(*.)googleapis.com/' prefixes are reserved - // for system annotations managed by Service Directory. If the user tries - // to write to these keyspaces, those entries will be silently ignored by - // the system. - // + // - The entire annotations dictionary may contain up to 512 characters, + // spread accoss all key-value pairs. Annotations that goes beyond any + // these limits will be rejected. + // - Valid annotation keys have two segments: an optional prefix and name, + // separated by a slash (/). The name segment is required and must be 63 + // characters or less, beginning and ending with an alphanumeric character + // ([a-z0-9A-Z]) with dashes (-), underscores (_), dots (.), and + // alphanumerics between. The prefix is optional. If specified, the prefix + // must be a DNS subdomain: a series of DNS labels separated by dots (.), + // not longer than 253 characters in total, followed by a slash (/). + // Annotations that fails to meet these requirements will be rejected. + // - The '(*.)google.com/' and '(*.)googleapis.com/' prefixes are reserved + // for system annotations managed by Service Directory. If the user tries + // to write to these keyspaces, those entries will be silently ignored by + // the system. // Note: This field is equivalent to the 'metadata' field in the v1beta1 API. // They have the same syntax and read/write to the same location in Service // Directory. diff --git a/servicedirectory/apiv1/servicedirectorypb/lookup_service.pb.go b/servicedirectory/apiv1/servicedirectorypb/lookup_service.pb.go index 47bb20a5dcae..5940300ace96 100644 --- a/servicedirectory/apiv1/servicedirectorypb/lookup_service.pb.go +++ b/servicedirectory/apiv1/servicedirectorypb/lookup_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/servicedirectory/v1/lookup_service.proto package servicedirectorypb @@ -65,13 +65,13 @@ type ResolveServiceRequest struct { // can be "AND, OR, NOT". // // Examples of valid filters: - // - "metadata.owner" returns Endpoints that have a label with the - // key "owner", this is the same as "metadata:owner" - // - "metadata.protocol=gRPC" returns Endpoints that have key/value - // "protocol=gRPC" - // - "metadata.owner!=sd AND metadata.foo=bar" returns - // Endpoints that have "owner" field in metadata with a value that is not - // "sd" AND have the key/value foo=bar. + // * "metadata.owner" returns Endpoints that have a label with the + // key "owner", this is the same as "metadata:owner" + // * "metadata.protocol=gRPC" returns Endpoints that have key/value + // "protocol=gRPC" + // * "metadata.owner!=sd AND metadata.foo=bar" returns + // Endpoints that have "owner" field in metadata with a value that is not + // "sd" AND have the key/value foo=bar. EndpointFilter string `protobuf:"bytes,3,opt,name=endpoint_filter,json=endpointFilter,proto3" json:"endpoint_filter,omitempty"` } diff --git a/servicedirectory/apiv1/servicedirectorypb/namespace.pb.go b/servicedirectory/apiv1/servicedirectorypb/namespace.pb.go index e2a50db341d3..0690d229b773 100644 --- a/servicedirectory/apiv1/servicedirectorypb/namespace.pb.go +++ b/servicedirectory/apiv1/servicedirectorypb/namespace.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/servicedirectory/v1/namespace.proto package servicedirectorypb diff --git a/servicedirectory/apiv1/servicedirectorypb/registration_service.pb.go b/servicedirectory/apiv1/servicedirectorypb/registration_service.pb.go index e5f9bb2cfb6e..2e7e8d25941a 100644 --- a/servicedirectory/apiv1/servicedirectorypb/registration_service.pb.go +++ b/servicedirectory/apiv1/servicedirectorypb/registration_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/servicedirectory/v1/registration_service.proto package servicedirectorypb @@ -144,18 +144,18 @@ type ListNamespacesRequest struct { // can be "AND, OR, NOT". // // Examples of valid filters: - // - "labels.owner" returns Namespaces that have a label with the key "owner" - // this is the same as "labels:owner". - // - "labels.protocol=gRPC" returns Namespaces that have key/value - // "protocol=gRPC". - // - "name>projects/my-project/locations/us-east/namespaces/namespace-c" - // returns Namespaces that have name that is alphabetically later than the - // string, so "namespace-e" will be returned but "namespace-a" will not be. - // - "labels.owner!=sd AND labels.foo=bar" returns Namespaces that have - // "owner" in label key but value is not "sd" AND have key/value foo=bar. - // - "doesnotexist.foo=bar" returns an empty list. Note that Namespace doesn't - // have a field called "doesnotexist". Since the filter does not match any - // Namespaces, it returns no results. + // * "labels.owner" returns Namespaces that have a label with the key "owner" + // this is the same as "labels:owner". + // * "labels.protocol=gRPC" returns Namespaces that have key/value + // "protocol=gRPC". + // * "name>projects/my-project/locations/us-east/namespaces/namespace-c" + // returns Namespaces that have name that is alphabetically later than the + // string, so "namespace-e" will be returned but "namespace-a" will not be. + // * "labels.owner!=sd AND labels.foo=bar" returns Namespaces that have + // "owner" in label key but value is not "sd" AND have key/value foo=bar. + // * "doesnotexist.foo=bar" returns an empty list. Note that Namespace doesn't + // have a field called "doesnotexist". Since the filter does not match any + // Namespaces, it returns no results. Filter string `protobuf:"bytes,4,opt,name=filter,proto3" json:"filter,omitempty"` // Optional. The order to list result by. // @@ -555,18 +555,18 @@ type ListServicesRequest struct { // can be "AND, OR, NOT". // // Examples of valid filters: - // - "metadata.owner" returns Services that have a label with the key "owner" - // this is the same as "metadata:owner". - // - "metadata.protocol=gRPC" returns Services that have key/value - // "protocol=gRPC". - // - "name>projects/my-project/locations/us-east/namespaces/my-namespace/services/service-c" - // returns Services that have name that is alphabetically later than the - // string, so "service-e" will be returned but "service-a" will not be. - // - "metadata.owner!=sd AND metadata.foo=bar" returns Services that have - // "owner" in label key but value is not "sd" AND have key/value foo=bar. - // - "doesnotexist.foo=bar" returns an empty list. Note that Service doesn't - // have a field called "doesnotexist". Since the filter does not match any - // Services, it returns no results. + // * "metadata.owner" returns Services that have a label with the key "owner" + // this is the same as "metadata:owner". + // * "metadata.protocol=gRPC" returns Services that have key/value + // "protocol=gRPC". + // * "name>projects/my-project/locations/us-east/namespaces/my-namespace/services/service-c" + // returns Services that have name that is alphabetically later than the + // string, so "service-e" will be returned but "service-a" will not be. + // * "metadata.owner!=sd AND metadata.foo=bar" returns Services that have + // "owner" in label key but value is not "sd" AND have key/value foo=bar. + // * "doesnotexist.foo=bar" returns an empty list. Note that Service doesn't + // have a field called "doesnotexist". Since the filter does not match any + // Services, it returns no results. Filter string `protobuf:"bytes,4,opt,name=filter,proto3" json:"filter,omitempty"` // Optional. The order to list result by. OrderBy string `protobuf:"bytes,5,opt,name=order_by,json=orderBy,proto3" json:"order_by,omitempty"` @@ -960,20 +960,20 @@ type ListEndpointsRequest struct { // can be "AND, OR, NOT". // // Examples of valid filters: - // - "metadata.owner" returns Endpoints that have a label with the key "owner" - // this is the same as "metadata:owner". - // - "metadata.protocol=gRPC" returns Endpoints that have key/value - // "protocol=gRPC". - // - "address=192.108.1.105" returns Endpoints that have this address. - // - "port>8080" returns Endpoints that have port number larger than 8080. - // - "name>projects/my-project/locations/us-east/namespaces/my-namespace/services/my-service/endpoints/endpoint-c" - // returns Endpoints that have name that is alphabetically later than the - // string, so "endpoint-e" will be returned but "endpoint-a" will not be. - // - "metadata.owner!=sd AND metadata.foo=bar" returns Endpoints that have - // "owner" in label key but value is not "sd" AND have key/value foo=bar. - // - "doesnotexist.foo=bar" returns an empty list. Note that Endpoint doesn't - // have a field called "doesnotexist". Since the filter does not match any - // Endpoints, it returns no results. + // * "metadata.owner" returns Endpoints that have a label with the key "owner" + // this is the same as "metadata:owner". + // * "metadata.protocol=gRPC" returns Endpoints that have key/value + // "protocol=gRPC". + // * "address=192.108.1.105" returns Endpoints that have this address. + // * "port>8080" returns Endpoints that have port number larger than 8080. + // * "name>projects/my-project/locations/us-east/namespaces/my-namespace/services/my-service/endpoints/endpoint-c" + // returns Endpoints that have name that is alphabetically later than the + // string, so "endpoint-e" will be returned but "endpoint-a" will not be. + // * "metadata.owner!=sd AND metadata.foo=bar" returns Endpoints that have + // "owner" in label key but value is not "sd" AND have key/value foo=bar. + // * "doesnotexist.foo=bar" returns an empty list. Note that Endpoint doesn't + // have a field called "doesnotexist". Since the filter does not match any + // Endpoints, it returns no results. Filter string `protobuf:"bytes,4,opt,name=filter,proto3" json:"filter,omitempty"` // Optional. The order to list result by. OrderBy string `protobuf:"bytes,5,opt,name=order_by,json=orderBy,proto3" json:"order_by,omitempty"` diff --git a/servicedirectory/apiv1/servicedirectorypb/service.pb.go b/servicedirectory/apiv1/servicedirectorypb/service.pb.go index 375f3392260b..dc5c68694612 100644 --- a/servicedirectory/apiv1/servicedirectorypb/service.pb.go +++ b/servicedirectory/apiv1/servicedirectorypb/service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/servicedirectory/v1/service.proto package servicedirectorypb @@ -51,22 +51,21 @@ type Service struct { // Optional. Annotations for the service. This data can be consumed by service // clients. // Restrictions: - // - The entire annotations dictionary may contain up to 2000 characters, - // spread accoss all key-value pairs. Annotations that goes beyond any - // these limits will be rejected. - // - Valid annotation keys have two segments: an optional prefix and name, - // separated by a slash (/). The name segment is required and must be 63 - // characters or less, beginning and ending with an alphanumeric character - // ([a-z0-9A-Z]) with dashes (-), underscores (_), dots (.), and - // alphanumerics between. The prefix is optional. If specified, the prefix - // must be a DNS subdomain: a series of DNS labels separated by dots (.), - // not longer than 253 characters in total, followed by a slash (/). - // Annotations that fails to meet these requirements will be rejected. - // - The '(*.)google.com/' and '(*.)googleapis.com/' prefixes are reserved - // for system annotations managed by Service Directory. If the user tries - // to write to these keyspaces, those entries will be silently ignored by - // the system. - // + // - The entire annotations dictionary may contain up to 2000 characters, + // spread accoss all key-value pairs. Annotations that goes beyond any + // these limits will be rejected. + // - Valid annotation keys have two segments: an optional prefix and name, + // separated by a slash (/). The name segment is required and must be 63 + // characters or less, beginning and ending with an alphanumeric character + // ([a-z0-9A-Z]) with dashes (-), underscores (_), dots (.), and + // alphanumerics between. The prefix is optional. If specified, the prefix + // must be a DNS subdomain: a series of DNS labels separated by dots (.), + // not longer than 253 characters in total, followed by a slash (/). + // Annotations that fails to meet these requirements will be rejected. + // - The '(*.)google.com/' and '(*.)googleapis.com/' prefixes are reserved + // for system annotations managed by Service Directory. If the user tries + // to write to these keyspaces, those entries will be silently ignored by + // the system. // Note: This field is equivalent to the 'metadata' field in the v1beta1 API. // They have the same syntax and read/write to the same location in Service // Directory. diff --git a/servicedirectory/apiv1beta1/lookup_client.go b/servicedirectory/apiv1beta1/lookup_client.go index 641821e08ef3..0e38594a8412 100644 --- a/servicedirectory/apiv1beta1/lookup_client.go +++ b/servicedirectory/apiv1beta1/lookup_client.go @@ -328,6 +328,11 @@ func (c *lookupRESTClient) ResolveService(ctx context.Context, req *servicedirec } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:resolve", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) diff --git a/servicedirectory/apiv1beta1/registration_client.go b/servicedirectory/apiv1beta1/registration_client.go index b5036a1bdd86..dc96d303c022 100644 --- a/servicedirectory/apiv1beta1/registration_client.go +++ b/servicedirectory/apiv1beta1/registration_client.go @@ -1314,6 +1314,7 @@ func (c *registrationRESTClient) CreateNamespace(ctx context.Context, req *servi baseUrl.Path += fmt.Sprintf("/v1beta1/%v/namespaces", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("namespaceId", fmt.Sprintf("%v", req.GetNamespaceId())) baseUrl.RawQuery = params.Encode() @@ -1385,6 +1386,7 @@ func (c *registrationRESTClient) ListNamespaces(ctx context.Context, req *servic baseUrl.Path += fmt.Sprintf("/v1beta1/%v/namespaces", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1464,6 +1466,11 @@ func (c *registrationRESTClient) GetNamespace(ctx context.Context, req *serviced } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1525,6 +1532,7 @@ func (c *registrationRESTClient) UpdateNamespace(ctx context.Context, req *servi baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetNamespace().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -1589,6 +1597,11 @@ func (c *registrationRESTClient) DeleteNamespace(ctx context.Context, req *servi } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1632,6 +1645,7 @@ func (c *registrationRESTClient) CreateService(ctx context.Context, req *service baseUrl.Path += fmt.Sprintf("/v1beta1/%v/services", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("serviceId", fmt.Sprintf("%v", req.GetServiceId())) baseUrl.RawQuery = params.Encode() @@ -1703,6 +1717,7 @@ func (c *registrationRESTClient) ListServices(ctx context.Context, req *serviced baseUrl.Path += fmt.Sprintf("/v1beta1/%v/services", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -1782,6 +1797,11 @@ func (c *registrationRESTClient) GetService(ctx context.Context, req *servicedir } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1843,6 +1863,7 @@ func (c *registrationRESTClient) UpdateService(ctx context.Context, req *service baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetService().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -1907,6 +1928,11 @@ func (c *registrationRESTClient) DeleteService(ctx context.Context, req *service } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1950,6 +1976,7 @@ func (c *registrationRESTClient) CreateEndpoint(ctx context.Context, req *servic baseUrl.Path += fmt.Sprintf("/v1beta1/%v/endpoints", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("endpointId", fmt.Sprintf("%v", req.GetEndpointId())) baseUrl.RawQuery = params.Encode() @@ -2021,6 +2048,7 @@ func (c *registrationRESTClient) ListEndpoints(ctx context.Context, req *service baseUrl.Path += fmt.Sprintf("/v1beta1/%v/endpoints", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -2100,6 +2128,11 @@ func (c *registrationRESTClient) GetEndpoint(ctx context.Context, req *servicedi } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2161,6 +2194,7 @@ func (c *registrationRESTClient) UpdateEndpoint(ctx context.Context, req *servic baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetEndpoint().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -2224,6 +2258,11 @@ func (c *registrationRESTClient) DeleteEndpoint(ctx context.Context, req *servic } baseUrl.Path += fmt.Sprintf("/v1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -2265,6 +2304,11 @@ func (c *registrationRESTClient) GetIamPolicy(ctx context.Context, req *iampb.Ge } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:getIamPolicy", req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) @@ -2324,6 +2368,11 @@ func (c *registrationRESTClient) SetIamPolicy(ctx context.Context, req *iampb.Se } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:setIamPolicy", req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) @@ -2383,6 +2432,11 @@ func (c *registrationRESTClient) TestIamPermissions(ctx context.Context, req *ia } baseUrl.Path += fmt.Sprintf("/v1beta1/%v:testIamPermissions", req.GetResource()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) diff --git a/servicedirectory/apiv1beta1/servicedirectorypb/endpoint.pb.go b/servicedirectory/apiv1beta1/servicedirectorypb/endpoint.pb.go index 90f41a26ae45..add82a0a9d3f 100644 --- a/servicedirectory/apiv1beta1/servicedirectorypb/endpoint.pb.go +++ b/servicedirectory/apiv1beta1/servicedirectorypb/endpoint.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/servicedirectory/v1beta1/endpoint.proto package servicedirectorypb @@ -65,10 +65,10 @@ type Endpoint struct { // // Restrictions: // - // - The entire metadata dictionary may contain up to 512 characters, + // * The entire metadata dictionary may contain up to 512 characters, // spread accoss all key-value pairs. Metadata that goes beyond this // limit are rejected - // - Valid metadata keys have two segments: an optional prefix and name, + // * Valid metadata keys have two segments: an optional prefix and name, // separated by a slash (/). The name segment is required and must be 63 // characters or less, beginning and ending with an alphanumeric character // ([a-z0-9A-Z]) with dashes (-), underscores (_), dots (.), and @@ -76,7 +76,7 @@ type Endpoint struct { // must be a DNS subdomain: a series of DNS labels separated by dots (.), // not longer than 253 characters in total, followed by a slash (/). // Metadata that fails to meet these requirements are rejected - // - The `(*.)google.com/` and `(*.)googleapis.com/` prefixes are reserved + // * The `(*.)google.com/` and `(*.)googleapis.com/` prefixes are reserved // for system metadata managed by Service Directory. If the user tries // to write to these keyspaces, those entries are silently ignored by // the system diff --git a/servicedirectory/apiv1beta1/servicedirectorypb/lookup_service.pb.go b/servicedirectory/apiv1beta1/servicedirectorypb/lookup_service.pb.go index fa33733c95a6..ec764b38b6d7 100644 --- a/servicedirectory/apiv1beta1/servicedirectorypb/lookup_service.pb.go +++ b/servicedirectory/apiv1beta1/servicedirectorypb/lookup_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/servicedirectory/v1beta1/lookup_service.proto package servicedirectorypb @@ -58,31 +58,29 @@ type ResolveServiceRequest struct { // General `filter` string syntax: // ` ()` // - // - `` can be `name`, `address`, `port`, or `metadata.` for + // * `` can be `name`, `address`, `port`, or `metadata.` for // map field - // - `` can be `<`, `>`, `<=`, `>=`, `!=`, `=`, `:`. Of which `:` + // * `` can be `<`, `>`, `<=`, `>=`, `!=`, `=`, `:`. Of which `:` // means `HAS`, and is roughly the same as `=` - // - `` must be the same data type as field - // - `` can be `AND`, `OR`, `NOT` + // * `` must be the same data type as field + // * `` can be `AND`, `OR`, `NOT` // // Examples of valid filters: // - // - `metadata.owner` returns endpoints that have a annotation with the key + // * `metadata.owner` returns endpoints that have a annotation with the key // `owner`, this is the same as `metadata:owner` - // - `metadata.protocol=gRPC` returns endpoints that have key/value + // * `metadata.protocol=gRPC` returns endpoints that have key/value // `protocol=gRPC` - // - `address=192.108.1.105` returns endpoints that have this address - // - `port>8080` returns endpoints that have port number larger than 8080 - // + // * `address=192.108.1.105` returns endpoints that have this address + // * `port>8080` returns endpoints that have port number larger than 8080 // * // `name>projects/my-project/locations/us-east1/namespaces/my-namespace/services/my-service/endpoints/endpoint-c` - // - // returns endpoints that have name that is alphabetically later than the - // string, so "endpoint-e" is returned but "endpoint-a" is not - // - `metadata.owner!=sd AND metadata.foo=bar` returns endpoints that have + // returns endpoints that have name that is alphabetically later than the + // string, so "endpoint-e" is returned but "endpoint-a" is not + // * `metadata.owner!=sd AND metadata.foo=bar` returns endpoints that have // `owner` in annotation key but value is not `sd` AND have key/value - // `foo=bar` - // - `doesnotexist.foo=bar` returns an empty list. Note that endpoint + // `foo=bar` + // * `doesnotexist.foo=bar` returns an empty list. Note that endpoint // doesn't have a field called "doesnotexist". Since the filter does not // match any endpoint, it returns no results // diff --git a/servicedirectory/apiv1beta1/servicedirectorypb/namespace.pb.go b/servicedirectory/apiv1beta1/servicedirectorypb/namespace.pb.go index 9530aad2c101..ebe993bf7e19 100644 --- a/servicedirectory/apiv1beta1/servicedirectorypb/namespace.pb.go +++ b/servicedirectory/apiv1beta1/servicedirectorypb/namespace.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/servicedirectory/v1beta1/namespace.proto package servicedirectorypb diff --git a/servicedirectory/apiv1beta1/servicedirectorypb/registration_service.pb.go b/servicedirectory/apiv1beta1/servicedirectorypb/registration_service.pb.go index 4270bec2ec4c..cffb57e714a4 100644 --- a/servicedirectory/apiv1beta1/servicedirectorypb/registration_service.pb.go +++ b/servicedirectory/apiv1beta1/servicedirectorypb/registration_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/servicedirectory/v1beta1/registration_service.proto package servicedirectorypb @@ -135,23 +135,23 @@ type ListNamespacesRequest struct { // General `filter` string syntax: // ` ()` // - // - `` can be `name` or `labels.` for map field - // - `` can be `<`, `>`, `<=`, `>=`, `!=`, `=`, `:`. Of which `:` + // * `` can be `name` or `labels.` for map field + // * `` can be `<`, `>`, `<=`, `>=`, `!=`, `=`, `:`. Of which `:` // means `HAS`, and is roughly the same as `=` - // - `` must be the same data type as field - // - `` can be `AND`, `OR`, `NOT` + // * `` must be the same data type as field + // * `` can be `AND`, `OR`, `NOT` // // Examples of valid filters: // - // - `labels.owner` returns namespaces that have a label with the key + // * `labels.owner` returns namespaces that have a label with the key // `owner`, this is the same as `labels:owner` - // - `labels.owner=sd` returns namespaces that have key/value `owner=sd` - // - `name>projects/my-project/locations/us-east1/namespaces/namespace-c` + // * `labels.owner=sd` returns namespaces that have key/value `owner=sd` + // * `name>projects/my-project/locations/us-east1/namespaces/namespace-c` // returns namespaces that have name that is alphabetically later than the // string, so "namespace-e" is returned but "namespace-a" is not - // - `labels.owner!=sd AND labels.foo=bar` returns namespaces that have + // * `labels.owner!=sd AND labels.foo=bar` returns namespaces that have // `owner` in label key but value is not `sd` AND have key/value `foo=bar` - // - `doesnotexist.foo=bar` returns an empty list. Note that namespace + // * `doesnotexist.foo=bar` returns an empty list. Note that namespace // doesn't have a field called "doesnotexist". Since the filter does not // match any namespaces, it returns no results // @@ -162,8 +162,8 @@ type ListNamespacesRequest struct { // // General `order_by` string syntax: ` () (,)` // - // - `` allows value: `name` - // - `` ascending or descending order by ``. If this is + // * `` allows value: `name` + // * `` ascending or descending order by ``. If this is // left blank, `asc` is used // // Note that an empty `order_by` string results in default order, which is @@ -545,28 +545,26 @@ type ListServicesRequest struct { // General `filter` string syntax: // ` ()` // - // - `` can be `name` or `metadata.` for map field - // - `` can be `<`, `>`, `<=`, `>=`, `!=`, `=`, `:`. Of which `:` + // * `` can be `name` or `metadata.` for map field + // * `` can be `<`, `>`, `<=`, `>=`, `!=`, `=`, `:`. Of which `:` // means `HAS`, and is roughly the same as `=` - // - `` must be the same data type as field - // - `` can be `AND`, `OR`, `NOT` + // * `` must be the same data type as field + // * `` can be `AND`, `OR`, `NOT` // // Examples of valid filters: // - // - `metadata.owner` returns services that have a metadata with the key + // * `metadata.owner` returns services that have a metadata with the key // `owner`, this is the same as `metadata:owner` - // - `metadata.protocol=gRPC` returns services that have key/value + // * `metadata.protocol=gRPC` returns services that have key/value // `protocol=gRPC` - // // * // `name>projects/my-project/locations/us-east1/namespaces/my-namespace/services/service-c` - // - // returns services that have name that is alphabetically later than the - // string, so "service-e" is returned but "service-a" is not - // - `metadata.owner!=sd AND metadata.foo=bar` returns services that have + // returns services that have name that is alphabetically later than the + // string, so "service-e" is returned but "service-a" is not + // * `metadata.owner!=sd AND metadata.foo=bar` returns services that have // `owner` in metadata key but value is not `sd` AND have key/value // `foo=bar` - // - `doesnotexist.foo=bar` returns an empty list. Note that service + // * `doesnotexist.foo=bar` returns an empty list. Note that service // doesn't have a field called "doesnotexist". Since the filter does not // match any services, it returns no results // @@ -577,8 +575,8 @@ type ListServicesRequest struct { // // General `order_by` string syntax: ` () (,)` // - // - `` allows value: `name` - // - `` ascending or descending order by ``. If this is + // * `` allows value: `name` + // * `` ascending or descending order by ``. If this is // left blank, `asc` is used // // Note that an empty `order_by` string results in default order, which is @@ -962,31 +960,29 @@ type ListEndpointsRequest struct { // General `filter` string syntax: // ` ()` // - // - `` can be `name`, `address`, `port`, or `metadata.` for map + // * `` can be `name`, `address`, `port`, or `metadata.` for map // field - // - `` can be `<`, `>`, `<=`, `>=`, `!=`, `=`, `:`. Of which `:` + // * `` can be `<`, `>`, `<=`, `>=`, `!=`, `=`, `:`. Of which `:` // means `HAS`, and is roughly the same as `=` - // - `` must be the same data type as field - // - `` can be `AND`, `OR`, `NOT` + // * `` must be the same data type as field + // * `` can be `AND`, `OR`, `NOT` // // Examples of valid filters: // - // - `metadata.owner` returns endpoints that have a metadata with the key + // * `metadata.owner` returns endpoints that have a metadata with the key // `owner`, this is the same as `metadata:owner` - // - `metadata.protocol=gRPC` returns endpoints that have key/value + // * `metadata.protocol=gRPC` returns endpoints that have key/value // `protocol=gRPC` - // - `address=192.108.1.105` returns endpoints that have this address - // - `port>8080` returns endpoints that have port number larger than 8080 - // + // * `address=192.108.1.105` returns endpoints that have this address + // * `port>8080` returns endpoints that have port number larger than 8080 // * // `name>projects/my-project/locations/us-east1/namespaces/my-namespace/services/my-service/endpoints/endpoint-c` - // - // returns endpoints that have name that is alphabetically later than the - // string, so "endpoint-e" is returned but "endpoint-a" is not - // - `metadata.owner!=sd AND metadata.foo=bar` returns endpoints that have + // returns endpoints that have name that is alphabetically later than the + // string, so "endpoint-e" is returned but "endpoint-a" is not + // * `metadata.owner!=sd AND metadata.foo=bar` returns endpoints that have // `owner` in metadata key but value is not `sd` AND have key/value - // `foo=bar` - // - `doesnotexist.foo=bar` returns an empty list. Note that endpoint + // `foo=bar` + // * `doesnotexist.foo=bar` returns an empty list. Note that endpoint // doesn't have a field called "doesnotexist". Since the filter does not // match any endpoints, it returns no results // @@ -997,8 +993,8 @@ type ListEndpointsRequest struct { // // General `order_by` string syntax: ` () (,)` // - // - `` allows values: `name`, `address`, `port` - // - `` ascending or descending order by ``. If this is + // * `` allows values: `name`, `address`, `port` + // * `` ascending or descending order by ``. If this is // left blank, `asc` is used // // Note that an empty `order_by` string results in default order, which is diff --git a/servicedirectory/apiv1beta1/servicedirectorypb/service.pb.go b/servicedirectory/apiv1beta1/servicedirectorypb/service.pb.go index 5881204d595c..acc5f237d254 100644 --- a/servicedirectory/apiv1beta1/servicedirectorypb/service.pb.go +++ b/servicedirectory/apiv1beta1/servicedirectorypb/service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/servicedirectory/v1beta1/service.proto package servicedirectorypb @@ -54,10 +54,10 @@ type Service struct { // // Restrictions: // - // - The entire metadata dictionary may contain up to 2000 characters, + // * The entire metadata dictionary may contain up to 2000 characters, // spread accoss all key-value pairs. Metadata that goes beyond this // limit are rejected - // - Valid metadata keys have two segments: an optional prefix and name, + // * Valid metadata keys have two segments: an optional prefix and name, // separated by a slash (/). The name segment is required and must be 63 // characters or less, beginning and ending with an alphanumeric character // ([a-z0-9A-Z]) with dashes (-), underscores (_), dots (.), and @@ -65,7 +65,7 @@ type Service struct { // must be a DNS subdomain: a series of DNS labels separated by dots (.), // not longer than 253 characters in total, followed by a slash (/). // Metadata that fails to meet these requirements are rejected - // - The `(*.)google.com/` and `(*.)googleapis.com/` prefixes are reserved + // * The `(*.)google.com/` and `(*.)googleapis.com/` prefixes are reserved // for system metadata managed by Service Directory. If the user tries // to write to these keyspaces, those entries are silently ignored by // the system diff --git a/servicemanagement/apiv1/doc.go b/servicemanagement/apiv1/doc.go index 1c5ed7c0e6ce..f807854be743 100644 --- a/servicemanagement/apiv1/doc.go +++ b/servicemanagement/apiv1/doc.go @@ -88,6 +88,8 @@ package servicemanagement // import "cloud.google.com/go/servicemanagement/apiv1 import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -179,3 +181,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/servicemanagement/apiv1/gapic_metadata.json b/servicemanagement/apiv1/gapic_metadata.json index b32e999aae67..483fa99eced2 100644 --- a/servicemanagement/apiv1/gapic_metadata.json +++ b/servicemanagement/apiv1/gapic_metadata.json @@ -76,6 +76,76 @@ ] } } + }, + "rest": { + "libraryClient": "ServiceManagerClient", + "rpcs": { + "CreateService": { + "methods": [ + "CreateService" + ] + }, + "CreateServiceConfig": { + "methods": [ + "CreateServiceConfig" + ] + }, + "CreateServiceRollout": { + "methods": [ + "CreateServiceRollout" + ] + }, + "DeleteService": { + "methods": [ + "DeleteService" + ] + }, + "GenerateConfigReport": { + "methods": [ + "GenerateConfigReport" + ] + }, + "GetService": { + "methods": [ + "GetService" + ] + }, + "GetServiceConfig": { + "methods": [ + "GetServiceConfig" + ] + }, + "GetServiceRollout": { + "methods": [ + "GetServiceRollout" + ] + }, + "ListServiceConfigs": { + "methods": [ + "ListServiceConfigs" + ] + }, + "ListServiceRollouts": { + "methods": [ + "ListServiceRollouts" + ] + }, + "ListServices": { + "methods": [ + "ListServices" + ] + }, + "SubmitConfigSource": { + "methods": [ + "SubmitConfigSource" + ] + }, + "UndeleteService": { + "methods": [ + "UndeleteService" + ] + } + } } } } diff --git a/servicemanagement/apiv1/service_manager_client.go b/servicemanagement/apiv1/service_manager_client.go index 41162f54843b..96faa77bcf16 100644 --- a/servicemanagement/apiv1/service_manager_client.go +++ b/servicemanagement/apiv1/service_manager_client.go @@ -17,9 +17,12 @@ package servicemanagement import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,14 +30,17 @@ import ( lroauto "cloud.google.com/go/longrunning/autogen" servicemanagementpb "cloud.google.com/go/servicemanagement/apiv1/servicemanagementpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" serviceconfigpb "google.golang.org/genproto/googleapis/api/serviceconfig" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -87,6 +93,24 @@ func defaultServiceManagerCallOptions() *ServiceManagerCallOptions { } } +func defaultServiceManagerRESTCallOptions() *ServiceManagerCallOptions { + return &ServiceManagerCallOptions{ + ListServices: []gax.CallOption{}, + GetService: []gax.CallOption{}, + CreateService: []gax.CallOption{}, + DeleteService: []gax.CallOption{}, + UndeleteService: []gax.CallOption{}, + ListServiceConfigs: []gax.CallOption{}, + GetServiceConfig: []gax.CallOption{}, + CreateServiceConfig: []gax.CallOption{}, + SubmitConfigSource: []gax.CallOption{}, + ListServiceRollouts: []gax.CallOption{}, + GetServiceRollout: []gax.CallOption{}, + CreateServiceRollout: []gax.CallOption{}, + GenerateConfigReport: []gax.CallOption{}, + } +} + // internalServiceManagerClient is an interface that defines the methods available from Service Management API. type internalServiceManagerClient interface { Close() error @@ -419,6 +443,90 @@ func (c *serviceManagerGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type serviceManagerRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing ServiceManagerClient + CallOptions **ServiceManagerCallOptions +} + +// NewServiceManagerRESTClient creates a new service manager rest client. +// +// Google Service Management +// API (at https://cloud.google.com/service-infrastructure/docs/overview) +func NewServiceManagerRESTClient(ctx context.Context, opts ...option.ClientOption) (*ServiceManagerClient, error) { + clientOpts := append(defaultServiceManagerRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultServiceManagerRESTCallOptions() + c := &serviceManagerRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &ServiceManagerClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultServiceManagerRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://servicemanagement.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://servicemanagement.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://servicemanagement.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *serviceManagerRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *serviceManagerRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *serviceManagerRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *serviceManagerGRPCClient) ListServices(ctx context.Context, req *servicemanagementpb.ListServicesRequest, opts ...gax.CallOption) *ManagedServiceIterator { ctx = insertMetadata(ctx, c.xGoogMetadata) opts = append((*c.CallOptions).ListServices[0:len((*c.CallOptions).ListServices):len((*c.CallOptions).ListServices)], opts...) @@ -778,147 +886,1150 @@ func (c *serviceManagerGRPCClient) GenerateConfigReport(ctx context.Context, req return resp, nil } -// CreateServiceOperation manages a long-running operation from CreateService. -type CreateServiceOperation struct { - lro *longrunning.Operation -} +// ListServices lists managed services. +// +// Returns all public services. For authenticated users, also returns all +// services the calling user has “servicemanagement.services.get” permission +// for. +func (c *serviceManagerRESTClient) ListServices(ctx context.Context, req *servicemanagementpb.ListServicesRequest, opts ...gax.CallOption) *ManagedServiceIterator { + it := &ManagedServiceIterator{} + req = proto.Clone(req).(*servicemanagementpb.ListServicesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*servicemanagementpb.ManagedService, string, error) { + resp := &servicemanagementpb.ListServicesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/services") -// CreateServiceOperation returns a new CreateServiceOperation from a given name. -// The name must be that of a previously created CreateServiceOperation, possibly from a different process. -func (c *serviceManagerGRPCClient) CreateServiceOperation(name string) *CreateServiceOperation { - return &CreateServiceOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetConsumerId() != "" { + params.Add("consumerId", fmt.Sprintf("%v", req.GetConsumerId())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + if req.GetProducerProjectId() != "" { + params.Add("producerProjectId", fmt.Sprintf("%v", req.GetProducerProjectId())) + } -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *CreateServiceOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*servicemanagementpb.ManagedService, error) { - var resp servicemanagementpb.ManagedService - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { - return nil, err + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetServices(), resp.GetNextPageToken(), nil } - return &resp, nil -} -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *CreateServiceOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*servicemanagementpb.ManagedService, error) { - var resp servicemanagementpb.ManagedService - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { - return nil, err - } - if !op.Done() { - return nil, 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 } - return &resp, nil + + it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it } -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *CreateServiceOperation) Metadata() (*servicemanagementpb.OperationMetadata, error) { - var meta servicemanagementpb.OperationMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { +// GetService gets a managed service. Authentication is required unless the service is +// public. +func (c *serviceManagerRESTClient) GetService(ctx context.Context, req *servicemanagementpb.GetServiceRequest, opts ...gax.CallOption) (*servicemanagementpb.ManagedService, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - return &meta, nil -} + baseUrl.Path += fmt.Sprintf("/v1/services/%v", req.GetServiceName()) -// Done reports whether the long-running operation has completed. -func (op *CreateServiceOperation) Done() bool { - return op.lro.Done() -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") -// 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 *CreateServiceOperation) Name() string { - return op.lro.Name() -} + baseUrl.RawQuery = params.Encode() -// CreateServiceRolloutOperation manages a long-running operation from CreateServiceRollout. -type CreateServiceRolloutOperation struct { - lro *longrunning.Operation -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "service_name", url.QueryEscape(req.GetServiceName()))) -// CreateServiceRolloutOperation returns a new CreateServiceRolloutOperation from a given name. -// The name must be that of a previously created CreateServiceRolloutOperation, possibly from a different process. -func (c *serviceManagerGRPCClient) CreateServiceRolloutOperation(name string) *CreateServiceRolloutOperation { - return &CreateServiceRolloutOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetService[0:len((*c.CallOptions).GetService):len((*c.CallOptions).GetService)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &servicemanagementpb.ManagedService{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *CreateServiceRolloutOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*servicemanagementpb.Rollout, error) { - var resp servicemanagementpb.Rollout - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { - return nil, err + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e } - return &resp, nil + return resp, nil } -// Poll fetches the latest state of the long-running operation. +// CreateService creates a new managed service. // -// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// A managed service is immutable, and is subject to mandatory 30-day +// data retention. You cannot move a service or recreate it within 30 days +// after deletion. // -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *CreateServiceRolloutOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*servicemanagementpb.Rollout, error) { - var resp servicemanagementpb.Rollout - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { +// One producer project can own no more than 500 services. For security and +// reliability purposes, a production service should be hosted in a +// dedicated producer project. +// +// Operation +func (c *serviceManagerRESTClient) CreateService(ctx context.Context, req *servicemanagementpb.CreateServiceRequest, opts ...gax.CallOption) (*CreateServiceOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetService() + jsonReq, err := m.Marshal(body) + if err != nil { return nil, err } - if !op.Done() { - return nil, nil - } - return &resp, nil -} -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *CreateServiceRolloutOperation) Metadata() (*servicemanagementpb.OperationMetadata, error) { - var meta servicemanagementpb.OperationMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - return &meta, nil -} + baseUrl.Path += fmt.Sprintf("/v1/services") -// Done reports whether the long-running operation has completed. -func (op *CreateServiceRolloutOperation) Done() bool { - return op.lro.Done() -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") -// 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 *CreateServiceRolloutOperation) Name() string { - return op.lro.Name() -} + baseUrl.RawQuery = params.Encode() -// DeleteServiceOperation manages a long-running operation from DeleteService. -type DeleteServiceOperation struct { - lro *longrunning.Operation + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateServiceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteService deletes a managed service. This method will change the service to the +// Soft-Delete state for 30 days. Within this period, service producers may +// call +// UndeleteService +// to restore the service. After 30 days, the service will be permanently +// deleted. +// +// Operation +func (c *serviceManagerRESTClient) DeleteService(ctx context.Context, req *servicemanagementpb.DeleteServiceRequest, opts ...gax.CallOption) (*DeleteServiceOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/services/%v", req.GetServiceName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "service_name", url.QueryEscape(req.GetServiceName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteServiceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UndeleteService revives a previously deleted managed service. The method restores the +// service using the configuration at the time the service was deleted. +// The target service must exist and must have been deleted within the +// last 30 days. +// +// Operation +func (c *serviceManagerRESTClient) UndeleteService(ctx context.Context, req *servicemanagementpb.UndeleteServiceRequest, opts ...gax.CallOption) (*UndeleteServiceOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/services/%v:undelete", req.GetServiceName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "service_name", url.QueryEscape(req.GetServiceName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UndeleteServiceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListServiceConfigs lists the history of the service configuration for a managed service, +// from the newest to the oldest. +func (c *serviceManagerRESTClient) ListServiceConfigs(ctx context.Context, req *servicemanagementpb.ListServiceConfigsRequest, opts ...gax.CallOption) *ServiceIterator { + it := &ServiceIterator{} + req = proto.Clone(req).(*servicemanagementpb.ListServiceConfigsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*serviceconfigpb.Service, string, error) { + resp := &servicemanagementpb.ListServiceConfigsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/services/%v/configs", req.GetServiceName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetServiceConfigs(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetServiceConfig gets a service configuration (version) for a managed service. +func (c *serviceManagerRESTClient) GetServiceConfig(ctx context.Context, req *servicemanagementpb.GetServiceConfigRequest, opts ...gax.CallOption) (*serviceconfigpb.Service, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/services/%v/configs/%v", req.GetServiceName(), req.GetConfigId()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetView() != 0 { + params.Add("view", fmt.Sprintf("%v", req.GetView())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "service_name", url.QueryEscape(req.GetServiceName()), "config_id", url.QueryEscape(req.GetConfigId()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetServiceConfig[0:len((*c.CallOptions).GetServiceConfig):len((*c.CallOptions).GetServiceConfig)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &serviceconfigpb.Service{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateServiceConfig creates a new service configuration (version) for a managed service. +// This method only stores the service configuration. To roll out the service +// configuration to backend systems please call +// CreateServiceRollout. +// +// Only the 100 most recent service configurations and ones referenced by +// existing rollouts are kept for each service. The rest will be deleted +// eventually. +func (c *serviceManagerRESTClient) CreateServiceConfig(ctx context.Context, req *servicemanagementpb.CreateServiceConfigRequest, opts ...gax.CallOption) (*serviceconfigpb.Service, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetServiceConfig() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/services/%v/configs", req.GetServiceName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "service_name", url.QueryEscape(req.GetServiceName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateServiceConfig[0:len((*c.CallOptions).CreateServiceConfig):len((*c.CallOptions).CreateServiceConfig)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &serviceconfigpb.Service{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SubmitConfigSource creates a new service configuration (version) for a managed service based +// on +// user-supplied configuration source files (for example: OpenAPI +// Specification). This method stores the source configurations as well as the +// generated service configuration. To rollout the service configuration to +// other services, +// please call +// CreateServiceRollout. +// +// Only the 100 most recent configuration sources and ones referenced by +// existing service configurtions are kept for each service. The rest will be +// deleted eventually. +// +// Operation +func (c *serviceManagerRESTClient) SubmitConfigSource(ctx context.Context, req *servicemanagementpb.SubmitConfigSourceRequest, opts ...gax.CallOption) (*SubmitConfigSourceOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/services/%v/configs:submit", req.GetServiceName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "service_name", url.QueryEscape(req.GetServiceName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &SubmitConfigSourceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListServiceRollouts lists the history of the service configuration rollouts for a managed +// service, from the newest to the oldest. +func (c *serviceManagerRESTClient) ListServiceRollouts(ctx context.Context, req *servicemanagementpb.ListServiceRolloutsRequest, opts ...gax.CallOption) *RolloutIterator { + it := &RolloutIterator{} + req = proto.Clone(req).(*servicemanagementpb.ListServiceRolloutsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*servicemanagementpb.Rollout, string, error) { + resp := &servicemanagementpb.ListServiceRolloutsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/services/%v/rollouts", req.GetServiceName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetRollouts(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetServiceRollout gets a service configuration +// rollout. +func (c *serviceManagerRESTClient) GetServiceRollout(ctx context.Context, req *servicemanagementpb.GetServiceRolloutRequest, opts ...gax.CallOption) (*servicemanagementpb.Rollout, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/services/%v/rollouts/%v", req.GetServiceName(), req.GetRolloutId()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "service_name", url.QueryEscape(req.GetServiceName()), "rollout_id", url.QueryEscape(req.GetRolloutId()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetServiceRollout[0:len((*c.CallOptions).GetServiceRollout):len((*c.CallOptions).GetServiceRollout)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &servicemanagementpb.Rollout{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateServiceRollout creates a new service configuration rollout. Based on rollout, the +// Google Service Management will roll out the service configurations to +// different backend services. For example, the logging configuration will be +// pushed to Google Cloud Logging. +// +// Please note that any previous pending and running Rollouts and associated +// Operations will be automatically cancelled so that the latest Rollout will +// not be blocked by previous Rollouts. +// +// Only the 100 most recent (in any state) and the last 10 successful (if not +// already part of the set of 100 most recent) rollouts are kept for each +// service. The rest will be deleted eventually. +// +// Operation +func (c *serviceManagerRESTClient) CreateServiceRollout(ctx context.Context, req *servicemanagementpb.CreateServiceRolloutRequest, opts ...gax.CallOption) (*CreateServiceRolloutOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetRollout() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/services/%v/rollouts", req.GetServiceName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "service_name", url.QueryEscape(req.GetServiceName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateServiceRolloutOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GenerateConfigReport generates and returns a report (errors, warnings and changes from +// existing configurations) associated with +// GenerateConfigReportRequest.new_value +// +// If GenerateConfigReportRequest.old_value is specified, +// GenerateConfigReportRequest will contain a single ChangeReport based on the +// comparison between GenerateConfigReportRequest.new_value and +// GenerateConfigReportRequest.old_value. +// If GenerateConfigReportRequest.old_value is not specified, this method +// will compare GenerateConfigReportRequest.new_value with the last pushed +// service configuration. +func (c *serviceManagerRESTClient) GenerateConfigReport(ctx context.Context, req *servicemanagementpb.GenerateConfigReportRequest, opts ...gax.CallOption) (*servicemanagementpb.GenerateConfigReportResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/services:generateConfigReport") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GenerateConfigReport[0:len((*c.CallOptions).GenerateConfigReport):len((*c.CallOptions).GenerateConfigReport)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &servicemanagementpb.GenerateConfigReportResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateServiceOperation manages a long-running operation from CreateService. +type CreateServiceOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateServiceOperation returns a new CreateServiceOperation from a given name. +// The name must be that of a previously created CreateServiceOperation, possibly from a different process. +func (c *serviceManagerGRPCClient) CreateServiceOperation(name string) *CreateServiceOperation { + return &CreateServiceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateServiceOperation returns a new CreateServiceOperation from a given name. +// The name must be that of a previously created CreateServiceOperation, possibly from a different process. +func (c *serviceManagerRESTClient) CreateServiceOperation(name string) *CreateServiceOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateServiceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CreateServiceOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*servicemanagementpb.ManagedService, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp servicemanagementpb.ManagedService + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *CreateServiceOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*servicemanagementpb.ManagedService, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp servicemanagementpb.ManagedService + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *CreateServiceOperation) Metadata() (*servicemanagementpb.OperationMetadata, error) { + var meta servicemanagementpb.OperationMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *CreateServiceOperation) Done() bool { + return op.lro.Done() +} + +// 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 *CreateServiceOperation) Name() string { + return op.lro.Name() +} + +// CreateServiceRolloutOperation manages a long-running operation from CreateServiceRollout. +type CreateServiceRolloutOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateServiceRolloutOperation returns a new CreateServiceRolloutOperation from a given name. +// The name must be that of a previously created CreateServiceRolloutOperation, possibly from a different process. +func (c *serviceManagerGRPCClient) CreateServiceRolloutOperation(name string) *CreateServiceRolloutOperation { + return &CreateServiceRolloutOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateServiceRolloutOperation returns a new CreateServiceRolloutOperation from a given name. +// The name must be that of a previously created CreateServiceRolloutOperation, possibly from a different process. +func (c *serviceManagerRESTClient) CreateServiceRolloutOperation(name string) *CreateServiceRolloutOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateServiceRolloutOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CreateServiceRolloutOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*servicemanagementpb.Rollout, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp servicemanagementpb.Rollout + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *CreateServiceRolloutOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*servicemanagementpb.Rollout, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp servicemanagementpb.Rollout + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *CreateServiceRolloutOperation) Metadata() (*servicemanagementpb.OperationMetadata, error) { + var meta servicemanagementpb.OperationMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *CreateServiceRolloutOperation) Done() bool { + return op.lro.Done() +} + +// 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 *CreateServiceRolloutOperation) Name() string { + return op.lro.Name() +} + +// DeleteServiceOperation manages a long-running operation from DeleteService. +type DeleteServiceOperation struct { + lro *longrunning.Operation + pollPath string } // DeleteServiceOperation returns a new DeleteServiceOperation from a given name. @@ -929,10 +2040,21 @@ func (c *serviceManagerGRPCClient) DeleteServiceOperation(name string) *DeleteSe } } +// DeleteServiceOperation returns a new DeleteServiceOperation from a given name. +// The name must be that of a previously created DeleteServiceOperation, possibly from a different process. +func (c *serviceManagerRESTClient) DeleteServiceOperation(name string) *DeleteServiceOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteServiceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteServiceOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -946,6 +2068,7 @@ func (op *DeleteServiceOperation) Wait(ctx context.Context, opts ...gax.CallOpti // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteServiceOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -976,7 +2099,8 @@ func (op *DeleteServiceOperation) Name() string { // SubmitConfigSourceOperation manages a long-running operation from SubmitConfigSource. type SubmitConfigSourceOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // SubmitConfigSourceOperation returns a new SubmitConfigSourceOperation from a given name. @@ -987,10 +2111,21 @@ func (c *serviceManagerGRPCClient) SubmitConfigSourceOperation(name string) *Sub } } +// SubmitConfigSourceOperation returns a new SubmitConfigSourceOperation from a given name. +// The name must be that of a previously created SubmitConfigSourceOperation, possibly from a different process. +func (c *serviceManagerRESTClient) SubmitConfigSourceOperation(name string) *SubmitConfigSourceOperation { + override := fmt.Sprintf("/v1/%s", name) + return &SubmitConfigSourceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *SubmitConfigSourceOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*servicemanagementpb.SubmitConfigSourceResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp servicemanagementpb.SubmitConfigSourceResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1008,6 +2143,7 @@ func (op *SubmitConfigSourceOperation) Wait(ctx context.Context, opts ...gax.Cal // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *SubmitConfigSourceOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*servicemanagementpb.SubmitConfigSourceResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp servicemanagementpb.SubmitConfigSourceResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1045,7 +2181,8 @@ func (op *SubmitConfigSourceOperation) Name() string { // UndeleteServiceOperation manages a long-running operation from UndeleteService. type UndeleteServiceOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UndeleteServiceOperation returns a new UndeleteServiceOperation from a given name. @@ -1056,10 +2193,21 @@ func (c *serviceManagerGRPCClient) UndeleteServiceOperation(name string) *Undele } } +// UndeleteServiceOperation returns a new UndeleteServiceOperation from a given name. +// The name must be that of a previously created UndeleteServiceOperation, possibly from a different process. +func (c *serviceManagerRESTClient) UndeleteServiceOperation(name string) *UndeleteServiceOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UndeleteServiceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UndeleteServiceOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*servicemanagementpb.UndeleteServiceResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp servicemanagementpb.UndeleteServiceResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1077,6 +2225,7 @@ func (op *UndeleteServiceOperation) Wait(ctx context.Context, opts ...gax.CallOp // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UndeleteServiceOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*servicemanagementpb.UndeleteServiceResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp servicemanagementpb.UndeleteServiceResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/servicemanagement/apiv1/service_manager_client_example_test.go b/servicemanagement/apiv1/service_manager_client_example_test.go index 74273298071c..051b4d264be8 100644 --- a/servicemanagement/apiv1/service_manager_client_example_test.go +++ b/servicemanagement/apiv1/service_manager_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewServiceManagerClient() { _ = c } +func ExampleNewServiceManagerRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := servicemanagement.NewServiceManagerRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleServiceManagerClient_ListServices() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/servicemanagement/apiv1/servicemanagementpb/resources.pb.go b/servicemanagement/apiv1/servicemanagementpb/resources.pb.go index 19ec1e44d014..93a09d70192b 100644 --- a/servicemanagement/apiv1/servicemanagementpb/resources.pb.go +++ b/servicemanagement/apiv1/servicemanagementpb/resources.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/api/servicemanagement/v1/resources.proto package servicemanagementpb @@ -769,7 +769,6 @@ type Rollout struct { // and how they should be used at runtime. // // Types that are assignable to Strategy: - // // *Rollout_TrafficPercentStrategy_ // *Rollout_DeleteServiceStrategy_ Strategy isRollout_Strategy `protobuf_oneof:"strategy"` diff --git a/servicemanagement/apiv1/servicemanagementpb/servicemanager.pb.go b/servicemanagement/apiv1/servicemanagementpb/servicemanager.pb.go index 738b816f88d3..7131406cc8be 100644 --- a/servicemanagement/apiv1/servicemanagementpb/servicemanager.pb.go +++ b/servicemanagement/apiv1/servicemanagementpb/servicemanager.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/api/servicemanagement/v1/servicemanager.proto package servicemanagementpb @@ -945,13 +945,12 @@ type ListServiceRolloutsRequest struct { PageSize int32 `protobuf:"varint,3,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"` // Required. Use `filter` to return subset of rollouts. // The following filters are supported: - // - // -- To limit the results to only those in - // status (google.api.servicemanagement.v1.RolloutStatus) 'SUCCESS', - // use filter='status=SUCCESS' - // -- To limit the results to those in - // status (google.api.servicemanagement.v1.RolloutStatus) 'CANCELLED' - // or 'FAILED', use filter='status=CANCELLED OR status=FAILED' + // -- To limit the results to only those in + // status (google.api.servicemanagement.v1.RolloutStatus) 'SUCCESS', + // use filter='status=SUCCESS' + // -- To limit the results to those in + // status (google.api.servicemanagement.v1.RolloutStatus) 'CANCELLED' + // or 'FAILED', use filter='status=CANCELLED OR status=FAILED' Filter string `protobuf:"bytes,4,opt,name=filter,proto3" json:"filter,omitempty"` } diff --git a/serviceusage/apiv1/doc.go b/serviceusage/apiv1/doc.go index 4d070096f306..fd8318eec316 100644 --- a/serviceusage/apiv1/doc.go +++ b/serviceusage/apiv1/doc.go @@ -87,6 +87,8 @@ package serviceusage // import "cloud.google.com/go/serviceusage/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -177,3 +179,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/serviceusage/apiv1/gapic_metadata.json b/serviceusage/apiv1/gapic_metadata.json index 9c9213fb2f51..eb89909e1949 100644 --- a/serviceusage/apiv1/gapic_metadata.json +++ b/serviceusage/apiv1/gapic_metadata.json @@ -41,6 +41,41 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "BatchEnableServices": { + "methods": [ + "BatchEnableServices" + ] + }, + "BatchGetServices": { + "methods": [ + "BatchGetServices" + ] + }, + "DisableService": { + "methods": [ + "DisableService" + ] + }, + "EnableService": { + "methods": [ + "EnableService" + ] + }, + "GetService": { + "methods": [ + "GetService" + ] + }, + "ListServices": { + "methods": [ + "ListServices" + ] + } + } } } } diff --git a/serviceusage/apiv1/service_usage_client.go b/serviceusage/apiv1/service_usage_client.go index 5470aac8f6d8..7561bd1dee3f 100644 --- a/serviceusage/apiv1/service_usage_client.go +++ b/serviceusage/apiv1/service_usage_client.go @@ -17,9 +17,12 @@ package serviceusage import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,13 +30,16 @@ import ( lroauto "cloud.google.com/go/longrunning/autogen" serviceusagepb "cloud.google.com/go/serviceusage/apiv1/serviceusagepb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -72,6 +78,17 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + EnableService: []gax.CallOption{}, + DisableService: []gax.CallOption{}, + GetService: []gax.CallOption{}, + ListServices: []gax.CallOption{}, + BatchEnableServices: []gax.CallOption{}, + BatchGetServices: []gax.CallOption{}, + } +} + // internalClient is an interface that defines the methods available from Service Usage API. type internalClient interface { Close() error @@ -302,6 +319,93 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new service usage rest client. +// +// Enables services that service consumers want to use on Google Cloud Platform, +// lists the available or enabled services, or disables services that service +// consumers no longer use. +// +// See Service Usage API (at https://cloud.google.com/service-usage/docs/overview) +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://serviceusage.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://serviceusage.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://serviceusage.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) EnableService(ctx context.Context, req *serviceusagepb.EnableServiceRequest, opts ...gax.CallOption) (*EnableServiceOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) @@ -463,9 +567,447 @@ func (c *gRPCClient) BatchGetServices(ctx context.Context, req *serviceusagepb.B return resp, nil } +// EnableService enable a service so that it can be used with a project. +func (c *restClient) EnableService(ctx context.Context, req *serviceusagepb.EnableServiceRequest, opts ...gax.CallOption) (*EnableServiceOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:enable", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &EnableServiceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DisableService disable a service so that it can no longer be used with a project. +// This prevents unintended usage that may cause unexpected billing +// charges or security leaks. +// +// It is not valid to call the disable method on a service that is not +// currently enabled. Callers will receive a FAILED_PRECONDITION status if +// the target service is not currently enabled. +func (c *restClient) DisableService(ctx context.Context, req *serviceusagepb.DisableServiceRequest, opts ...gax.CallOption) (*DisableServiceOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:disable", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DisableServiceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetService returns the service configuration and enabled state for a given service. +func (c *restClient) GetService(ctx context.Context, req *serviceusagepb.GetServiceRequest, opts ...gax.CallOption) (*serviceusagepb.Service, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetService[0:len((*c.CallOptions).GetService):len((*c.CallOptions).GetService)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &serviceusagepb.Service{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListServices list all services available to the specified project, and the current +// state of those services with respect to the project. The list includes +// all public services, all services for which the calling user has the +// servicemanagement.services.bind permission, and all services that have +// already been enabled on the project. The list can be filtered to +// only include services in a specific state, for example to only include +// services enabled on the project. +// +// WARNING: If you need to query enabled services frequently or across +// an organization, you should use +// Cloud Asset Inventory +// API (at https://cloud.google.com/asset-inventory/docs/apis), which provides +// higher throughput and richer filtering capability. +func (c *restClient) ListServices(ctx context.Context, req *serviceusagepb.ListServicesRequest, opts ...gax.CallOption) *ServiceIterator { + it := &ServiceIterator{} + req = proto.Clone(req).(*serviceusagepb.ListServicesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*serviceusagepb.Service, string, error) { + resp := &serviceusagepb.ListServicesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/services", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetServices(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// BatchEnableServices enable multiple services on a project. The operation is atomic: if enabling +// any service fails, then the entire batch fails, and no state changes occur. +// To enable a single service, use the EnableService method instead. +func (c *restClient) BatchEnableServices(ctx context.Context, req *serviceusagepb.BatchEnableServicesRequest, opts ...gax.CallOption) (*BatchEnableServicesOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/services:batchEnable", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &BatchEnableServicesOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// BatchGetServices returns the service configurations and enabled states for a given list of +// services. +func (c *restClient) BatchGetServices(ctx context.Context, req *serviceusagepb.BatchGetServicesRequest, opts ...gax.CallOption) (*serviceusagepb.BatchGetServicesResponse, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/services:batchGet", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if items := req.GetNames(); len(items) > 0 { + for _, item := range items { + params.Add("names", fmt.Sprintf("%v", item)) + } + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).BatchGetServices[0:len((*c.CallOptions).BatchGetServices):len((*c.CallOptions).BatchGetServices)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &serviceusagepb.BatchGetServicesResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + // BatchEnableServicesOperation manages a long-running operation from BatchEnableServices. type BatchEnableServicesOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // BatchEnableServicesOperation returns a new BatchEnableServicesOperation from a given name. @@ -476,10 +1018,21 @@ func (c *gRPCClient) BatchEnableServicesOperation(name string) *BatchEnableServi } } +// BatchEnableServicesOperation returns a new BatchEnableServicesOperation from a given name. +// The name must be that of a previously created BatchEnableServicesOperation, possibly from a different process. +func (c *restClient) BatchEnableServicesOperation(name string) *BatchEnableServicesOperation { + override := fmt.Sprintf("/v1/%s", name) + return &BatchEnableServicesOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *BatchEnableServicesOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*serviceusagepb.BatchEnableServicesResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp serviceusagepb.BatchEnableServicesResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -497,6 +1050,7 @@ func (op *BatchEnableServicesOperation) Wait(ctx context.Context, opts ...gax.Ca // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *BatchEnableServicesOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*serviceusagepb.BatchEnableServicesResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp serviceusagepb.BatchEnableServicesResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -534,7 +1088,8 @@ func (op *BatchEnableServicesOperation) Name() string { // DisableServiceOperation manages a long-running operation from DisableService. type DisableServiceOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DisableServiceOperation returns a new DisableServiceOperation from a given name. @@ -545,10 +1100,21 @@ func (c *gRPCClient) DisableServiceOperation(name string) *DisableServiceOperati } } +// DisableServiceOperation returns a new DisableServiceOperation from a given name. +// The name must be that of a previously created DisableServiceOperation, possibly from a different process. +func (c *restClient) DisableServiceOperation(name string) *DisableServiceOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DisableServiceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DisableServiceOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*serviceusagepb.DisableServiceResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp serviceusagepb.DisableServiceResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -566,6 +1132,7 @@ func (op *DisableServiceOperation) Wait(ctx context.Context, opts ...gax.CallOpt // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DisableServiceOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*serviceusagepb.DisableServiceResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp serviceusagepb.DisableServiceResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -603,7 +1170,8 @@ func (op *DisableServiceOperation) Name() string { // EnableServiceOperation manages a long-running operation from EnableService. type EnableServiceOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // EnableServiceOperation returns a new EnableServiceOperation from a given name. @@ -614,10 +1182,21 @@ func (c *gRPCClient) EnableServiceOperation(name string) *EnableServiceOperation } } +// EnableServiceOperation returns a new EnableServiceOperation from a given name. +// The name must be that of a previously created EnableServiceOperation, possibly from a different process. +func (c *restClient) EnableServiceOperation(name string) *EnableServiceOperation { + override := fmt.Sprintf("/v1/%s", name) + return &EnableServiceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *EnableServiceOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*serviceusagepb.EnableServiceResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp serviceusagepb.EnableServiceResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -635,6 +1214,7 @@ func (op *EnableServiceOperation) Wait(ctx context.Context, opts ...gax.CallOpti // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *EnableServiceOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*serviceusagepb.EnableServiceResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp serviceusagepb.EnableServiceResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/serviceusage/apiv1/service_usage_client_example_test.go b/serviceusage/apiv1/service_usage_client_example_test.go index 306a0e2c5b3e..b9211050857d 100644 --- a/serviceusage/apiv1/service_usage_client_example_test.go +++ b/serviceusage/apiv1/service_usage_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := serviceusage.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_EnableService() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/serviceusage/apiv1/serviceusagepb/resources.pb.go b/serviceusage/apiv1/serviceusagepb/resources.pb.go index c12663ad6261..b39c684f1cff 100644 --- a/serviceusage/apiv1/serviceusagepb/resources.pb.go +++ b/serviceusage/apiv1/serviceusagepb/resources.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/api/serviceusage/v1/resources.proto package serviceusagepb diff --git a/serviceusage/apiv1/serviceusagepb/serviceusage.pb.go b/serviceusage/apiv1/serviceusagepb/serviceusage.pb.go index 260b0817304a..19f92d6feb37 100644 --- a/serviceusage/apiv1/serviceusagepb/serviceusage.pb.go +++ b/serviceusage/apiv1/serviceusagepb/serviceusage.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/api/serviceusage/v1/serviceusage.proto package serviceusagepb diff --git a/shell/apiv1/cloud_shell_client.go b/shell/apiv1/cloud_shell_client.go index 4540d93c53cd..39dc5627eaea 100644 --- a/shell/apiv1/cloud_shell_client.go +++ b/shell/apiv1/cloud_shell_client.go @@ -17,9 +17,12 @@ package shell import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,13 +30,16 @@ import ( lroauto "cloud.google.com/go/longrunning/autogen" shellpb "cloud.google.com/go/shell/apiv1/shellpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" ) var newCloudShellClientHook clientHook @@ -80,6 +86,26 @@ func defaultCloudShellCallOptions() *CloudShellCallOptions { } } +func defaultCloudShellRESTCallOptions() *CloudShellCallOptions { + return &CloudShellCallOptions{ + GetEnvironment: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusInternalServerError) + }), + }, + StartEnvironment: []gax.CallOption{}, + AuthorizeEnvironment: []gax.CallOption{}, + AddPublicKey: []gax.CallOption{}, + RemovePublicKey: []gax.CallOption{}, + } +} + // internalCloudShellClient is an interface that defines the methods available from Cloud Shell API. type internalCloudShellClient interface { Close() error @@ -307,6 +333,95 @@ func (c *cloudShellGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type cloudShellRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing CloudShellClient + CallOptions **CloudShellCallOptions +} + +// NewCloudShellRESTClient creates a new cloud shell service rest client. +// +// API for interacting with Google Cloud Shell. Each user of Cloud Shell has at +// least one environment, which has the ID “default”. Environment consists of a +// Docker image defining what is installed on the environment and a home +// directory containing the user’s data that will remain across sessions. +// Clients use this API to start and fetch information about their environment, +// which can then be used to connect to that environment via a separate SSH +// client. +func NewCloudShellRESTClient(ctx context.Context, opts ...option.ClientOption) (*CloudShellClient, error) { + clientOpts := append(defaultCloudShellRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultCloudShellRESTCallOptions() + c := &cloudShellRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &CloudShellClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultCloudShellRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://cloudshell.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://cloudshell.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://cloudshell.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *cloudShellRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *cloudShellRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *cloudShellRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *cloudShellGRPCClient) GetEnvironment(ctx context.Context, req *shellpb.GetEnvironmentRequest, opts ...gax.CallOption) (*shellpb.Environment, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) @@ -425,9 +540,353 @@ func (c *cloudShellGRPCClient) RemovePublicKey(ctx context.Context, req *shellpb }, nil } +// GetEnvironment gets an environment. Returns NOT_FOUND if the environment does not exist. +func (c *cloudShellRESTClient) GetEnvironment(ctx context.Context, req *shellpb.GetEnvironmentRequest, opts ...gax.CallOption) (*shellpb.Environment, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetEnvironment[0:len((*c.CallOptions).GetEnvironment):len((*c.CallOptions).GetEnvironment)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &shellpb.Environment{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// StartEnvironment starts an existing environment, allowing clients to connect to it. The +// returned operation will contain an instance of StartEnvironmentMetadata in +// its metadata field. Users can wait for the environment to start by polling +// this operation via GetOperation. Once the environment has finished starting +// and is ready to accept connections, the operation will contain a +// StartEnvironmentResponse in its response field. +func (c *cloudShellRESTClient) StartEnvironment(ctx context.Context, req *shellpb.StartEnvironmentRequest, opts ...gax.CallOption) (*StartEnvironmentOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:start", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &StartEnvironmentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// AuthorizeEnvironment sends OAuth credentials to a running environment on behalf of a user. When +// this completes, the environment will be authorized to run various Google +// Cloud command line tools without requiring the user to manually +// authenticate. +func (c *cloudShellRESTClient) AuthorizeEnvironment(ctx context.Context, req *shellpb.AuthorizeEnvironmentRequest, opts ...gax.CallOption) (*AuthorizeEnvironmentOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:authorize", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &AuthorizeEnvironmentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// AddPublicKey adds a public SSH key to an environment, allowing clients with the +// corresponding private key to connect to that environment via SSH. If a key +// with the same content already exists, this will error with ALREADY_EXISTS. +func (c *cloudShellRESTClient) AddPublicKey(ctx context.Context, req *shellpb.AddPublicKeyRequest, opts ...gax.CallOption) (*AddPublicKeyOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:addPublicKey", req.GetEnvironment()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "environment", url.QueryEscape(req.GetEnvironment()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &AddPublicKeyOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// RemovePublicKey removes a public SSH key from an environment. Clients will no longer be +// able to connect to the environment using the corresponding private key. +// If a key with the same content is not present, this will error with +// NOT_FOUND. +func (c *cloudShellRESTClient) RemovePublicKey(ctx context.Context, req *shellpb.RemovePublicKeyRequest, opts ...gax.CallOption) (*RemovePublicKeyOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:removePublicKey", req.GetEnvironment()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "environment", url.QueryEscape(req.GetEnvironment()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &RemovePublicKeyOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + // AddPublicKeyOperation manages a long-running operation from AddPublicKey. type AddPublicKeyOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // AddPublicKeyOperation returns a new AddPublicKeyOperation from a given name. @@ -438,10 +897,21 @@ func (c *cloudShellGRPCClient) AddPublicKeyOperation(name string) *AddPublicKeyO } } +// AddPublicKeyOperation returns a new AddPublicKeyOperation from a given name. +// The name must be that of a previously created AddPublicKeyOperation, possibly from a different process. +func (c *cloudShellRESTClient) AddPublicKeyOperation(name string) *AddPublicKeyOperation { + override := fmt.Sprintf("/v1/%s", name) + return &AddPublicKeyOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *AddPublicKeyOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*shellpb.AddPublicKeyResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp shellpb.AddPublicKeyResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -459,6 +929,7 @@ func (op *AddPublicKeyOperation) Wait(ctx context.Context, opts ...gax.CallOptio // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *AddPublicKeyOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*shellpb.AddPublicKeyResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp shellpb.AddPublicKeyResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -496,7 +967,8 @@ func (op *AddPublicKeyOperation) Name() string { // AuthorizeEnvironmentOperation manages a long-running operation from AuthorizeEnvironment. type AuthorizeEnvironmentOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // AuthorizeEnvironmentOperation returns a new AuthorizeEnvironmentOperation from a given name. @@ -507,10 +979,21 @@ func (c *cloudShellGRPCClient) AuthorizeEnvironmentOperation(name string) *Autho } } +// AuthorizeEnvironmentOperation returns a new AuthorizeEnvironmentOperation from a given name. +// The name must be that of a previously created AuthorizeEnvironmentOperation, possibly from a different process. +func (c *cloudShellRESTClient) AuthorizeEnvironmentOperation(name string) *AuthorizeEnvironmentOperation { + override := fmt.Sprintf("/v1/%s", name) + return &AuthorizeEnvironmentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *AuthorizeEnvironmentOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*shellpb.AuthorizeEnvironmentResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp shellpb.AuthorizeEnvironmentResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -528,6 +1011,7 @@ func (op *AuthorizeEnvironmentOperation) Wait(ctx context.Context, opts ...gax.C // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *AuthorizeEnvironmentOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*shellpb.AuthorizeEnvironmentResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp shellpb.AuthorizeEnvironmentResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -565,7 +1049,8 @@ func (op *AuthorizeEnvironmentOperation) Name() string { // RemovePublicKeyOperation manages a long-running operation from RemovePublicKey. type RemovePublicKeyOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // RemovePublicKeyOperation returns a new RemovePublicKeyOperation from a given name. @@ -576,10 +1061,21 @@ func (c *cloudShellGRPCClient) RemovePublicKeyOperation(name string) *RemovePubl } } +// RemovePublicKeyOperation returns a new RemovePublicKeyOperation from a given name. +// The name must be that of a previously created RemovePublicKeyOperation, possibly from a different process. +func (c *cloudShellRESTClient) RemovePublicKeyOperation(name string) *RemovePublicKeyOperation { + override := fmt.Sprintf("/v1/%s", name) + return &RemovePublicKeyOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *RemovePublicKeyOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*shellpb.RemovePublicKeyResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp shellpb.RemovePublicKeyResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -597,6 +1093,7 @@ func (op *RemovePublicKeyOperation) Wait(ctx context.Context, opts ...gax.CallOp // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *RemovePublicKeyOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*shellpb.RemovePublicKeyResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp shellpb.RemovePublicKeyResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -634,7 +1131,8 @@ func (op *RemovePublicKeyOperation) Name() string { // StartEnvironmentOperation manages a long-running operation from StartEnvironment. type StartEnvironmentOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // StartEnvironmentOperation returns a new StartEnvironmentOperation from a given name. @@ -645,10 +1143,21 @@ func (c *cloudShellGRPCClient) StartEnvironmentOperation(name string) *StartEnvi } } +// StartEnvironmentOperation returns a new StartEnvironmentOperation from a given name. +// The name must be that of a previously created StartEnvironmentOperation, possibly from a different process. +func (c *cloudShellRESTClient) StartEnvironmentOperation(name string) *StartEnvironmentOperation { + override := fmt.Sprintf("/v1/%s", name) + return &StartEnvironmentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *StartEnvironmentOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*shellpb.StartEnvironmentResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp shellpb.StartEnvironmentResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -666,6 +1175,7 @@ func (op *StartEnvironmentOperation) Wait(ctx context.Context, opts ...gax.CallO // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *StartEnvironmentOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*shellpb.StartEnvironmentResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp shellpb.StartEnvironmentResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/shell/apiv1/cloud_shell_client_example_test.go b/shell/apiv1/cloud_shell_client_example_test.go index 8dcae4ea4ed5..0b22deb83915 100644 --- a/shell/apiv1/cloud_shell_client_example_test.go +++ b/shell/apiv1/cloud_shell_client_example_test.go @@ -40,6 +40,23 @@ func ExampleNewCloudShellClient() { _ = c } +func ExampleNewCloudShellRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := shell.NewCloudShellRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleCloudShellClient_GetEnvironment() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/shell/apiv1/doc.go b/shell/apiv1/doc.go index 1806e8ad94a9..e4ee67c659e5 100644 --- a/shell/apiv1/doc.go +++ b/shell/apiv1/doc.go @@ -81,6 +81,8 @@ package shell // import "cloud.google.com/go/shell/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -169,3 +171,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/shell/apiv1/gapic_metadata.json b/shell/apiv1/gapic_metadata.json index 9f2bef8962e2..fe314e7d3d70 100644 --- a/shell/apiv1/gapic_metadata.json +++ b/shell/apiv1/gapic_metadata.json @@ -36,6 +36,36 @@ ] } } + }, + "rest": { + "libraryClient": "CloudShellClient", + "rpcs": { + "AddPublicKey": { + "methods": [ + "AddPublicKey" + ] + }, + "AuthorizeEnvironment": { + "methods": [ + "AuthorizeEnvironment" + ] + }, + "GetEnvironment": { + "methods": [ + "GetEnvironment" + ] + }, + "RemovePublicKey": { + "methods": [ + "RemovePublicKey" + ] + }, + "StartEnvironment": { + "methods": [ + "StartEnvironment" + ] + } + } } } } diff --git a/shell/apiv1/shellpb/cloudshell.pb.go b/shell/apiv1/shellpb/cloudshell.pb.go index 70fadee93c37..a104f7790b86 100644 --- a/shell/apiv1/shellpb/cloudshell.pb.go +++ b/shell/apiv1/shellpb/cloudshell.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/shell/v1/cloudshell.proto package shellpb diff --git a/spanner/admin/database/apiv1/database_admin_client.go b/spanner/admin/database/apiv1/database_admin_client.go index 2d9ba5fbf811..555cf923c466 100644 --- a/spanner/admin/database/apiv1/database_admin_client.go +++ b/spanner/admin/database/apiv1/database_admin_client.go @@ -17,9 +17,12 @@ package database import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,15 +30,18 @@ import ( lroauto "cloud.google.com/go/longrunning/autogen" databasepb "cloud.google.com/go/spanner/admin/database/apiv1/databasepb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" iampb "google.golang.org/genproto/googleapis/iam/v1" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -251,6 +257,164 @@ func defaultDatabaseAdminCallOptions() *DatabaseAdminCallOptions { } } +func defaultDatabaseAdminRESTCallOptions() *DatabaseAdminCallOptions { + return &DatabaseAdminCallOptions{ + ListDatabases: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 32000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + CreateDatabase: []gax.CallOption{}, + GetDatabase: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 32000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + UpdateDatabaseDdl: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 32000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + DropDatabase: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 32000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + GetDatabaseDdl: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 32000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + SetIamPolicy: []gax.CallOption{}, + GetIamPolicy: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 32000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + TestIamPermissions: []gax.CallOption{}, + CreateBackup: []gax.CallOption{}, + CopyBackup: []gax.CallOption{}, + GetBackup: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 32000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + UpdateBackup: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 32000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + DeleteBackup: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 32000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + ListBackups: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 32000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + RestoreDatabase: []gax.CallOption{}, + ListDatabaseOperations: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 32000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + ListBackupOperations: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 32000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + ListDatabaseRoles: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 32000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + CancelOperation: []gax.CallOption{}, + DeleteOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalDatabaseAdminClient is an interface that defines the methods available from Cloud Spanner API. type internalDatabaseAdminClient interface { Close() error @@ -688,6 +852,99 @@ func (c *databaseAdminGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type databaseAdminRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing DatabaseAdminClient + CallOptions **DatabaseAdminCallOptions +} + +// NewDatabaseAdminRESTClient creates a new database admin rest client. +// +// # Cloud Spanner Database Admin API +// +// The Cloud Spanner Database Admin API can be used to: +// +// create, drop, and list databases +// +// update the schema of pre-existing databases +// +// create, delete and list backups for a database +// +// restore a database from an existing backup +func NewDatabaseAdminRESTClient(ctx context.Context, opts ...option.ClientOption) (*DatabaseAdminClient, error) { + clientOpts := append(defaultDatabaseAdminRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultDatabaseAdminRESTCallOptions() + c := &databaseAdminRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &DatabaseAdminClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultDatabaseAdminRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://spanner.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://spanner.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://spanner.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *databaseAdminRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *databaseAdminRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *databaseAdminRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *databaseAdminGRPCClient) ListDatabases(ctx context.Context, req *databasepb.ListDatabasesRequest, opts ...gax.CallOption) *DatabaseIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1311,62 +1568,1714 @@ func (c *databaseAdminGRPCClient) ListOperations(ctx context.Context, req *longr return it } -// CopyBackupOperation manages a long-running operation from CopyBackup. -type CopyBackupOperation struct { - lro *longrunning.Operation -} +// ListDatabases lists Cloud Spanner databases. +func (c *databaseAdminRESTClient) ListDatabases(ctx context.Context, req *databasepb.ListDatabasesRequest, opts ...gax.CallOption) *DatabaseIterator { + it := &DatabaseIterator{} + req = proto.Clone(req).(*databasepb.ListDatabasesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*databasepb.Database, string, error) { + resp := &databasepb.ListDatabasesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/databases", req.GetParent()) -// CopyBackupOperation returns a new CopyBackupOperation from a given name. -// The name must be that of a previously created CopyBackupOperation, possibly from a different process. -func (c *databaseAdminGRPCClient) CopyBackupOperation(name string) *CopyBackupOperation { - return &CopyBackupOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetDatabases(), resp.GetNextPageToken(), nil } -} -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *CopyBackupOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*databasepb.Backup, error) { - var resp databasepb.Backup - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { - return nil, err + 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 } - return &resp, nil + + it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it } -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *CopyBackupOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*databasepb.Backup, error) { - var resp databasepb.Backup - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { +// CreateDatabase creates a new Cloud Spanner database and starts to prepare it for serving. +// The returned [long-running operation][google.longrunning.Operation] will +// have a name of the format /operations/ and +// can be used to track preparation of the database. The +// metadata field type is +// CreateDatabaseMetadata. The +// response field type is +// Database, if successful. +func (c *databaseAdminRESTClient) CreateDatabase(ctx context.Context, req *databasepb.CreateDatabaseRequest, opts ...gax.CallOption) (*CreateDatabaseOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { return nil, err } - if !op.Done() { - return nil, nil - } - return &resp, nil -} -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *CopyBackupOperation) Metadata() (*databasepb.CopyBackupMetadata, error) { - var meta databasepb.CopyBackupMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - return &meta, nil + baseUrl.Path += fmt.Sprintf("/v1/%v/databases", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateDatabaseOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetDatabase gets the state of a Cloud Spanner database. +func (c *databaseAdminRESTClient) GetDatabase(ctx context.Context, req *databasepb.GetDatabaseRequest, opts ...gax.CallOption) (*databasepb.Database, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetDatabase[0:len((*c.CallOptions).GetDatabase):len((*c.CallOptions).GetDatabase)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &databasepb.Database{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateDatabaseDdl updates the schema of a Cloud Spanner database by +// creating/altering/dropping tables, columns, indexes, etc. The returned +// [long-running operation][google.longrunning.Operation] will have a name of +// the format /operations/ and can be used to +// track execution of the schema change(s). The +// metadata field type is +// UpdateDatabaseDdlMetadata. The operation has no response. +func (c *databaseAdminRESTClient) UpdateDatabaseDdl(ctx context.Context, req *databasepb.UpdateDatabaseDdlRequest, opts ...gax.CallOption) (*UpdateDatabaseDdlOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/ddl", req.GetDatabase()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "database", url.QueryEscape(req.GetDatabase()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateDatabaseDdlOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DropDatabase drops (aka deletes) a Cloud Spanner database. +// Completed backups for the database will be retained according to their +// expire_time. +// Note: Cloud Spanner might continue to accept requests for a few seconds +// after the database has been deleted. +func (c *databaseAdminRESTClient) DropDatabase(ctx context.Context, req *databasepb.DropDatabaseRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetDatabase()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "database", url.QueryEscape(req.GetDatabase()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetDatabaseDdl returns the schema of a Cloud Spanner database as a list of formatted +// DDL statements. This method does not show pending schema updates, those may +// be queried using the Operations API. +func (c *databaseAdminRESTClient) GetDatabaseDdl(ctx context.Context, req *databasepb.GetDatabaseDdlRequest, opts ...gax.CallOption) (*databasepb.GetDatabaseDdlResponse, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/ddl", req.GetDatabase()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "database", url.QueryEscape(req.GetDatabase()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetDatabaseDdl[0:len((*c.CallOptions).GetDatabaseDdl):len((*c.CallOptions).GetDatabaseDdl)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &databasepb.GetDatabaseDdlResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SetIamPolicy sets the access control policy on a database or backup resource. +// Replaces any existing policy. +// +// Authorization requires spanner.databases.setIamPolicy +// permission on resource. +// For backups, authorization requires spanner.backups.setIamPolicy +// permission on resource. +func (c *databaseAdminRESTClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:setIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetIamPolicy gets the access control policy for a database or backup resource. +// Returns an empty policy if a database or backup exists but does not have a +// policy set. +// +// Authorization requires spanner.databases.getIamPolicy permission on +// resource. +// For backups, authorization requires spanner.backups.getIamPolicy +// permission on resource. +func (c *databaseAdminRESTClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:getIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// TestIamPermissions returns permissions that the caller has on the specified database or backup +// resource. +// +// Attempting this RPC on a non-existent Cloud Spanner database will +// result in a NOT_FOUND error if the user has +// spanner.databases.list permission on the containing Cloud +// Spanner instance. Otherwise returns an empty set of permissions. +// Calling this method on a backup that does not exist will +// result in a NOT_FOUND error if the user has +// spanner.backups.list permission on the containing instance. +func (c *databaseAdminRESTClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:testIamPermissions", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.TestIamPermissionsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateBackup starts creating a new Cloud Spanner Backup. +// The returned backup [long-running operation][google.longrunning.Operation] +// will have a name of the format +// projects//instances//backups//operations/ +// and can be used to track creation of the backup. The +// metadata field type is +// CreateBackupMetadata. The +// response field type is +// Backup, if successful. Cancelling the returned operation will stop the +// creation and delete the backup. +// There can be only one pending backup creation per database. Backup creation +// of different databases can run concurrently. +func (c *databaseAdminRESTClient) CreateBackup(ctx context.Context, req *databasepb.CreateBackupRequest, opts ...gax.CallOption) (*CreateBackupOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetBackup() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/backups", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("backupId", fmt.Sprintf("%v", req.GetBackupId())) + params.Add("encryptionConfig.encryptionType", fmt.Sprintf("%v", req.GetEncryptionConfig().GetEncryptionType())) + if req.GetEncryptionConfig().GetKmsKeyName() != "" { + params.Add("encryptionConfig.kmsKeyName", fmt.Sprintf("%v", req.GetEncryptionConfig().GetKmsKeyName())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateBackupOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// CopyBackup starts copying a Cloud Spanner Backup. +// The returned backup [long-running operation][google.longrunning.Operation] +// will have a name of the format +// projects//instances//backups//operations/ +// and can be used to track copying of the backup. The operation is associated +// with the destination backup. +// The metadata field type is +// CopyBackupMetadata. +// The response field type is +// Backup, if successful. Cancelling the returned operation will stop the +// copying and delete the backup. +// Concurrent CopyBackup requests can run on the same source backup. +func (c *databaseAdminRESTClient) CopyBackup(ctx context.Context, req *databasepb.CopyBackupRequest, opts ...gax.CallOption) (*CopyBackupOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/backups:copy", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CopyBackupOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetBackup gets metadata on a pending or completed Backup. +func (c *databaseAdminRESTClient) GetBackup(ctx context.Context, req *databasepb.GetBackupRequest, opts ...gax.CallOption) (*databasepb.Backup, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetBackup[0:len((*c.CallOptions).GetBackup):len((*c.CallOptions).GetBackup)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &databasepb.Backup{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateBackup updates a pending or completed Backup. +func (c *databaseAdminRESTClient) UpdateBackup(ctx context.Context, req *databasepb.UpdateBackupRequest, opts ...gax.CallOption) (*databasepb.Backup, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetBackup() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetBackup().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "backup.name", url.QueryEscape(req.GetBackup().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateBackup[0:len((*c.CallOptions).UpdateBackup):len((*c.CallOptions).UpdateBackup)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &databasepb.Backup{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteBackup deletes a pending or completed Backup. +func (c *databaseAdminRESTClient) DeleteBackup(ctx context.Context, req *databasepb.DeleteBackupRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// ListBackups lists completed and pending backups. +// Backups returned are ordered by create_time in descending order, +// starting from the most recent create_time. +func (c *databaseAdminRESTClient) ListBackups(ctx context.Context, req *databasepb.ListBackupsRequest, opts ...gax.CallOption) *BackupIterator { + it := &BackupIterator{} + req = proto.Clone(req).(*databasepb.ListBackupsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*databasepb.Backup, string, error) { + resp := &databasepb.ListBackupsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/backups", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetBackups(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// RestoreDatabase create a new database by restoring from a completed backup. The new +// database must be in the same project and in an instance with the same +// instance configuration as the instance containing +// the backup. The returned database [long-running +// operation][google.longrunning.Operation] has a name of the format +// projects//instances//databases//operations/, +// and can be used to track the progress of the operation, and to cancel it. +// The metadata field type is +// RestoreDatabaseMetadata. +// The response type +// is Database, if +// successful. Cancelling the returned operation will stop the restore and +// delete the database. +// There can be only one database being restored into an instance at a time. +// Once the restore operation completes, a new restore operation can be +// initiated, without waiting for the optimize operation associated with the +// first restore to complete. +func (c *databaseAdminRESTClient) RestoreDatabase(ctx context.Context, req *databasepb.RestoreDatabaseRequest, opts ...gax.CallOption) (*RestoreDatabaseOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/databases:restore", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &RestoreDatabaseOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListDatabaseOperations lists database [longrunning-operations][google.longrunning.Operation]. +// A database operation has a name of the form +// projects//instances//databases//operations/. +// The long-running operation +// metadata field type +// metadata.type_url describes the type of the metadata. Operations returned +// include those that have completed/failed/canceled within the last 7 days, +// and pending operations. +func (c *databaseAdminRESTClient) ListDatabaseOperations(ctx context.Context, req *databasepb.ListDatabaseOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*databasepb.ListDatabaseOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &databasepb.ListDatabaseOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/databaseOperations", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// ListBackupOperations lists the backup [long-running operations][google.longrunning.Operation] in +// the given instance. A backup operation has a name of the form +// projects//instances//backups//operations/. +// The long-running operation +// metadata field type +// metadata.type_url describes the type of the metadata. Operations returned +// include those that have completed/failed/canceled within the last 7 days, +// and pending operations. Operations returned are ordered by +// operation.metadata.value.progress.start_time in descending order starting +// from the most recently started operation. +func (c *databaseAdminRESTClient) ListBackupOperations(ctx context.Context, req *databasepb.ListBackupOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*databasepb.ListBackupOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &databasepb.ListBackupOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/backupOperations", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// ListDatabaseRoles lists Cloud Spanner database roles. +func (c *databaseAdminRESTClient) ListDatabaseRoles(ctx context.Context, req *databasepb.ListDatabaseRolesRequest, opts ...gax.CallOption) *DatabaseRoleIterator { + it := &DatabaseRoleIterator{} + req = proto.Clone(req).(*databasepb.ListDatabaseRolesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*databasepb.DatabaseRole, string, error) { + resp := &databasepb.ListDatabaseRolesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/databaseRoles", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetDatabaseRoles(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *databaseAdminRESTClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// DeleteOperation is a utility method from google.longrunning.Operations. +func (c *databaseAdminRESTClient) DeleteOperation(ctx context.Context, req *longrunningpb.DeleteOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *databaseAdminRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *databaseAdminRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CopyBackupOperation manages a long-running operation from CopyBackup. +type CopyBackupOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CopyBackupOperation returns a new CopyBackupOperation from a given name. +// The name must be that of a previously created CopyBackupOperation, possibly from a different process. +func (c *databaseAdminGRPCClient) CopyBackupOperation(name string) *CopyBackupOperation { + return &CopyBackupOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CopyBackupOperation returns a new CopyBackupOperation from a given name. +// The name must be that of a previously created CopyBackupOperation, possibly from a different process. +func (c *databaseAdminRESTClient) CopyBackupOperation(name string) *CopyBackupOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CopyBackupOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CopyBackupOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*databasepb.Backup, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp databasepb.Backup + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *CopyBackupOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*databasepb.Backup, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp databasepb.Backup + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *CopyBackupOperation) Metadata() (*databasepb.CopyBackupMetadata, error) { + var meta databasepb.CopyBackupMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil } // Done reports whether the long-running operation has completed. @@ -1382,7 +3291,8 @@ func (op *CopyBackupOperation) Name() string { // CreateBackupOperation manages a long-running operation from CreateBackup. type CreateBackupOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateBackupOperation returns a new CreateBackupOperation from a given name. @@ -1393,10 +3303,21 @@ func (c *databaseAdminGRPCClient) CreateBackupOperation(name string) *CreateBack } } +// CreateBackupOperation returns a new CreateBackupOperation from a given name. +// The name must be that of a previously created CreateBackupOperation, possibly from a different process. +func (c *databaseAdminRESTClient) CreateBackupOperation(name string) *CreateBackupOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateBackupOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateBackupOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*databasepb.Backup, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp databasepb.Backup if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1414,6 +3335,7 @@ func (op *CreateBackupOperation) Wait(ctx context.Context, opts ...gax.CallOptio // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateBackupOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*databasepb.Backup, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp databasepb.Backup if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1451,7 +3373,8 @@ func (op *CreateBackupOperation) Name() string { // CreateDatabaseOperation manages a long-running operation from CreateDatabase. type CreateDatabaseOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateDatabaseOperation returns a new CreateDatabaseOperation from a given name. @@ -1462,10 +3385,21 @@ func (c *databaseAdminGRPCClient) CreateDatabaseOperation(name string) *CreateDa } } +// CreateDatabaseOperation returns a new CreateDatabaseOperation from a given name. +// The name must be that of a previously created CreateDatabaseOperation, possibly from a different process. +func (c *databaseAdminRESTClient) CreateDatabaseOperation(name string) *CreateDatabaseOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateDatabaseOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateDatabaseOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*databasepb.Database, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp databasepb.Database if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1483,6 +3417,7 @@ func (op *CreateDatabaseOperation) Wait(ctx context.Context, opts ...gax.CallOpt // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateDatabaseOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*databasepb.Database, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp databasepb.Database if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1520,7 +3455,8 @@ func (op *CreateDatabaseOperation) Name() string { // RestoreDatabaseOperation manages a long-running operation from RestoreDatabase. type RestoreDatabaseOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // RestoreDatabaseOperation returns a new RestoreDatabaseOperation from a given name. @@ -1531,10 +3467,21 @@ func (c *databaseAdminGRPCClient) RestoreDatabaseOperation(name string) *Restore } } +// RestoreDatabaseOperation returns a new RestoreDatabaseOperation from a given name. +// The name must be that of a previously created RestoreDatabaseOperation, possibly from a different process. +func (c *databaseAdminRESTClient) RestoreDatabaseOperation(name string) *RestoreDatabaseOperation { + override := fmt.Sprintf("/v1/%s", name) + return &RestoreDatabaseOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *RestoreDatabaseOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*databasepb.Database, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp databasepb.Database if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1552,6 +3499,7 @@ func (op *RestoreDatabaseOperation) Wait(ctx context.Context, opts ...gax.CallOp // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *RestoreDatabaseOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*databasepb.Database, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp databasepb.Database if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1589,7 +3537,8 @@ func (op *RestoreDatabaseOperation) Name() string { // UpdateDatabaseDdlOperation manages a long-running operation from UpdateDatabaseDdl. type UpdateDatabaseDdlOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateDatabaseDdlOperation returns a new UpdateDatabaseDdlOperation from a given name. @@ -1600,10 +3549,21 @@ func (c *databaseAdminGRPCClient) UpdateDatabaseDdlOperation(name string) *Updat } } +// UpdateDatabaseDdlOperation returns a new UpdateDatabaseDdlOperation from a given name. +// The name must be that of a previously created UpdateDatabaseDdlOperation, possibly from a different process. +func (c *databaseAdminRESTClient) UpdateDatabaseDdlOperation(name string) *UpdateDatabaseDdlOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateDatabaseDdlOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateDatabaseDdlOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -1617,6 +3577,7 @@ func (op *UpdateDatabaseDdlOperation) Wait(ctx context.Context, opts ...gax.Call // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateDatabaseDdlOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } diff --git a/spanner/admin/database/apiv1/database_admin_client_example_test.go b/spanner/admin/database/apiv1/database_admin_client_example_test.go index 1824a502617d..2faa7adc08bb 100644 --- a/spanner/admin/database/apiv1/database_admin_client_example_test.go +++ b/spanner/admin/database/apiv1/database_admin_client_example_test.go @@ -43,6 +43,23 @@ func ExampleNewDatabaseAdminClient() { _ = c } +func ExampleNewDatabaseAdminRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := database.NewDatabaseAdminRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleDatabaseAdminClient_ListDatabases() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/spanner/admin/database/apiv1/databasepb/backup.pb.go b/spanner/admin/database/apiv1/databasepb/backup.pb.go index 675c169b4990..c93a07273dfa 100644 --- a/spanner/admin/database/apiv1/databasepb/backup.pb.go +++ b/spanner/admin/database/apiv1/databasepb/backup.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/spanner/admin/database/v1/backup.proto package databasepb @@ -785,7 +785,7 @@ type UpdateBackupRequest struct { // Required. The backup to update. `backup.name`, and the fields to be updated // as specified by `update_mask` are required. Other fields are ignored. // Update is only supported for the following fields: - // - `backup.expire_time`. + // * `backup.expire_time`. Backup *Backup `protobuf:"bytes,1,opt,name=backup,proto3" json:"backup,omitempty"` // Required. A mask specifying which fields (e.g. `expire_time`) in the // Backup resource should be updated. This mask is relative to the Backup @@ -962,13 +962,13 @@ type ListBackupsRequest struct { // // The following fields in the [Backup][google.spanner.admin.database.v1.Backup] are eligible for filtering: // - // - `name` - // - `database` - // - `state` - // - `create_time` (and values are of the format YYYY-MM-DDTHH:MM:SSZ) - // - `expire_time` (and values are of the format YYYY-MM-DDTHH:MM:SSZ) - // - `version_time` (and values are of the format YYYY-MM-DDTHH:MM:SSZ) - // - `size_bytes` + // * `name` + // * `database` + // * `state` + // * `create_time` (and values are of the format YYYY-MM-DDTHH:MM:SSZ) + // * `expire_time` (and values are of the format YYYY-MM-DDTHH:MM:SSZ) + // * `version_time` (and values are of the format YYYY-MM-DDTHH:MM:SSZ) + // * `size_bytes` // // You can combine multiple expressions by enclosing each expression in // parentheses. By default, expressions are combined with AND logic, but @@ -976,17 +976,17 @@ type ListBackupsRequest struct { // // Here are a few examples: // - // - `name:Howl` - The backup's name contains the string "howl". - // - `database:prod` - // - The database's name contains the string "prod". - // - `state:CREATING` - The backup is pending creation. - // - `state:READY` - The backup is fully created and ready for use. - // - `(name:howl) AND (create_time < \"2018-03-28T14:50:00Z\")` - // - The backup name contains the string "howl" and `create_time` - // of the backup is before 2018-03-28T14:50:00Z. - // - `expire_time < \"2018-03-28T14:50:00Z\"` - // - The backup `expire_time` is before 2018-03-28T14:50:00Z. - // - `size_bytes > 10000000000` - The backup's size is greater than 10GB + // * `name:Howl` - The backup's name contains the string "howl". + // * `database:prod` + // - The database's name contains the string "prod". + // * `state:CREATING` - The backup is pending creation. + // * `state:READY` - The backup is fully created and ready for use. + // * `(name:howl) AND (create_time < \"2018-03-28T14:50:00Z\")` + // - The backup name contains the string "howl" and `create_time` + // of the backup is before 2018-03-28T14:50:00Z. + // * `expire_time < \"2018-03-28T14:50:00Z\"` + // - The backup `expire_time` is before 2018-03-28T14:50:00Z. + // * `size_bytes > 10000000000` - The backup's size is greater than 10GB Filter string `protobuf:"bytes,2,opt,name=filter,proto3" json:"filter,omitempty"` // Number of backups to be returned in the response. If 0 or // less, defaults to the server's maximum allowed page size. @@ -1140,17 +1140,17 @@ type ListBackupOperationsRequest struct { // The following fields in the [operation][google.longrunning.Operation] // are eligible for filtering: // - // - `name` - The name of the long-running operation - // - `done` - False if the operation is in progress, else true. - // - `metadata.@type` - the type of metadata. For example, the type string - // for [CreateBackupMetadata][google.spanner.admin.database.v1.CreateBackupMetadata] is - // `type.googleapis.com/google.spanner.admin.database.v1.CreateBackupMetadata`. - // - `metadata.` - any field in metadata.value. - // `metadata.@type` must be specified first if filtering on metadata - // fields. - // - `error` - Error associated with the long-running operation. - // - `response.@type` - the type of response. - // - `response.` - any field in response.value. + // * `name` - The name of the long-running operation + // * `done` - False if the operation is in progress, else true. + // * `metadata.@type` - the type of metadata. For example, the type string + // for [CreateBackupMetadata][google.spanner.admin.database.v1.CreateBackupMetadata] is + // `type.googleapis.com/google.spanner.admin.database.v1.CreateBackupMetadata`. + // * `metadata.` - any field in metadata.value. + // `metadata.@type` must be specified first if filtering on metadata + // fields. + // * `error` - Error associated with the long-running operation. + // * `response.@type` - the type of response. + // * `response.` - any field in response.value. // // You can combine multiple expressions by enclosing each expression in // parentheses. By default, expressions are combined with AND logic, but @@ -1158,43 +1158,43 @@ type ListBackupOperationsRequest struct { // // Here are a few examples: // - // - `done:true` - The operation is complete. - // - `(metadata.@type=type.googleapis.com/google.spanner.admin.database.v1.CreateBackupMetadata) AND` \ - // `metadata.database:prod` - Returns operations where: - // - The operation's metadata type is [CreateBackupMetadata][google.spanner.admin.database.v1.CreateBackupMetadata]. - // - The database the backup was taken from has a name containing the - // string "prod". - // - `(metadata.@type=type.googleapis.com/google.spanner.admin.database.v1.CreateBackupMetadata) AND` \ + // * `done:true` - The operation is complete. + // * `(metadata.@type=type.googleapis.com/google.spanner.admin.database.v1.CreateBackupMetadata) AND` \ + // `metadata.database:prod` - Returns operations where: + // * The operation's metadata type is [CreateBackupMetadata][google.spanner.admin.database.v1.CreateBackupMetadata]. + // * The database the backup was taken from has a name containing the + // string "prod". + // * `(metadata.@type=type.googleapis.com/google.spanner.admin.database.v1.CreateBackupMetadata) AND` \ // `(metadata.name:howl) AND` \ // `(metadata.progress.start_time < \"2018-03-28T14:50:00Z\") AND` \ // `(error:*)` - Returns operations where: - // - The operation's metadata type is [CreateBackupMetadata][google.spanner.admin.database.v1.CreateBackupMetadata]. - // - The backup name contains the string "howl". - // - The operation started before 2018-03-28T14:50:00Z. - // - The operation resulted in an error. - // - `(metadata.@type=type.googleapis.com/google.spanner.admin.database.v1.CopyBackupMetadata) AND` \ + // * The operation's metadata type is [CreateBackupMetadata][google.spanner.admin.database.v1.CreateBackupMetadata]. + // * The backup name contains the string "howl". + // * The operation started before 2018-03-28T14:50:00Z. + // * The operation resulted in an error. + // * `(metadata.@type=type.googleapis.com/google.spanner.admin.database.v1.CopyBackupMetadata) AND` \ // `(metadata.source_backup:test) AND` \ // `(metadata.progress.start_time < \"2022-01-18T14:50:00Z\") AND` \ // `(error:*)` - Returns operations where: - // - The operation's metadata type is [CopyBackupMetadata][google.spanner.admin.database.v1.CopyBackupMetadata]. - // - The source backup of the copied backup name contains the string + // * The operation's metadata type is [CopyBackupMetadata][google.spanner.admin.database.v1.CopyBackupMetadata]. + // * The source backup of the copied backup name contains the string // "test". - // - The operation started before 2022-01-18T14:50:00Z. - // - The operation resulted in an error. - // - `((metadata.@type=type.googleapis.com/google.spanner.admin.database.v1.CreateBackupMetadata) AND` \ + // * The operation started before 2022-01-18T14:50:00Z. + // * The operation resulted in an error. + // * `((metadata.@type=type.googleapis.com/google.spanner.admin.database.v1.CreateBackupMetadata) AND` \ // `(metadata.database:test_db)) OR` \ // `((metadata.@type=type.googleapis.com/google.spanner.admin.database.v1.CopyBackupMetadata) // AND` \ // `(metadata.source_backup:test_bkp)) AND` \ // `(error:*)` - Returns operations where: - // - The operation's metadata matches either of criteria: - // - The operation's metadata type is [CreateBackupMetadata][google.spanner.admin.database.v1.CreateBackupMetadata] AND the - // database the backup was taken from has name containing string - // "test_db" - // - The operation's metadata type is [CopyBackupMetadata][google.spanner.admin.database.v1.CopyBackupMetadata] AND the - // backup the backup was copied from has name containing string - // "test_bkp" - // - The operation resulted in an error. + // * The operation's metadata matches either of criteria: + // * The operation's metadata type is [CreateBackupMetadata][google.spanner.admin.database.v1.CreateBackupMetadata] AND the + // database the backup was taken from has name containing string + // "test_db" + // * The operation's metadata type is [CopyBackupMetadata][google.spanner.admin.database.v1.CopyBackupMetadata] AND the + // backup the backup was copied from has name containing string + // "test_bkp" + // * The operation resulted in an error. Filter string `protobuf:"bytes,2,opt,name=filter,proto3" json:"filter,omitempty"` // Number of operations to be returned in the response. If 0 or // less, defaults to the server's maximum allowed page size. diff --git a/spanner/admin/database/apiv1/databasepb/common.pb.go b/spanner/admin/database/apiv1/databasepb/common.pb.go index 60df29379c86..2b40e87176ba 100644 --- a/spanner/admin/database/apiv1/databasepb/common.pb.go +++ b/spanner/admin/database/apiv1/databasepb/common.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/spanner/admin/database/v1/common.proto package databasepb diff --git a/spanner/admin/database/apiv1/databasepb/spanner_database_admin.pb.go b/spanner/admin/database/apiv1/databasepb/spanner_database_admin.pb.go index 6661574a1c0b..afc8ec282ef8 100644 --- a/spanner/admin/database/apiv1/databasepb/spanner_database_admin.pb.go +++ b/spanner/admin/database/apiv1/databasepb/spanner_database_admin.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/spanner/admin/database/v1/spanner_database_admin.proto package databasepb @@ -228,7 +228,6 @@ type RestoreInfo struct { // Information about the source used to restore the database. // // Types that are assignable to SourceInfo: - // // *RestoreInfo_BackupInfo SourceInfo isRestoreInfo_SourceInfo `protobuf_oneof:"source_info"` } @@ -601,7 +600,7 @@ type CreateDatabaseRequest struct { // new database. The database ID must conform to the regular expression // `[a-z][a-z0-9_\-]*[a-z0-9]` and be between 2 and 30 characters in length. // If the database ID is a reserved word or if it contains a hyphen, the - // database ID must be enclosed in backticks (“ ` “). + // database ID must be enclosed in backticks (`` ` ``). CreateStatement string `protobuf:"bytes,2,opt,name=create_statement,json=createStatement,proto3" json:"create_statement,omitempty"` // Optional. A list of DDL statements to run inside the newly created // database. Statements can create tables, indexes, etc. These @@ -1152,17 +1151,17 @@ type ListDatabaseOperationsRequest struct { // The following fields in the [Operation][google.longrunning.Operation] // are eligible for filtering: // - // - `name` - The name of the long-running operation - // - `done` - False if the operation is in progress, else true. - // - `metadata.@type` - the type of metadata. For example, the type string - // for [RestoreDatabaseMetadata][google.spanner.admin.database.v1.RestoreDatabaseMetadata] is - // `type.googleapis.com/google.spanner.admin.database.v1.RestoreDatabaseMetadata`. - // - `metadata.` - any field in metadata.value. - // `metadata.@type` must be specified first, if filtering on metadata - // fields. - // - `error` - Error associated with the long-running operation. - // - `response.@type` - the type of response. - // - `response.` - any field in response.value. + // * `name` - The name of the long-running operation + // * `done` - False if the operation is in progress, else true. + // * `metadata.@type` - the type of metadata. For example, the type string + // for [RestoreDatabaseMetadata][google.spanner.admin.database.v1.RestoreDatabaseMetadata] is + // `type.googleapis.com/google.spanner.admin.database.v1.RestoreDatabaseMetadata`. + // * `metadata.` - any field in metadata.value. + // `metadata.@type` must be specified first, if filtering on metadata + // fields. + // * `error` - Error associated with the long-running operation. + // * `response.@type` - the type of response. + // * `response.` - any field in response.value. // // You can combine multiple expressions by enclosing each expression in // parentheses. By default, expressions are combined with AND logic. However, @@ -1170,19 +1169,19 @@ type ListDatabaseOperationsRequest struct { // // Here are a few examples: // - // - `done:true` - The operation is complete. - // - `(metadata.@type=type.googleapis.com/google.spanner.admin.database.v1.RestoreDatabaseMetadata) AND` \ + // * `done:true` - The operation is complete. + // * `(metadata.@type=type.googleapis.com/google.spanner.admin.database.v1.RestoreDatabaseMetadata) AND` \ // `(metadata.source_type:BACKUP) AND` \ // `(metadata.backup_info.backup:backup_howl) AND` \ // `(metadata.name:restored_howl) AND` \ // `(metadata.progress.start_time < \"2018-03-28T14:50:00Z\") AND` \ // `(error:*)` - Return operations where: - // - The operation's metadata type is [RestoreDatabaseMetadata][google.spanner.admin.database.v1.RestoreDatabaseMetadata]. - // - The database is restored from a backup. - // - The backup name contains "backup_howl". - // - The restored database's name contains "restored_howl". - // - The operation started before 2018-03-28T14:50:00Z. - // - The operation resulted in an error. + // * The operation's metadata type is [RestoreDatabaseMetadata][google.spanner.admin.database.v1.RestoreDatabaseMetadata]. + // * The database is restored from a backup. + // * The backup name contains "backup_howl". + // * The restored database's name contains "restored_howl". + // * The operation started before 2018-03-28T14:50:00Z. + // * The operation resulted in an error. Filter string `protobuf:"bytes,2,opt,name=filter,proto3" json:"filter,omitempty"` // Number of operations to be returned in the response. If 0 or // less, defaults to the server's maximum allowed page size. @@ -1340,7 +1339,6 @@ type RestoreDatabaseRequest struct { // Required. The source from which to restore. // // Types that are assignable to Source: - // // *RestoreDatabaseRequest_Backup Source isRestoreDatabaseRequest_Source `protobuf_oneof:"source"` // Optional. An encryption configuration describing the encryption type and key @@ -1508,7 +1506,6 @@ type RestoreDatabaseMetadata struct { // `source` in [RestoreDatabaseRequest][google.spanner.admin.database.v1.RestoreDatabaseRequest]. // // Types that are assignable to SourceInfo: - // // *RestoreDatabaseMetadata_BackupInfo SourceInfo isRestoreDatabaseMetadata_SourceInfo `protobuf_oneof:"source_info"` // The progress of the diff --git a/spanner/admin/database/apiv1/doc.go b/spanner/admin/database/apiv1/doc.go index 1a098ddb0311..9ff077a96af8 100644 --- a/spanner/admin/database/apiv1/doc.go +++ b/spanner/admin/database/apiv1/doc.go @@ -87,6 +87,8 @@ package database // import "cloud.google.com/go/spanner/admin/database/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -176,3 +178,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/spanner/admin/database/apiv1/gapic_metadata.json b/spanner/admin/database/apiv1/gapic_metadata.json index dbc6307230f7..6441c94bc7f3 100644 --- a/spanner/admin/database/apiv1/gapic_metadata.json +++ b/spanner/admin/database/apiv1/gapic_metadata.json @@ -126,6 +126,126 @@ ] } } + }, + "rest": { + "libraryClient": "DatabaseAdminClient", + "rpcs": { + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "CopyBackup": { + "methods": [ + "CopyBackup" + ] + }, + "CreateBackup": { + "methods": [ + "CreateBackup" + ] + }, + "CreateDatabase": { + "methods": [ + "CreateDatabase" + ] + }, + "DeleteBackup": { + "methods": [ + "DeleteBackup" + ] + }, + "DeleteOperation": { + "methods": [ + "DeleteOperation" + ] + }, + "DropDatabase": { + "methods": [ + "DropDatabase" + ] + }, + "GetBackup": { + "methods": [ + "GetBackup" + ] + }, + "GetDatabase": { + "methods": [ + "GetDatabase" + ] + }, + "GetDatabaseDdl": { + "methods": [ + "GetDatabaseDdl" + ] + }, + "GetIamPolicy": { + "methods": [ + "GetIamPolicy" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ListBackupOperations": { + "methods": [ + "ListBackupOperations" + ] + }, + "ListBackups": { + "methods": [ + "ListBackups" + ] + }, + "ListDatabaseOperations": { + "methods": [ + "ListDatabaseOperations" + ] + }, + "ListDatabaseRoles": { + "methods": [ + "ListDatabaseRoles" + ] + }, + "ListDatabases": { + "methods": [ + "ListDatabases" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "RestoreDatabase": { + "methods": [ + "RestoreDatabase" + ] + }, + "SetIamPolicy": { + "methods": [ + "SetIamPolicy" + ] + }, + "TestIamPermissions": { + "methods": [ + "TestIamPermissions" + ] + }, + "UpdateBackup": { + "methods": [ + "UpdateBackup" + ] + }, + "UpdateDatabaseDdl": { + "methods": [ + "UpdateDatabaseDdl" + ] + } + } } } } diff --git a/spanner/admin/instance/apiv1/doc.go b/spanner/admin/instance/apiv1/doc.go index cb134c37f71b..5bd753d1402f 100644 --- a/spanner/admin/instance/apiv1/doc.go +++ b/spanner/admin/instance/apiv1/doc.go @@ -84,6 +84,8 @@ package instance // import "cloud.google.com/go/spanner/admin/instance/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -173,3 +175,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/spanner/admin/instance/apiv1/gapic_metadata.json b/spanner/admin/instance/apiv1/gapic_metadata.json index dc9d71886cd7..ee616c6be0b1 100644 --- a/spanner/admin/instance/apiv1/gapic_metadata.json +++ b/spanner/admin/instance/apiv1/gapic_metadata.json @@ -81,6 +81,81 @@ ] } } + }, + "rest": { + "libraryClient": "InstanceAdminClient", + "rpcs": { + "CreateInstance": { + "methods": [ + "CreateInstance" + ] + }, + "CreateInstanceConfig": { + "methods": [ + "CreateInstanceConfig" + ] + }, + "DeleteInstance": { + "methods": [ + "DeleteInstance" + ] + }, + "DeleteInstanceConfig": { + "methods": [ + "DeleteInstanceConfig" + ] + }, + "GetIamPolicy": { + "methods": [ + "GetIamPolicy" + ] + }, + "GetInstance": { + "methods": [ + "GetInstance" + ] + }, + "GetInstanceConfig": { + "methods": [ + "GetInstanceConfig" + ] + }, + "ListInstanceConfigOperations": { + "methods": [ + "ListInstanceConfigOperations" + ] + }, + "ListInstanceConfigs": { + "methods": [ + "ListInstanceConfigs" + ] + }, + "ListInstances": { + "methods": [ + "ListInstances" + ] + }, + "SetIamPolicy": { + "methods": [ + "SetIamPolicy" + ] + }, + "TestIamPermissions": { + "methods": [ + "TestIamPermissions" + ] + }, + "UpdateInstance": { + "methods": [ + "UpdateInstance" + ] + }, + "UpdateInstanceConfig": { + "methods": [ + "UpdateInstanceConfig" + ] + } + } } } } diff --git a/spanner/admin/instance/apiv1/instance_admin_client.go b/spanner/admin/instance/apiv1/instance_admin_client.go index 49b2db4f27af..c7d2dd379b19 100644 --- a/spanner/admin/instance/apiv1/instance_admin_client.go +++ b/spanner/admin/instance/apiv1/instance_admin_client.go @@ -17,9 +17,12 @@ package instance import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,15 +30,18 @@ import ( lroauto "cloud.google.com/go/longrunning/autogen" instancepb "cloud.google.com/go/spanner/admin/instance/apiv1/instancepb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" iampb "google.golang.org/genproto/googleapis/iam/v1" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -156,6 +162,85 @@ func defaultInstanceAdminCallOptions() *InstanceAdminCallOptions { } } +func defaultInstanceAdminRESTCallOptions() *InstanceAdminCallOptions { + return &InstanceAdminCallOptions{ + ListInstanceConfigs: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 32000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + GetInstanceConfig: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 32000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + CreateInstanceConfig: []gax.CallOption{}, + UpdateInstanceConfig: []gax.CallOption{}, + DeleteInstanceConfig: []gax.CallOption{}, + ListInstanceConfigOperations: []gax.CallOption{}, + ListInstances: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 32000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + GetInstance: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 32000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + CreateInstance: []gax.CallOption{}, + UpdateInstance: []gax.CallOption{}, + DeleteInstance: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 32000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + SetIamPolicy: []gax.CallOption{}, + GetIamPolicy: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 32000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + TestIamPermissions: []gax.CallOption{}, + } +} + // internalInstanceAdminClient is an interface that defines the methods available from Cloud Spanner Instance Admin API. type internalInstanceAdminClient interface { Close() error @@ -662,6 +747,109 @@ func (c *instanceAdminGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type instanceAdminRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing InstanceAdminClient + CallOptions **InstanceAdminCallOptions +} + +// NewInstanceAdminRESTClient creates a new instance admin rest client. +// +// # Cloud Spanner Instance Admin API +// +// The Cloud Spanner Instance Admin API can be used to create, delete, +// modify and list instances. Instances are dedicated Cloud Spanner serving +// and storage resources to be used by Cloud Spanner databases. +// +// Each instance has a “configuration”, which dictates where the +// serving resources for the Cloud Spanner instance are located (e.g., +// US-central, Europe). Configurations are created by Google based on +// resource availability. +// +// Cloud Spanner billing is based on the instances that exist and their +// sizes. After an instance exists, there are no additional +// per-database or per-operation charges for use of the instance +// (though there may be additional network bandwidth charges). +// Instances offer isolation: problems with databases in one instance +// will not affect other instances. However, within an instance +// databases can affect each other. For example, if one database in an +// instance receives a lot of requests and consumes most of the +// instance resources, fewer resources are available for other +// databases in that instance, and their performance may suffer. +func NewInstanceAdminRESTClient(ctx context.Context, opts ...option.ClientOption) (*InstanceAdminClient, error) { + clientOpts := append(defaultInstanceAdminRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultInstanceAdminRESTCallOptions() + c := &instanceAdminRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &InstanceAdminClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultInstanceAdminRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://spanner.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://spanner.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://spanner.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *instanceAdminRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *instanceAdminRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *instanceAdminRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *instanceAdminGRPCClient) ListInstanceConfigs(ctx context.Context, req *instancepb.ListInstanceConfigsRequest, opts ...gax.CallOption) *InstanceConfigIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1024,92 +1212,1270 @@ func (c *instanceAdminGRPCClient) TestIamPermissions(ctx context.Context, req *i return resp, nil } -// CreateInstanceOperation manages a long-running operation from CreateInstance. -type CreateInstanceOperation struct { - lro *longrunning.Operation -} +// ListInstanceConfigs lists the supported instance configurations for a given project. +func (c *instanceAdminRESTClient) ListInstanceConfigs(ctx context.Context, req *instancepb.ListInstanceConfigsRequest, opts ...gax.CallOption) *InstanceConfigIterator { + it := &InstanceConfigIterator{} + req = proto.Clone(req).(*instancepb.ListInstanceConfigsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*instancepb.InstanceConfig, string, error) { + resp := &instancepb.ListInstanceConfigsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/instanceConfigs", req.GetParent()) -// CreateInstanceOperation returns a new CreateInstanceOperation from a given name. -// The name must be that of a previously created CreateInstanceOperation, possibly from a different process. -func (c *instanceAdminGRPCClient) CreateInstanceOperation(name string) *CreateInstanceOperation { - return &CreateInstanceOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *CreateInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*instancepb.Instance, error) { - var resp instancepb.Instance - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { - return nil, err + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetInstanceConfigs(), resp.GetNextPageToken(), nil } - return &resp, nil -} -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *CreateInstanceOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*instancepb.Instance, error) { - var resp instancepb.Instance - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { - return nil, err - } - if !op.Done() { - return nil, 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 } - return &resp, nil + + it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it } -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *CreateInstanceOperation) Metadata() (*instancepb.CreateInstanceMetadata, error) { - var meta instancepb.CreateInstanceMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { +// GetInstanceConfig gets information about a particular instance configuration. +func (c *instanceAdminRESTClient) GetInstanceConfig(ctx context.Context, req *instancepb.GetInstanceConfigRequest, opts ...gax.CallOption) (*instancepb.InstanceConfig, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - return &meta, nil -} + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) -// Done reports whether the long-running operation has completed. -func (op *CreateInstanceOperation) Done() bool { - return op.lro.Done() -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") -// 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 *CreateInstanceOperation) Name() string { - return op.lro.Name() -} + baseUrl.RawQuery = params.Encode() -// CreateInstanceConfigOperation manages a long-running operation from CreateInstanceConfig. -type CreateInstanceConfigOperation struct { - lro *longrunning.Operation -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) -// CreateInstanceConfigOperation returns a new CreateInstanceConfigOperation from a given name. -// The name must be that of a previously created CreateInstanceConfigOperation, possibly from a different process. -func (c *instanceAdminGRPCClient) CreateInstanceConfigOperation(name string) *CreateInstanceConfigOperation { - return &CreateInstanceConfigOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetInstanceConfig[0:len((*c.CallOptions).GetInstanceConfig):len((*c.CallOptions).GetInstanceConfig)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &instancepb.InstanceConfig{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e } + return resp, nil } -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// CreateInstanceConfig creates an instance config and begins preparing it to be used. The +// returned [long-running operation][google.longrunning.Operation] +// can be used to track the progress of preparing the new +// instance config. The instance config name is assigned by the caller. If the +// named instance config already exists, CreateInstanceConfig returns +// ALREADY_EXISTS. // -// See documentation of Poll for error-handling information. +// Immediately after the request returns: +// +// The instance config is readable via the API, with all requested +// attributes. The instance config’s +// reconciling +// field is set to true. Its state is CREATING. +// +// While the operation is pending: +// +// Cancelling the operation renders the instance config immediately +// unreadable via the API. +// +// Except for deleting the creating resource, all other attempts to modify +// the instance config are rejected. +// +// Upon completion of the returned operation: +// +// Instances can be created using the instance configuration. +// +// The instance config’s +// reconciling +// field becomes false. Its state becomes READY. +// +// The returned [long-running operation][google.longrunning.Operation] will +// have a name of the format +// /operations/ and can be used to track +// creation of the instance config. The +// metadata field type is +// CreateInstanceConfigMetadata. +// The response field type is +// InstanceConfig, if +// successful. +// +// Authorization requires spanner.instanceConfigs.create permission on +// the resource +// parent. +func (c *instanceAdminRESTClient) CreateInstanceConfig(ctx context.Context, req *instancepb.CreateInstanceConfigRequest, opts ...gax.CallOption) (*CreateInstanceConfigOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/instanceConfigs", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateInstanceConfigOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateInstanceConfig updates an instance config. The returned +// [long-running operation][google.longrunning.Operation] can be used to track +// the progress of updating the instance. If the named instance config does +// not exist, returns NOT_FOUND. +// +// Only user managed configurations can be updated. +// +// Immediately after the request returns: +// +// The instance config’s +// reconciling +// field is set to true. +// +// While the operation is pending: +// +// Cancelling the operation sets its metadata’s +// cancel_time. +// The operation is guaranteed to succeed at undoing all changes, after +// which point it terminates with a CANCELLED status. +// +// All other attempts to modify the instance config are rejected. +// +// Reading the instance config via the API continues to give the +// pre-request values. +// +// Upon completion of the returned operation: +// +// Creating instances using the instance configuration uses the new +// values. +// +// The instance config’s new values are readable via the API. +// +// The instance config’s +// reconciling +// field becomes false. +// +// The returned [long-running operation][google.longrunning.Operation] will +// have a name of the format +// /operations/ and can be used to track +// the instance config modification. The +// metadata field type is +// UpdateInstanceConfigMetadata. +// The response field type is +// InstanceConfig, if +// successful. +// +// Authorization requires spanner.instanceConfigs.update permission on +// the resource [name][google.spanner.admin.instance.v1.InstanceConfig.name (at http://google.spanner.admin.instance.v1.InstanceConfig.name)]. +func (c *instanceAdminRESTClient) UpdateInstanceConfig(ctx context.Context, req *instancepb.UpdateInstanceConfigRequest, opts ...gax.CallOption) (*UpdateInstanceConfigOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetInstanceConfig().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "instance_config.name", url.QueryEscape(req.GetInstanceConfig().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateInstanceConfigOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteInstanceConfig deletes the instance config. Deletion is only allowed when no +// instances are using the configuration. If any instances are using +// the config, returns FAILED_PRECONDITION. +// +// Only user managed configurations can be deleted. +// +// Authorization requires spanner.instanceConfigs.delete permission on +// the resource [name][google.spanner.admin.instance.v1.InstanceConfig.name (at http://google.spanner.admin.instance.v1.InstanceConfig.name)]. +func (c *instanceAdminRESTClient) DeleteInstanceConfig(ctx context.Context, req *instancepb.DeleteInstanceConfigRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetEtag() != "" { + params.Add("etag", fmt.Sprintf("%v", req.GetEtag())) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// ListInstanceConfigOperations lists the user-managed instance config [long-running +// operations][google.longrunning.Operation] in the given project. An instance +// config operation has a name of the form +// projects//instanceConfigs//operations/. +// The long-running operation +// metadata field type +// metadata.type_url describes the type of the metadata. Operations returned +// include those that have completed/failed/canceled within the last 7 days, +// and pending operations. Operations returned are ordered by +// operation.metadata.value.start_time in descending order starting +// from the most recently started operation. +func (c *instanceAdminRESTClient) ListInstanceConfigOperations(ctx context.Context, req *instancepb.ListInstanceConfigOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*instancepb.ListInstanceConfigOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &instancepb.ListInstanceConfigOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/instanceConfigOperations", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// ListInstances lists all instances in the given project. +func (c *instanceAdminRESTClient) ListInstances(ctx context.Context, req *instancepb.ListInstancesRequest, opts ...gax.CallOption) *InstanceIterator { + it := &InstanceIterator{} + req = proto.Clone(req).(*instancepb.ListInstancesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*instancepb.Instance, string, error) { + resp := &instancepb.ListInstancesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/instances", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetInstances(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetInstance gets information about a particular instance. +func (c *instanceAdminRESTClient) GetInstance(ctx context.Context, req *instancepb.GetInstanceRequest, opts ...gax.CallOption) (*instancepb.Instance, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFieldMask() != nil { + fieldMask, err := protojson.Marshal(req.GetFieldMask()) + if err != nil { + return nil, err + } + params.Add("fieldMask", string(fieldMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetInstance[0:len((*c.CallOptions).GetInstance):len((*c.CallOptions).GetInstance)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &instancepb.Instance{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateInstance creates an instance and begins preparing it to begin serving. The +// returned [long-running operation][google.longrunning.Operation] +// can be used to track the progress of preparing the new +// instance. The instance name is assigned by the caller. If the +// named instance already exists, CreateInstance returns +// ALREADY_EXISTS. +// +// Immediately upon completion of this request: +// +// The instance is readable via the API, with all requested attributes +// but no allocated resources. Its state is CREATING. +// +// Until completion of the returned operation: +// +// Cancelling the operation renders the instance immediately unreadable +// via the API. +// +// The instance can be deleted. +// +// All other attempts to modify the instance are rejected. +// +// Upon completion of the returned operation: +// +// Billing for all successfully-allocated resources begins (some types +// may have lower than the requested levels). +// +// Databases can be created in the instance. +// +// The instance’s allocated resource levels are readable via the API. +// +// The instance’s state becomes READY. +// +// The returned [long-running operation][google.longrunning.Operation] will +// have a name of the format /operations/ and +// can be used to track creation of the instance. The +// metadata field type is +// CreateInstanceMetadata. +// The response field type is +// Instance, if successful. +func (c *instanceAdminRESTClient) CreateInstance(ctx context.Context, req *instancepb.CreateInstanceRequest, opts ...gax.CallOption) (*CreateInstanceOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/instances", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateInstance updates an instance, and begins allocating or releasing resources +// as requested. The returned [long-running +// operation][google.longrunning.Operation] can be used to track the +// progress of updating the instance. If the named instance does not +// exist, returns NOT_FOUND. +// +// Immediately upon completion of this request: +// +// For resource types for which a decrease in the instance’s allocation +// has been requested, billing is based on the newly-requested level. +// +// Until completion of the returned operation: +// +// Cancelling the operation sets its metadata’s +// cancel_time, +// and begins restoring resources to their pre-request values. The +// operation is guaranteed to succeed at undoing all resource changes, +// after which point it terminates with a CANCELLED status. +// +// All other attempts to modify the instance are rejected. +// +// Reading the instance via the API continues to give the pre-request +// resource levels. +// +// Upon completion of the returned operation: +// +// Billing begins for all successfully-allocated resources (some types +// may have lower than the requested levels). +// +// All newly-reserved resources are available for serving the instance’s +// tables. +// +// The instance’s new resource levels are readable via the API. +// +// The returned [long-running operation][google.longrunning.Operation] will +// have a name of the format /operations/ and +// can be used to track the instance modification. The +// metadata field type is +// UpdateInstanceMetadata. +// The response field type is +// Instance, if successful. +// +// Authorization requires spanner.instances.update permission on +// the resource [name][google.spanner.admin.instance.v1.Instance.name (at http://google.spanner.admin.instance.v1.Instance.name)]. +func (c *instanceAdminRESTClient) UpdateInstance(ctx context.Context, req *instancepb.UpdateInstanceRequest, opts ...gax.CallOption) (*UpdateInstanceOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetInstance().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "instance.name", url.QueryEscape(req.GetInstance().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteInstance deletes an instance. +// +// Immediately upon completion of the request: +// +// Billing ceases for all of the instance’s reserved resources. +// +// Soon afterward: +// +// The instance and all of its databases immediately and +// irrevocably disappear from the API. All data in the databases +// is permanently deleted. +func (c *instanceAdminRESTClient) DeleteInstance(ctx context.Context, req *instancepb.DeleteInstanceRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// SetIamPolicy sets the access control policy on an instance resource. Replaces any +// existing policy. +// +// Authorization requires spanner.instances.setIamPolicy on +// resource. +func (c *instanceAdminRESTClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:setIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetIamPolicy gets the access control policy for an instance resource. Returns an empty +// policy if an instance exists but does not have a policy set. +// +// Authorization requires spanner.instances.getIamPolicy on +// resource. +func (c *instanceAdminRESTClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:getIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// TestIamPermissions returns permissions that the caller has on the specified instance resource. +// +// Attempting this RPC on a non-existent Cloud Spanner instance resource will +// result in a NOT_FOUND error if the user has spanner.instances.list +// permission on the containing Google Cloud Project. Otherwise returns an +// empty set of permissions. +func (c *instanceAdminRESTClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:testIamPermissions", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.TestIamPermissionsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateInstanceOperation manages a long-running operation from CreateInstance. +type CreateInstanceOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateInstanceOperation returns a new CreateInstanceOperation from a given name. +// The name must be that of a previously created CreateInstanceOperation, possibly from a different process. +func (c *instanceAdminGRPCClient) CreateInstanceOperation(name string) *CreateInstanceOperation { + return &CreateInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateInstanceOperation returns a new CreateInstanceOperation from a given name. +// The name must be that of a previously created CreateInstanceOperation, possibly from a different process. +func (c *instanceAdminRESTClient) CreateInstanceOperation(name string) *CreateInstanceOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CreateInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*instancepb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp instancepb.Instance + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *CreateInstanceOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*instancepb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp instancepb.Instance + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *CreateInstanceOperation) Metadata() (*instancepb.CreateInstanceMetadata, error) { + var meta instancepb.CreateInstanceMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *CreateInstanceOperation) Done() bool { + return op.lro.Done() +} + +// 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 *CreateInstanceOperation) Name() string { + return op.lro.Name() +} + +// CreateInstanceConfigOperation manages a long-running operation from CreateInstanceConfig. +type CreateInstanceConfigOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateInstanceConfigOperation returns a new CreateInstanceConfigOperation from a given name. +// The name must be that of a previously created CreateInstanceConfigOperation, possibly from a different process. +func (c *instanceAdminGRPCClient) CreateInstanceConfigOperation(name string) *CreateInstanceConfigOperation { + return &CreateInstanceConfigOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateInstanceConfigOperation returns a new CreateInstanceConfigOperation from a given name. +// The name must be that of a previously created CreateInstanceConfigOperation, possibly from a different process. +func (c *instanceAdminRESTClient) CreateInstanceConfigOperation(name string) *CreateInstanceConfigOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateInstanceConfigOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. func (op *CreateInstanceConfigOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*instancepb.InstanceConfig, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp instancepb.InstanceConfig if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1127,6 +2493,7 @@ func (op *CreateInstanceConfigOperation) Wait(ctx context.Context, opts ...gax.C // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateInstanceConfigOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*instancepb.InstanceConfig, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp instancepb.InstanceConfig if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1164,7 +2531,8 @@ func (op *CreateInstanceConfigOperation) Name() string { // UpdateInstanceOperation manages a long-running operation from UpdateInstance. type UpdateInstanceOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateInstanceOperation returns a new UpdateInstanceOperation from a given name. @@ -1175,10 +2543,21 @@ func (c *instanceAdminGRPCClient) UpdateInstanceOperation(name string) *UpdateIn } } +// UpdateInstanceOperation returns a new UpdateInstanceOperation from a given name. +// The name must be that of a previously created UpdateInstanceOperation, possibly from a different process. +func (c *instanceAdminRESTClient) UpdateInstanceOperation(name string) *UpdateInstanceOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateInstanceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*instancepb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp instancepb.Instance if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1196,6 +2575,7 @@ func (op *UpdateInstanceOperation) Wait(ctx context.Context, opts ...gax.CallOpt // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateInstanceOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*instancepb.Instance, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp instancepb.Instance if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1233,7 +2613,8 @@ func (op *UpdateInstanceOperation) Name() string { // UpdateInstanceConfigOperation manages a long-running operation from UpdateInstanceConfig. type UpdateInstanceConfigOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateInstanceConfigOperation returns a new UpdateInstanceConfigOperation from a given name. @@ -1244,10 +2625,21 @@ func (c *instanceAdminGRPCClient) UpdateInstanceConfigOperation(name string) *Up } } +// UpdateInstanceConfigOperation returns a new UpdateInstanceConfigOperation from a given name. +// The name must be that of a previously created UpdateInstanceConfigOperation, possibly from a different process. +func (c *instanceAdminRESTClient) UpdateInstanceConfigOperation(name string) *UpdateInstanceConfigOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateInstanceConfigOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateInstanceConfigOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*instancepb.InstanceConfig, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp instancepb.InstanceConfig if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1265,6 +2657,7 @@ func (op *UpdateInstanceConfigOperation) Wait(ctx context.Context, opts ...gax.C // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateInstanceConfigOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*instancepb.InstanceConfig, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp instancepb.InstanceConfig if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/spanner/admin/instance/apiv1/instance_admin_client_example_test.go b/spanner/admin/instance/apiv1/instance_admin_client_example_test.go index b4c60cb764b0..c73315a2d49e 100644 --- a/spanner/admin/instance/apiv1/instance_admin_client_example_test.go +++ b/spanner/admin/instance/apiv1/instance_admin_client_example_test.go @@ -42,6 +42,23 @@ func ExampleNewInstanceAdminClient() { _ = c } +func ExampleNewInstanceAdminRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := instance.NewInstanceAdminRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleInstanceAdminClient_ListInstanceConfigs() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/spanner/admin/instance/apiv1/instancepb/common.pb.go b/spanner/admin/instance/apiv1/instancepb/common.pb.go index 634470d5f6f1..03964993c083 100644 --- a/spanner/admin/instance/apiv1/instancepb/common.pb.go +++ b/spanner/admin/instance/apiv1/instancepb/common.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/spanner/admin/instance/v1/common.proto package instancepb diff --git a/spanner/admin/instance/apiv1/instancepb/spanner_instance_admin.pb.go b/spanner/admin/instance/apiv1/instancepb/spanner_instance_admin.pb.go index 16f7d5e8913f..a1874d38c0fc 100644 --- a/spanner/admin/instance/apiv1/instancepb/spanner_instance_admin.pb.go +++ b/spanner/admin/instance/apiv1/instancepb/spanner_instance_admin.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/spanner/admin/instance/v1/spanner_instance_admin.proto package instancepb @@ -387,11 +387,11 @@ type InstanceConfig struct { // And they can be used as arguments to policy management rules (e.g. route, // firewall, load balancing, etc.). // - // - Label keys must be between 1 and 63 characters long and must conform to - // the following regular expression: `[a-z][a-z0-9_-]{0,62}`. - // - Label values must be between 0 and 63 characters long and must conform - // to the regular expression `[a-z0-9_-]{0,63}`. - // - No more than 64 labels can be associated with a given resource. + // * Label keys must be between 1 and 63 characters long and must conform to + // the following regular expression: `[a-z][a-z0-9_-]{0,62}`. + // * Label values must be between 0 and 63 characters long and must conform + // to the regular expression `[a-z0-9_-]{0,63}`. + // * No more than 64 labels can be associated with a given resource. // // See https://goo.gl/xmQnxf for more information on and examples of labels. // @@ -581,11 +581,11 @@ type Instance struct { // And they can be used as arguments to policy management rules (e.g. route, // firewall, load balancing, etc.). // - // - Label keys must be between 1 and 63 characters long and must conform to - // the following regular expression: `[a-z][a-z0-9_-]{0,62}`. - // - Label values must be between 0 and 63 characters long and must conform - // to the regular expression `[a-z0-9_-]{0,63}`. - // - No more than 64 labels can be associated with a given resource. + // * Label keys must be between 1 and 63 characters long and must conform to + // the following regular expression: `[a-z][a-z0-9_-]{0,62}`. + // * Label values must be between 0 and 63 characters long and must conform + // to the regular expression `[a-z0-9_-]{0,63}`. + // * No more than 64 labels can be associated with a given resource. // // See https://goo.gl/xmQnxf for more information on and examples of labels. // @@ -1155,19 +1155,19 @@ type ListInstanceConfigOperationsRequest struct { // The following fields in the [Operation][google.longrunning.Operation] // are eligible for filtering: // - // - `name` - The name of the long-running operation - // - `done` - False if the operation is in progress, else true. - // - `metadata.@type` - the type of metadata. For example, the type string - // for - // [CreateInstanceConfigMetadata][google.spanner.admin.instance.v1.CreateInstanceConfigMetadata] - // is - // `type.googleapis.com/google.spanner.admin.instance.v1.CreateInstanceConfigMetadata`. - // - `metadata.` - any field in metadata.value. - // `metadata.@type` must be specified first, if filtering on metadata - // fields. - // - `error` - Error associated with the long-running operation. - // - `response.@type` - the type of response. - // - `response.` - any field in response.value. + // * `name` - The name of the long-running operation + // * `done` - False if the operation is in progress, else true. + // * `metadata.@type` - the type of metadata. For example, the type string + // for + // [CreateInstanceConfigMetadata][google.spanner.admin.instance.v1.CreateInstanceConfigMetadata] + // is + // `type.googleapis.com/google.spanner.admin.instance.v1.CreateInstanceConfigMetadata`. + // * `metadata.` - any field in metadata.value. + // `metadata.@type` must be specified first, if filtering on metadata + // fields. + // * `error` - Error associated with the long-running operation. + // * `response.@type` - the type of response. + // * `response.` - any field in response.value. // // You can combine multiple expressions by enclosing each expression in // parentheses. By default, expressions are combined with AND logic. However, @@ -1175,18 +1175,18 @@ type ListInstanceConfigOperationsRequest struct { // // Here are a few examples: // - // - `done:true` - The operation is complete. - // - `(metadata.@type=` \ + // * `done:true` - The operation is complete. + // * `(metadata.@type=` \ // `type.googleapis.com/google.spanner.admin.instance.v1.CreateInstanceConfigMetadata) // AND` \ // `(metadata.instance_config.name:custom-config) AND` \ // `(metadata.progress.start_time < \"2021-03-28T14:50:00Z\") AND` \ // `(error:*)` - Return operations where: - // - The operation's metadata type is + // * The operation's metadata type is // [CreateInstanceConfigMetadata][google.spanner.admin.instance.v1.CreateInstanceConfigMetadata]. - // - The instance config name contains "custom-config". - // - The operation started before 2021-03-28T14:50:00Z. - // - The operation resulted in an error. + // * The instance config name contains "custom-config". + // * The operation started before 2021-03-28T14:50:00Z. + // * The operation resulted in an error. Filter string `protobuf:"bytes,2,opt,name=filter,proto3" json:"filter,omitempty"` // Number of operations to be returned in the response. If 0 or // less, defaults to the server's maximum allowed page size. @@ -1480,22 +1480,22 @@ type ListInstancesRequest struct { // An expression for filtering the results of the request. Filter rules are // case insensitive. The fields eligible for filtering are: // - // - `name` - // - `display_name` - // - `labels.key` where key is the name of a label + // * `name` + // * `display_name` + // * `labels.key` where key is the name of a label // // Some examples of using filters are: // - // - `name:*` --> The instance has a name. - // - `name:Howl` --> The instance's name contains the string "howl". - // - `name:HOWL` --> Equivalent to above. - // - `NAME:howl` --> Equivalent to above. - // - `labels.env:*` --> The instance has the label "env". - // - `labels.env:dev` --> The instance has the label "env" and the value of - // the label contains the string "dev". - // - `name:howl labels.env:dev` --> The instance's name contains "howl" and - // it has the label "env" with its value - // containing "dev". + // * `name:*` --> The instance has a name. + // * `name:Howl` --> The instance's name contains the string "howl". + // * `name:HOWL` --> Equivalent to above. + // * `NAME:howl` --> Equivalent to above. + // * `labels.env:*` --> The instance has the label "env". + // * `labels.env:dev` --> The instance has the label "env" and the value of + // the label contains the string "dev". + // * `name:howl labels.env:dev` --> The instance's name contains "howl" and + // it has the label "env" with its value + // containing "dev". Filter string `protobuf:"bytes,4,opt,name=filter,proto3" json:"filter,omitempty"` } @@ -3059,24 +3059,24 @@ type InstanceAdminClient interface { // // Immediately after the request returns: // - // - The instance config is readable via the API, with all requested + // * The instance config is readable via the API, with all requested // attributes. The instance config's // [reconciling][google.spanner.admin.instance.v1.InstanceConfig.reconciling] // field is set to true. Its state is `CREATING`. // // While the operation is pending: // - // - Cancelling the operation renders the instance config immediately + // * Cancelling the operation renders the instance config immediately // unreadable via the API. - // - Except for deleting the creating resource, all other attempts to modify + // * Except for deleting the creating resource, all other attempts to modify // the instance config are rejected. // // Upon completion of the returned operation: // - // - Instances can be created using the instance configuration. - // - The instance config's - // [reconciling][google.spanner.admin.instance.v1.InstanceConfig.reconciling] - // field becomes false. Its state becomes `READY`. + // * Instances can be created using the instance configuration. + // * The instance config's + // [reconciling][google.spanner.admin.instance.v1.InstanceConfig.reconciling] + // field becomes false. Its state becomes `READY`. // // The returned [long-running operation][google.longrunning.Operation] will // have a name of the format @@ -3101,28 +3101,28 @@ type InstanceAdminClient interface { // // Immediately after the request returns: // - // - The instance config's + // * The instance config's // [reconciling][google.spanner.admin.instance.v1.InstanceConfig.reconciling] // field is set to true. // // While the operation is pending: // - // - Cancelling the operation sets its metadata's + // * Cancelling the operation sets its metadata's // [cancel_time][google.spanner.admin.instance.v1.UpdateInstanceConfigMetadata.cancel_time]. // The operation is guaranteed to succeed at undoing all changes, after // which point it terminates with a `CANCELLED` status. - // - All other attempts to modify the instance config are rejected. - // - Reading the instance config via the API continues to give the + // * All other attempts to modify the instance config are rejected. + // * Reading the instance config via the API continues to give the // pre-request values. // // Upon completion of the returned operation: // - // - Creating instances using the instance configuration uses the new + // * Creating instances using the instance configuration uses the new // values. - // - The instance config's new values are readable via the API. - // - The instance config's - // [reconciling][google.spanner.admin.instance.v1.InstanceConfig.reconciling] - // field becomes false. + // * The instance config's new values are readable via the API. + // * The instance config's + // [reconciling][google.spanner.admin.instance.v1.InstanceConfig.reconciling] + // field becomes false. // // The returned [long-running operation][google.longrunning.Operation] will // have a name of the format @@ -3171,23 +3171,23 @@ type InstanceAdminClient interface { // // Immediately upon completion of this request: // - // - The instance is readable via the API, with all requested attributes + // * The instance is readable via the API, with all requested attributes // but no allocated resources. Its state is `CREATING`. // // Until completion of the returned operation: // - // - Cancelling the operation renders the instance immediately unreadable + // * Cancelling the operation renders the instance immediately unreadable // via the API. - // - The instance can be deleted. - // - All other attempts to modify the instance are rejected. + // * The instance can be deleted. + // * All other attempts to modify the instance are rejected. // // Upon completion of the returned operation: // - // - Billing for all successfully-allocated resources begins (some types + // * Billing for all successfully-allocated resources begins (some types // may have lower than the requested levels). - // - Databases can be created in the instance. - // - The instance's allocated resource levels are readable via the API. - // - The instance's state becomes `READY`. + // * Databases can be created in the instance. + // * The instance's allocated resource levels are readable via the API. + // * The instance's state becomes `READY`. // // The returned [long-running operation][google.longrunning.Operation] will // have a name of the format `/operations/` and @@ -3205,27 +3205,27 @@ type InstanceAdminClient interface { // // Immediately upon completion of this request: // - // - For resource types for which a decrease in the instance's allocation + // * For resource types for which a decrease in the instance's allocation // has been requested, billing is based on the newly-requested level. // // Until completion of the returned operation: // - // - Cancelling the operation sets its metadata's + // * Cancelling the operation sets its metadata's // [cancel_time][google.spanner.admin.instance.v1.UpdateInstanceMetadata.cancel_time], // and begins restoring resources to their pre-request values. The // operation is guaranteed to succeed at undoing all resource changes, // after which point it terminates with a `CANCELLED` status. - // - All other attempts to modify the instance are rejected. - // - Reading the instance via the API continues to give the pre-request + // * All other attempts to modify the instance are rejected. + // * Reading the instance via the API continues to give the pre-request // resource levels. // // Upon completion of the returned operation: // - // - Billing begins for all successfully-allocated resources (some types + // * Billing begins for all successfully-allocated resources (some types // may have lower than the requested levels). - // - All newly-reserved resources are available for serving the instance's + // * All newly-reserved resources are available for serving the instance's // tables. - // - The instance's new resource levels are readable via the API. + // * The instance's new resource levels are readable via the API. // // The returned [long-running operation][google.longrunning.Operation] will // have a name of the format `/operations/` and @@ -3242,11 +3242,11 @@ type InstanceAdminClient interface { // // Immediately upon completion of the request: // - // - Billing ceases for all of the instance's reserved resources. + // * Billing ceases for all of the instance's reserved resources. // // Soon afterward: // - // - The instance and *all of its databases* immediately and + // * The instance and *all of its databases* immediately and // irrevocably disappear from the API. All data in the databases // is permanently deleted. DeleteInstance(ctx context.Context, in *DeleteInstanceRequest, opts ...grpc.CallOption) (*emptypb.Empty, error) @@ -3420,24 +3420,24 @@ type InstanceAdminServer interface { // // Immediately after the request returns: // - // - The instance config is readable via the API, with all requested + // * The instance config is readable via the API, with all requested // attributes. The instance config's // [reconciling][google.spanner.admin.instance.v1.InstanceConfig.reconciling] // field is set to true. Its state is `CREATING`. // // While the operation is pending: // - // - Cancelling the operation renders the instance config immediately + // * Cancelling the operation renders the instance config immediately // unreadable via the API. - // - Except for deleting the creating resource, all other attempts to modify + // * Except for deleting the creating resource, all other attempts to modify // the instance config are rejected. // // Upon completion of the returned operation: // - // - Instances can be created using the instance configuration. - // - The instance config's - // [reconciling][google.spanner.admin.instance.v1.InstanceConfig.reconciling] - // field becomes false. Its state becomes `READY`. + // * Instances can be created using the instance configuration. + // * The instance config's + // [reconciling][google.spanner.admin.instance.v1.InstanceConfig.reconciling] + // field becomes false. Its state becomes `READY`. // // The returned [long-running operation][google.longrunning.Operation] will // have a name of the format @@ -3462,28 +3462,28 @@ type InstanceAdminServer interface { // // Immediately after the request returns: // - // - The instance config's + // * The instance config's // [reconciling][google.spanner.admin.instance.v1.InstanceConfig.reconciling] // field is set to true. // // While the operation is pending: // - // - Cancelling the operation sets its metadata's + // * Cancelling the operation sets its metadata's // [cancel_time][google.spanner.admin.instance.v1.UpdateInstanceConfigMetadata.cancel_time]. // The operation is guaranteed to succeed at undoing all changes, after // which point it terminates with a `CANCELLED` status. - // - All other attempts to modify the instance config are rejected. - // - Reading the instance config via the API continues to give the + // * All other attempts to modify the instance config are rejected. + // * Reading the instance config via the API continues to give the // pre-request values. // // Upon completion of the returned operation: // - // - Creating instances using the instance configuration uses the new + // * Creating instances using the instance configuration uses the new // values. - // - The instance config's new values are readable via the API. - // - The instance config's - // [reconciling][google.spanner.admin.instance.v1.InstanceConfig.reconciling] - // field becomes false. + // * The instance config's new values are readable via the API. + // * The instance config's + // [reconciling][google.spanner.admin.instance.v1.InstanceConfig.reconciling] + // field becomes false. // // The returned [long-running operation][google.longrunning.Operation] will // have a name of the format @@ -3532,23 +3532,23 @@ type InstanceAdminServer interface { // // Immediately upon completion of this request: // - // - The instance is readable via the API, with all requested attributes + // * The instance is readable via the API, with all requested attributes // but no allocated resources. Its state is `CREATING`. // // Until completion of the returned operation: // - // - Cancelling the operation renders the instance immediately unreadable + // * Cancelling the operation renders the instance immediately unreadable // via the API. - // - The instance can be deleted. - // - All other attempts to modify the instance are rejected. + // * The instance can be deleted. + // * All other attempts to modify the instance are rejected. // // Upon completion of the returned operation: // - // - Billing for all successfully-allocated resources begins (some types + // * Billing for all successfully-allocated resources begins (some types // may have lower than the requested levels). - // - Databases can be created in the instance. - // - The instance's allocated resource levels are readable via the API. - // - The instance's state becomes `READY`. + // * Databases can be created in the instance. + // * The instance's allocated resource levels are readable via the API. + // * The instance's state becomes `READY`. // // The returned [long-running operation][google.longrunning.Operation] will // have a name of the format `/operations/` and @@ -3566,27 +3566,27 @@ type InstanceAdminServer interface { // // Immediately upon completion of this request: // - // - For resource types for which a decrease in the instance's allocation + // * For resource types for which a decrease in the instance's allocation // has been requested, billing is based on the newly-requested level. // // Until completion of the returned operation: // - // - Cancelling the operation sets its metadata's + // * Cancelling the operation sets its metadata's // [cancel_time][google.spanner.admin.instance.v1.UpdateInstanceMetadata.cancel_time], // and begins restoring resources to their pre-request values. The // operation is guaranteed to succeed at undoing all resource changes, // after which point it terminates with a `CANCELLED` status. - // - All other attempts to modify the instance are rejected. - // - Reading the instance via the API continues to give the pre-request + // * All other attempts to modify the instance are rejected. + // * Reading the instance via the API continues to give the pre-request // resource levels. // // Upon completion of the returned operation: // - // - Billing begins for all successfully-allocated resources (some types + // * Billing begins for all successfully-allocated resources (some types // may have lower than the requested levels). - // - All newly-reserved resources are available for serving the instance's + // * All newly-reserved resources are available for serving the instance's // tables. - // - The instance's new resource levels are readable via the API. + // * The instance's new resource levels are readable via the API. // // The returned [long-running operation][google.longrunning.Operation] will // have a name of the format `/operations/` and @@ -3603,11 +3603,11 @@ type InstanceAdminServer interface { // // Immediately upon completion of the request: // - // - Billing ceases for all of the instance's reserved resources. + // * Billing ceases for all of the instance's reserved resources. // // Soon afterward: // - // - The instance and *all of its databases* immediately and + // * The instance and *all of its databases* immediately and // irrevocably disappear from the API. All data in the databases // is permanently deleted. DeleteInstance(context.Context, *DeleteInstanceRequest) (*emptypb.Empty, error) diff --git a/spanner/apiv1/doc.go b/spanner/apiv1/doc.go index 714372fc6f39..8c17aa2fdaec 100644 --- a/spanner/apiv1/doc.go +++ b/spanner/apiv1/doc.go @@ -81,6 +81,8 @@ package spanner // import "cloud.google.com/go/spanner/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -170,3 +172,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/spanner/apiv1/gapic_metadata.json b/spanner/apiv1/gapic_metadata.json index 7a47d3467843..e4e0f08e6131 100644 --- a/spanner/apiv1/gapic_metadata.json +++ b/spanner/apiv1/gapic_metadata.json @@ -86,6 +86,86 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "BatchCreateSessions": { + "methods": [ + "BatchCreateSessions" + ] + }, + "BeginTransaction": { + "methods": [ + "BeginTransaction" + ] + }, + "Commit": { + "methods": [ + "Commit" + ] + }, + "CreateSession": { + "methods": [ + "CreateSession" + ] + }, + "DeleteSession": { + "methods": [ + "DeleteSession" + ] + }, + "ExecuteBatchDml": { + "methods": [ + "ExecuteBatchDml" + ] + }, + "ExecuteSql": { + "methods": [ + "ExecuteSql" + ] + }, + "ExecuteStreamingSql": { + "methods": [ + "ExecuteStreamingSql" + ] + }, + "GetSession": { + "methods": [ + "GetSession" + ] + }, + "ListSessions": { + "methods": [ + "ListSessions" + ] + }, + "PartitionQuery": { + "methods": [ + "PartitionQuery" + ] + }, + "PartitionRead": { + "methods": [ + "PartitionRead" + ] + }, + "Read": { + "methods": [ + "Read" + ] + }, + "Rollback": { + "methods": [ + "Rollback" + ] + }, + "StreamingRead": { + "methods": [ + "StreamingRead" + ] + } + } } } } diff --git a/spanner/apiv1/spanner_client.go b/spanner/apiv1/spanner_client.go index 82720a64a2a8..8f9580bfee29 100644 --- a/spanner/apiv1/spanner_client.go +++ b/spanner/apiv1/spanner_client.go @@ -17,21 +17,27 @@ package spanner import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" spannerpb "cloud.google.com/go/spanner/apiv1/spannerpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -218,6 +224,143 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + CreateSession: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 250 * time.Millisecond, + Max: 32000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + BatchCreateSessions: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 250 * time.Millisecond, + Max: 32000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetSession: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 250 * time.Millisecond, + Max: 32000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListSessions: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 250 * time.Millisecond, + Max: 32000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeleteSession: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 250 * time.Millisecond, + Max: 32000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ExecuteSql: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 250 * time.Millisecond, + Max: 32000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ExecuteStreamingSql: []gax.CallOption{}, + ExecuteBatchDml: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 250 * time.Millisecond, + Max: 32000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + Read: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 250 * time.Millisecond, + Max: 32000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + StreamingRead: []gax.CallOption{}, + BeginTransaction: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 250 * time.Millisecond, + Max: 32000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + Commit: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 250 * time.Millisecond, + Max: 32000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + Rollback: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 250 * time.Millisecond, + Max: 32000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + PartitionQuery: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 250 * time.Millisecond, + Max: 32000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + PartitionRead: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 250 * time.Millisecond, + Max: 32000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + } +} + // internalClient is an interface that defines the methods available from Cloud Spanner API. type internalClient interface { Close() error @@ -547,6 +690,77 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new spanner rest client. +// +// # Cloud Spanner API +// +// The Cloud Spanner API can be used to manage sessions and execute +// transactions on data stored in Cloud Spanner databases. +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://spanner.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://spanner.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://spanner.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) CreateSession(ctx context.Context, req *spannerpb.CreateSessionRequest, opts ...gax.CallOption) (*spannerpb.Session, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) @@ -880,6 +1094,1135 @@ func (c *gRPCClient) PartitionRead(ctx context.Context, req *spannerpb.Partition return resp, nil } +// CreateSession creates a new session. A session can be used to perform +// transactions that read and/or modify data in a Cloud Spanner database. +// Sessions are meant to be reused for many consecutive +// transactions. +// +// Sessions can only execute one transaction at a time. To execute +// multiple concurrent read-write/write-only transactions, create +// multiple sessions. Note that standalone reads and queries use a +// transaction internally, and count toward the one transaction +// limit. +// +// Active sessions use additional server resources, so it is a good idea to +// delete idle and unneeded sessions. +// Aside from explicit deletes, Cloud Spanner may delete sessions for which no +// operations are sent for more than an hour. If a session is deleted, +// requests to it return NOT_FOUND. +// +// Idle sessions can be kept alive by sending a trivial SQL query +// periodically, e.g., "SELECT 1". +func (c *restClient) CreateSession(ctx context.Context, req *spannerpb.CreateSessionRequest, opts ...gax.CallOption) (*spannerpb.Session, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/sessions", req.GetDatabase()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "database", url.QueryEscape(req.GetDatabase()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateSession[0:len((*c.CallOptions).CreateSession):len((*c.CallOptions).CreateSession)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &spannerpb.Session{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// BatchCreateSessions creates multiple new sessions. +// +// This API can be used to initialize a session cache on the clients. +// See https://goo.gl/TgSFN2 (at https://goo.gl/TgSFN2) for best practices on session cache management. +func (c *restClient) BatchCreateSessions(ctx context.Context, req *spannerpb.BatchCreateSessionsRequest, opts ...gax.CallOption) (*spannerpb.BatchCreateSessionsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/sessions:batchCreate", req.GetDatabase()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "database", url.QueryEscape(req.GetDatabase()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).BatchCreateSessions[0:len((*c.CallOptions).BatchCreateSessions):len((*c.CallOptions).BatchCreateSessions)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &spannerpb.BatchCreateSessionsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetSession gets a session. Returns NOT_FOUND if the session does not exist. +// This is mainly useful for determining whether a session is still +// alive. +func (c *restClient) GetSession(ctx context.Context, req *spannerpb.GetSessionRequest, opts ...gax.CallOption) (*spannerpb.Session, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetSession[0:len((*c.CallOptions).GetSession):len((*c.CallOptions).GetSession)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &spannerpb.Session{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListSessions lists all sessions in a given database. +func (c *restClient) ListSessions(ctx context.Context, req *spannerpb.ListSessionsRequest, opts ...gax.CallOption) *SessionIterator { + it := &SessionIterator{} + req = proto.Clone(req).(*spannerpb.ListSessionsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*spannerpb.Session, string, error) { + resp := &spannerpb.ListSessionsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/sessions", req.GetDatabase()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetSessions(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// DeleteSession ends a session, releasing server resources associated with it. This will +// asynchronously trigger cancellation of any operations that are running with +// this session. +func (c *restClient) DeleteSession(ctx context.Context, req *spannerpb.DeleteSessionRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// ExecuteSql executes an SQL statement, returning all results in a single reply. This +// method cannot be used to return a result set larger than 10 MiB; +// if the query yields more data than that, the query fails with +// a FAILED_PRECONDITION error. +// +// Operations inside read-write transactions might return ABORTED. If +// this occurs, the application should restart the transaction from +// the beginning. See Transaction for more details. +// +// Larger result sets can be fetched in streaming fashion by calling +// ExecuteStreamingSql instead. +func (c *restClient) ExecuteSql(ctx context.Context, req *spannerpb.ExecuteSqlRequest, opts ...gax.CallOption) (*spannerpb.ResultSet, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:executeSql", req.GetSession()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "session", url.QueryEscape(req.GetSession()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).ExecuteSql[0:len((*c.CallOptions).ExecuteSql):len((*c.CallOptions).ExecuteSql)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &spannerpb.ResultSet{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ExecuteStreamingSql like ExecuteSql, except returns the result +// set as a stream. Unlike ExecuteSql, there +// is no limit on the size of the returned result set. However, no +// individual row in the result set can exceed 100 MiB, and no +// column value can exceed 10 MiB. +func (c *restClient) ExecuteStreamingSql(ctx context.Context, req *spannerpb.ExecuteSqlRequest, opts ...gax.CallOption) (spannerpb.Spanner_ExecuteStreamingSqlClient, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:executeStreamingSql", req.GetSession()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "session", url.QueryEscape(req.GetSession()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + var streamClient *executeStreamingSqlRESTClient + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + streamClient = &executeStreamingSqlRESTClient{ + ctx: ctx, + md: metadata.MD(httpRsp.Header), + stream: gax.NewProtoJSONStreamReader(httpRsp.Body, (&spannerpb.PartialResultSet{}).ProtoReflect().Type()), + } + return nil + }, opts...) + + return streamClient, e +} + +// executeStreamingSqlRESTClient is the stream client used to consume the server stream created by +// the REST implementation of ExecuteStreamingSql. +type executeStreamingSqlRESTClient struct { + ctx context.Context + md metadata.MD + stream *gax.ProtoJSONStream +} + +func (c *executeStreamingSqlRESTClient) Recv() (*spannerpb.PartialResultSet, error) { + if err := c.ctx.Err(); err != nil { + defer c.stream.Close() + return nil, err + } + msg, err := c.stream.Recv() + if err != nil { + defer c.stream.Close() + return nil, err + } + res := msg.(*spannerpb.PartialResultSet) + return res, nil +} + +func (c *executeStreamingSqlRESTClient) Header() (metadata.MD, error) { + return c.md, nil +} + +func (c *executeStreamingSqlRESTClient) Trailer() metadata.MD { + return c.md +} + +func (c *executeStreamingSqlRESTClient) CloseSend() error { + // This is a no-op to fulfill the interface. + return fmt.Errorf("this method is not implemented for a server-stream") +} + +func (c *executeStreamingSqlRESTClient) Context() context.Context { + return c.ctx +} + +func (c *executeStreamingSqlRESTClient) SendMsg(m interface{}) error { + // This is a no-op to fulfill the interface. + return fmt.Errorf("this method is not implemented for a server-stream") +} + +func (c *executeStreamingSqlRESTClient) RecvMsg(m interface{}) error { + // This is a no-op to fulfill the interface. + return fmt.Errorf("this method is not implemented, use Recv") +} + +// ExecuteBatchDml executes a batch of SQL DML statements. This method allows many statements +// to be run with lower latency than submitting them sequentially with +// ExecuteSql. +// +// Statements are executed in sequential order. A request can succeed even if +// a statement fails. The ExecuteBatchDmlResponse.status field in the +// response provides information about the statement that failed. Clients must +// inspect this field to determine whether an error occurred. +// +// Execution stops after the first failed statement; the remaining statements +// are not executed. +func (c *restClient) ExecuteBatchDml(ctx context.Context, req *spannerpb.ExecuteBatchDmlRequest, opts ...gax.CallOption) (*spannerpb.ExecuteBatchDmlResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:executeBatchDml", req.GetSession()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "session", url.QueryEscape(req.GetSession()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).ExecuteBatchDml[0:len((*c.CallOptions).ExecuteBatchDml):len((*c.CallOptions).ExecuteBatchDml)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &spannerpb.ExecuteBatchDmlResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// Read reads rows from the database using key lookups and scans, as a +// simple key/value style alternative to +// ExecuteSql. This method cannot be used to +// return a result set larger than 10 MiB; if the read matches more +// data than that, the read fails with a FAILED_PRECONDITION +// error. +// +// Reads inside read-write transactions might return ABORTED. If +// this occurs, the application should restart the transaction from +// the beginning. See Transaction for more details. +// +// Larger result sets can be yielded in streaming fashion by calling +// StreamingRead instead. +func (c *restClient) Read(ctx context.Context, req *spannerpb.ReadRequest, opts ...gax.CallOption) (*spannerpb.ResultSet, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:read", req.GetSession()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "session", url.QueryEscape(req.GetSession()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).Read[0:len((*c.CallOptions).Read):len((*c.CallOptions).Read)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &spannerpb.ResultSet{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// StreamingRead like Read, except returns the result set as a +// stream. Unlike Read, there is no limit on the +// size of the returned result set. However, no individual row in +// the result set can exceed 100 MiB, and no column value can exceed +// 10 MiB. +func (c *restClient) StreamingRead(ctx context.Context, req *spannerpb.ReadRequest, opts ...gax.CallOption) (spannerpb.Spanner_StreamingReadClient, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:streamingRead", req.GetSession()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "session", url.QueryEscape(req.GetSession()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + var streamClient *streamingReadRESTClient + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + streamClient = &streamingReadRESTClient{ + ctx: ctx, + md: metadata.MD(httpRsp.Header), + stream: gax.NewProtoJSONStreamReader(httpRsp.Body, (&spannerpb.PartialResultSet{}).ProtoReflect().Type()), + } + return nil + }, opts...) + + return streamClient, e +} + +// streamingReadRESTClient is the stream client used to consume the server stream created by +// the REST implementation of StreamingRead. +type streamingReadRESTClient struct { + ctx context.Context + md metadata.MD + stream *gax.ProtoJSONStream +} + +func (c *streamingReadRESTClient) Recv() (*spannerpb.PartialResultSet, error) { + if err := c.ctx.Err(); err != nil { + defer c.stream.Close() + return nil, err + } + msg, err := c.stream.Recv() + if err != nil { + defer c.stream.Close() + return nil, err + } + res := msg.(*spannerpb.PartialResultSet) + return res, nil +} + +func (c *streamingReadRESTClient) Header() (metadata.MD, error) { + return c.md, nil +} + +func (c *streamingReadRESTClient) Trailer() metadata.MD { + return c.md +} + +func (c *streamingReadRESTClient) CloseSend() error { + // This is a no-op to fulfill the interface. + return fmt.Errorf("this method is not implemented for a server-stream") +} + +func (c *streamingReadRESTClient) Context() context.Context { + return c.ctx +} + +func (c *streamingReadRESTClient) SendMsg(m interface{}) error { + // This is a no-op to fulfill the interface. + return fmt.Errorf("this method is not implemented for a server-stream") +} + +func (c *streamingReadRESTClient) RecvMsg(m interface{}) error { + // This is a no-op to fulfill the interface. + return fmt.Errorf("this method is not implemented, use Recv") +} + +// BeginTransaction begins a new transaction. This step can often be skipped: +// Read, ExecuteSql and +// Commit can begin a new transaction as a +// side-effect. +func (c *restClient) BeginTransaction(ctx context.Context, req *spannerpb.BeginTransactionRequest, opts ...gax.CallOption) (*spannerpb.Transaction, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:beginTransaction", req.GetSession()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "session", url.QueryEscape(req.GetSession()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).BeginTransaction[0:len((*c.CallOptions).BeginTransaction):len((*c.CallOptions).BeginTransaction)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &spannerpb.Transaction{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// Commit commits a transaction. The request includes the mutations to be +// applied to rows in the database. +// +// Commit might return an ABORTED error. This can occur at any time; +// commonly, the cause is conflicts with concurrent +// transactions. However, it can also happen for a variety of other +// reasons. If Commit returns ABORTED, the caller should re-attempt +// the transaction from the beginning, re-using the same session. +// +// On very rare occasions, Commit might return UNKNOWN. This can happen, +// for example, if the client job experiences a 1+ hour networking failure. +// At that point, Cloud Spanner has lost track of the transaction outcome and +// we recommend that you perform another read from the database to see the +// state of things as they are now. +func (c *restClient) Commit(ctx context.Context, req *spannerpb.CommitRequest, opts ...gax.CallOption) (*spannerpb.CommitResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:commit", req.GetSession()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "session", url.QueryEscape(req.GetSession()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).Commit[0:len((*c.CallOptions).Commit):len((*c.CallOptions).Commit)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &spannerpb.CommitResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// Rollback rolls back a transaction, releasing any locks it holds. It is a good +// idea to call this for any transaction that includes one or more +// Read or ExecuteSql requests and +// ultimately decides not to commit. +// +// Rollback returns OK if it successfully aborts the transaction, the +// transaction was already aborted, or the transaction is not +// found. Rollback never returns ABORTED. +func (c *restClient) Rollback(ctx context.Context, req *spannerpb.RollbackRequest, opts ...gax.CallOption) error { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:rollback", req.GetSession()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "session", url.QueryEscape(req.GetSession()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// PartitionQuery creates a set of partition tokens that can be used to execute a query +// operation in parallel. Each of the returned partition tokens can be used +// by ExecuteStreamingSql to specify a subset +// of the query result to read. The same session and read-only transaction +// must be used by the PartitionQueryRequest used to create the +// partition tokens and the ExecuteSqlRequests that use the partition tokens. +// +// Partition tokens become invalid when the session used to create them +// is deleted, is idle for too long, begins a new transaction, or becomes too +// old. When any of these happen, it is not possible to resume the query, and +// the whole operation must be restarted from the beginning. +func (c *restClient) PartitionQuery(ctx context.Context, req *spannerpb.PartitionQueryRequest, opts ...gax.CallOption) (*spannerpb.PartitionResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:partitionQuery", req.GetSession()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "session", url.QueryEscape(req.GetSession()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).PartitionQuery[0:len((*c.CallOptions).PartitionQuery):len((*c.CallOptions).PartitionQuery)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &spannerpb.PartitionResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// PartitionRead creates a set of partition tokens that can be used to execute a read +// operation in parallel. Each of the returned partition tokens can be used +// by StreamingRead to specify a subset of the read +// result to read. The same session and read-only transaction must be used by +// the PartitionReadRequest used to create the partition tokens and the +// ReadRequests that use the partition tokens. There are no ordering +// guarantees on rows returned among the returned partition tokens, or even +// within each individual StreamingRead call issued with a partition_token. +// +// Partition tokens become invalid when the session used to create them +// is deleted, is idle for too long, begins a new transaction, or becomes too +// old. When any of these happen, it is not possible to resume the read, and +// the whole operation must be restarted from the beginning. +func (c *restClient) PartitionRead(ctx context.Context, req *spannerpb.PartitionReadRequest, opts ...gax.CallOption) (*spannerpb.PartitionResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:partitionRead", req.GetSession()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "session", url.QueryEscape(req.GetSession()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).PartitionRead[0:len((*c.CallOptions).PartitionRead):len((*c.CallOptions).PartitionRead)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &spannerpb.PartitionResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + // SessionIterator manages a stream of *spannerpb.Session. type SessionIterator struct { items []*spannerpb.Session diff --git a/spanner/apiv1/spanner_client_example_test.go b/spanner/apiv1/spanner_client_example_test.go index 0d7910010620..7b0bbb45972a 100644 --- a/spanner/apiv1/spanner_client_example_test.go +++ b/spanner/apiv1/spanner_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := spanner.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_CreateSession() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/spanner/apiv1/spannerpb/commit_response.pb.go b/spanner/apiv1/spannerpb/commit_response.pb.go index 9f68d93bd73f..a3fffa207cc4 100644 --- a/spanner/apiv1/spannerpb/commit_response.pb.go +++ b/spanner/apiv1/spannerpb/commit_response.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/spanner/v1/commit_response.proto package spannerpb diff --git a/spanner/apiv1/spannerpb/keys.pb.go b/spanner/apiv1/spannerpb/keys.pb.go index 343fb421bec1..12eadfd8a37d 100644 --- a/spanner/apiv1/spannerpb/keys.pb.go +++ b/spanner/apiv1/spannerpb/keys.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/spanner/v1/keys.proto package spannerpb @@ -132,14 +132,12 @@ type KeyRange struct { // The start key must be provided. It can be either closed or open. // // Types that are assignable to StartKeyType: - // // *KeyRange_StartClosed // *KeyRange_StartOpen StartKeyType isKeyRange_StartKeyType `protobuf_oneof:"start_key_type"` // The end key must be provided. It can be either closed or open. // // Types that are assignable to EndKeyType: - // // *KeyRange_EndClosed // *KeyRange_EndOpen EndKeyType isKeyRange_EndKeyType `protobuf_oneof:"end_key_type"` diff --git a/spanner/apiv1/spannerpb/mutation.pb.go b/spanner/apiv1/spannerpb/mutation.pb.go index 3a12d6c9ac47..efc5ad2a69ef 100644 --- a/spanner/apiv1/spannerpb/mutation.pb.go +++ b/spanner/apiv1/spannerpb/mutation.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/spanner/v1/mutation.proto package spannerpb @@ -48,7 +48,6 @@ type Mutation struct { // Required. The operation to perform. // // Types that are assignable to Operation: - // // *Mutation_Insert // *Mutation_Update // *Mutation_InsertOrUpdate diff --git a/spanner/apiv1/spannerpb/query_plan.pb.go b/spanner/apiv1/spannerpb/query_plan.pb.go index 99b55ec6aea1..8385b1e7e9b5 100644 --- a/spanner/apiv1/spannerpb/query_plan.pb.go +++ b/spanner/apiv1/spannerpb/query_plan.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/spanner/v1/query_plan.proto package spannerpb @@ -119,10 +119,10 @@ type PlanNode struct { // For example, a Parameter Reference node could have the following // information in its metadata: // - // { - // "parameter_reference": "param1", - // "parameter_type": "array" - // } + // { + // "parameter_reference": "param1", + // "parameter_type": "array" + // } Metadata *structpb.Struct `protobuf:"bytes,6,opt,name=metadata,proto3" json:"metadata,omitempty"` // The execution statistics associated with the node, contained in a group of // key-value pairs. Only present if the plan was returned as a result of a diff --git a/spanner/apiv1/spannerpb/result_set.pb.go b/spanner/apiv1/spannerpb/result_set.pb.go index c25855a99d93..f8933c1da12d 100644 --- a/spanner/apiv1/spannerpb/result_set.pb.go +++ b/spanner/apiv1/spannerpb/result_set.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/spanner/v1/result_set.proto package spannerpb @@ -142,60 +142,60 @@ type PartialResultSet struct { // field. Two or more chunked values can be merged to form a // complete value as follows: // - // - `bool/number/null`: cannot be chunked - // - `string`: concatenate the strings - // - `list`: concatenate the lists. If the last element in a list is a + // * `bool/number/null`: cannot be chunked + // * `string`: concatenate the strings + // * `list`: concatenate the lists. If the last element in a list is a // `string`, `list`, or `object`, merge it with the first element in // the next list by applying these rules recursively. - // - `object`: concatenate the (field name, field value) pairs. If a + // * `object`: concatenate the (field name, field value) pairs. If a // field name is duplicated, then apply these rules recursively // to merge the field values. // // Some examples of merging: // - // # Strings are concatenated. - // "foo", "bar" => "foobar" + // # Strings are concatenated. + // "foo", "bar" => "foobar" // - // # Lists of non-strings are concatenated. - // [2, 3], [4] => [2, 3, 4] + // # Lists of non-strings are concatenated. + // [2, 3], [4] => [2, 3, 4] // - // # Lists are concatenated, but the last and first elements are merged - // # because they are strings. - // ["a", "b"], ["c", "d"] => ["a", "bc", "d"] + // # Lists are concatenated, but the last and first elements are merged + // # because they are strings. + // ["a", "b"], ["c", "d"] => ["a", "bc", "d"] // - // # Lists are concatenated, but the last and first elements are merged - // # because they are lists. Recursively, the last and first elements - // # of the inner lists are merged because they are strings. - // ["a", ["b", "c"]], [["d"], "e"] => ["a", ["b", "cd"], "e"] + // # Lists are concatenated, but the last and first elements are merged + // # because they are lists. Recursively, the last and first elements + // # of the inner lists are merged because they are strings. + // ["a", ["b", "c"]], [["d"], "e"] => ["a", ["b", "cd"], "e"] // - // # Non-overlapping object fields are combined. - // {"a": "1"}, {"b": "2"} => {"a": "1", "b": 2"} + // # Non-overlapping object fields are combined. + // {"a": "1"}, {"b": "2"} => {"a": "1", "b": 2"} // - // # Overlapping object fields are merged. - // {"a": "1"}, {"a": "2"} => {"a": "12"} + // # Overlapping object fields are merged. + // {"a": "1"}, {"a": "2"} => {"a": "12"} // - // # Examples of merging objects containing lists of strings. - // {"a": ["1"]}, {"a": ["2"]} => {"a": ["12"]} + // # Examples of merging objects containing lists of strings. + // {"a": ["1"]}, {"a": ["2"]} => {"a": ["12"]} // // For a more complete example, suppose a streaming SQL query is // yielding a result set whose rows contain a single string // field. The following `PartialResultSet`s might be yielded: // - // { - // "metadata": { ... } - // "values": ["Hello", "W"] - // "chunked_value": true - // "resume_token": "Af65..." - // } - // { - // "values": ["orl"] - // "chunked_value": true - // "resume_token": "Bqp2..." - // } - // { - // "values": ["d"] - // "resume_token": "Zx1B..." - // } + // { + // "metadata": { ... } + // "values": ["Hello", "W"] + // "chunked_value": true + // "resume_token": "Af65..." + // } + // { + // "values": ["orl"] + // "chunked_value": true + // "resume_token": "Bqp2..." + // } + // { + // "values": ["d"] + // "resume_token": "Zx1B..." + // } // // This sequence of `PartialResultSet`s encodes two rows, one // containing the field value `"Hello"`, and a second containing the @@ -297,10 +297,10 @@ type ResultSetMetadata struct { // set. For example, a SQL query like `"SELECT UserId, UserName FROM // Users"` could return a `row_type` value like: // - // "fields": [ - // { "name": "UserId", "type": { "code": "INT64" } }, - // { "name": "UserName", "type": { "code": "STRING" } }, - // ] + // "fields": [ + // { "name": "UserId", "type": { "code": "INT64" } }, + // { "name": "UserName", "type": { "code": "STRING" } }, + // ] RowType *StructType `protobuf:"bytes,1,opt,name=row_type,json=rowType,proto3" json:"row_type,omitempty"` // If the read or SQL query began a transaction as a side-effect, the // information about the new transaction is yielded here. @@ -311,10 +311,10 @@ type ResultSetMetadata struct { // Users where UserId = @userId and UserName = @userName "` could return a // `undeclared_parameters` value like: // - // "fields": [ - // { "name": "UserId", "type": { "code": "INT64" } }, - // { "name": "UserName", "type": { "code": "STRING" } }, - // ] + // "fields": [ + // { "name": "UserId", "type": { "code": "INT64" } }, + // { "name": "UserName", "type": { "code": "STRING" } }, + // ] UndeclaredParameters *StructType `protobuf:"bytes,3,opt,name=undeclared_parameters,json=undeclaredParameters,proto3" json:"undeclared_parameters,omitempty"` } @@ -383,16 +383,15 @@ type ResultSetStats struct { // the query is profiled. For example, a query could return the statistics as // follows: // - // { - // "rows_returned": "3", - // "elapsed_time": "1.22 secs", - // "cpu_time": "1.19 secs" - // } + // { + // "rows_returned": "3", + // "elapsed_time": "1.22 secs", + // "cpu_time": "1.19 secs" + // } QueryStats *structpb.Struct `protobuf:"bytes,2,opt,name=query_stats,json=queryStats,proto3" json:"query_stats,omitempty"` // The number of rows modified by the DML statement. // // Types that are assignable to RowCount: - // // *ResultSetStats_RowCountExact // *ResultSetStats_RowCountLowerBound RowCount isResultSetStats_RowCount `protobuf_oneof:"row_count"` diff --git a/spanner/apiv1/spannerpb/spanner.pb.go b/spanner/apiv1/spannerpb/spanner.pb.go index 3a39b7efed6b..2e4ead3f26e1 100644 --- a/spanner/apiv1/spannerpb/spanner.pb.go +++ b/spanner/apiv1/spannerpb/spanner.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/spanner/v1/spanner.proto package spannerpb @@ -359,11 +359,11 @@ type Session struct { Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // The labels for the session. // - // - Label keys must be between 1 and 63 characters long and must conform to - // the following regular expression: `[a-z]([-a-z0-9]*[a-z0-9])?`. - // - Label values must be between 0 and 63 characters long and must conform - // to the regular expression `([a-z]([-a-z0-9]*[a-z0-9])?)?`. - // - No more than 64 labels can be associated with a given session. + // * Label keys must be between 1 and 63 characters long and must conform to + // the following regular expression: `[a-z]([-a-z0-9]*[a-z0-9])?`. + // * Label values must be between 0 and 63 characters long and must conform + // to the regular expression `([a-z]([-a-z0-9]*[a-z0-9])?)?`. + // * No more than 64 labels can be associated with a given session. // // See https://goo.gl/xmQnxf for more information on and examples of labels. Labels map[string]string `protobuf:"bytes,2,rep,name=labels,proto3" json:"labels,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` @@ -510,13 +510,13 @@ type ListSessionsRequest struct { // An expression for filtering the results of the request. Filter rules are // case insensitive. The fields eligible for filtering are: // - // - `labels.key` where key is the name of a label + // * `labels.key` where key is the name of a label // // Some examples of using filters are: // - // - `labels.env:*` --> The session has the label "env". - // - `labels.env:dev` --> The session has the label "env" and the value of - // the label contains the string "dev". + // * `labels.env:*` --> The session has the label "env". + // * `labels.env:dev` --> The session has the label "env" and the value of + // the label contains the string "dev". Filter string `protobuf:"bytes,4,opt,name=filter,proto3" json:"filter,omitempty"` } @@ -1806,7 +1806,6 @@ type CommitRequest struct { // Required. The transaction in which to commit. // // Types that are assignable to Transaction: - // // *CommitRequest_TransactionId // *CommitRequest_SingleUseTransaction Transaction isCommitRequest_Transaction `protobuf_oneof:"transaction"` diff --git a/spanner/apiv1/spannerpb/transaction.pb.go b/spanner/apiv1/spannerpb/transaction.pb.go index c96a9cfa0e3e..9789b1ca60bb 100644 --- a/spanner/apiv1/spannerpb/transaction.pb.go +++ b/spanner/apiv1/spannerpb/transaction.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/spanner/v1/transaction.proto package spannerpb @@ -431,7 +431,6 @@ type TransactionOptions struct { // Required. The type of transaction. // // Types that are assignable to Mode: - // // *TransactionOptions_ReadWrite_ // *TransactionOptions_PartitionedDml_ // *TransactionOptions_ReadOnly_ @@ -620,7 +619,6 @@ type TransactionSelector struct { // with strong concurrency. // // Types that are assignable to Selector: - // // *TransactionSelector_SingleUse // *TransactionSelector_Id // *TransactionSelector_Begin @@ -815,7 +813,6 @@ type TransactionOptions_ReadOnly struct { // How to choose the timestamp for the read-only transaction. // // Types that are assignable to TimestampBound: - // // *TransactionOptions_ReadOnly_Strong // *TransactionOptions_ReadOnly_MinReadTimestamp // *TransactionOptions_ReadOnly_MaxStaleness diff --git a/spanner/apiv1/spannerpb/type.pb.go b/spanner/apiv1/spannerpb/type.pb.go index c8e2610e2225..6ecc26d6816a 100644 --- a/spanner/apiv1/spannerpb/type.pb.go +++ b/spanner/apiv1/spannerpb/type.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/spanner/v1/type.proto package spannerpb @@ -91,11 +91,11 @@ const ( // Encoded as a JSON-formatted `string` as described in RFC 7159. The // following rules are applied when parsing JSON input: // - // - Whitespace characters are not preserved. - // - If a JSON object has duplicate keys, only the first key is preserved. - // - Members of a JSON object are not guaranteed to have their order - // preserved. - // - JSON array elements will have their order preserved. + // - Whitespace characters are not preserved. + // - If a JSON object has duplicate keys, only the first key is preserved. + // - Members of a JSON object are not guaranteed to have their order + // preserved. + // - JSON array elements will have their order preserved. TypeCode_JSON TypeCode = 11 ) diff --git a/speech/apiv1/adaptation_client.go b/speech/apiv1/adaptation_client.go index 17ef6523745a..85e3d943a029 100644 --- a/speech/apiv1/adaptation_client.go +++ b/speech/apiv1/adaptation_client.go @@ -17,19 +17,26 @@ package speech import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" speechpb "cloud.google.com/go/speech/apiv1/speechpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" + longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -47,6 +54,8 @@ type AdaptationCallOptions struct { ListCustomClasses []gax.CallOption UpdateCustomClass []gax.CallOption DeleteCustomClass []gax.CallOption + GetOperation []gax.CallOption + ListOperations []gax.CallOption } func defaultAdaptationGRPCClientOptions() []option.ClientOption { @@ -73,6 +82,25 @@ func defaultAdaptationCallOptions() *AdaptationCallOptions { ListCustomClasses: []gax.CallOption{}, UpdateCustomClass: []gax.CallOption{}, DeleteCustomClass: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + +func defaultAdaptationRESTCallOptions() *AdaptationCallOptions { + return &AdaptationCallOptions{ + CreatePhraseSet: []gax.CallOption{}, + GetPhraseSet: []gax.CallOption{}, + ListPhraseSet: []gax.CallOption{}, + UpdatePhraseSet: []gax.CallOption{}, + DeletePhraseSet: []gax.CallOption{}, + CreateCustomClass: []gax.CallOption{}, + GetCustomClass: []gax.CallOption{}, + ListCustomClasses: []gax.CallOption{}, + UpdateCustomClass: []gax.CallOption{}, + DeleteCustomClass: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, } } @@ -91,6 +119,8 @@ type internalAdaptationClient interface { ListCustomClasses(context.Context, *speechpb.ListCustomClassesRequest, ...gax.CallOption) *CustomClassIterator UpdateCustomClass(context.Context, *speechpb.UpdateCustomClassRequest, ...gax.CallOption) (*speechpb.CustomClass, error) DeleteCustomClass(context.Context, *speechpb.DeleteCustomClassRequest, ...gax.CallOption) error + GetOperation(context.Context, *longrunningpb.GetOperationRequest, ...gax.CallOption) (*longrunningpb.Operation, error) + ListOperations(context.Context, *longrunningpb.ListOperationsRequest, ...gax.CallOption) *OperationIterator } // AdaptationClient is a client for interacting with Cloud Speech-to-Text API. @@ -180,6 +210,16 @@ func (c *AdaptationClient) DeleteCustomClass(ctx context.Context, req *speechpb. return c.internalClient.DeleteCustomClass(ctx, req, opts...) } +// GetOperation is a utility method from google.longrunning.Operations. +func (c *AdaptationClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + return c.internalClient.GetOperation(ctx, req, opts...) +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *AdaptationClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + return c.internalClient.ListOperations(ctx, req, opts...) +} + // adaptationGRPCClient is a client for interacting with Cloud Speech-to-Text API over gRPC transport. // // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. @@ -196,6 +236,8 @@ type adaptationGRPCClient struct { // The gRPC API client. adaptationClient speechpb.AdaptationClient + operationsClient longrunningpb.OperationsClient + // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } @@ -230,6 +272,7 @@ func NewAdaptationClient(ctx context.Context, opts ...option.ClientOption) (*Ada disableDeadlines: disableDeadlines, adaptationClient: speechpb.NewAdaptationClient(connPool), CallOptions: &client.CallOptions, + operationsClient: longrunningpb.NewOperationsClient(connPool), } c.setGoogleClientInfo() @@ -261,6 +304,74 @@ func (c *adaptationGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type adaptationRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing AdaptationClient + CallOptions **AdaptationCallOptions +} + +// NewAdaptationRESTClient creates a new adaptation rest client. +// +// Service that implements Google Cloud Speech Adaptation API. +func NewAdaptationRESTClient(ctx context.Context, opts ...option.ClientOption) (*AdaptationClient, error) { + clientOpts := append(defaultAdaptationRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultAdaptationRESTCallOptions() + c := &adaptationRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &AdaptationClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultAdaptationRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://speech.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://speech.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://speech.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *adaptationRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *adaptationRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *adaptationRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *adaptationGRPCClient) CreatePhraseSet(ctx context.Context, req *speechpb.CreatePhraseSetRequest, opts ...gax.CallOption) (*speechpb.PhraseSet, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -479,6 +590,864 @@ func (c *adaptationGRPCClient) DeleteCustomClass(ctx context.Context, req *speec return err } +func (c *adaptationGRPCClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + 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 +} + +func (c *adaptationGRPCClient) 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{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + 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 + } + + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CreatePhraseSet create a set of phrase hints. Each item in the set can be a single word or +// a multi-word phrase. The items in the PhraseSet are favored by the +// recognition model when you send a call that includes the PhraseSet. +func (c *adaptationRESTClient) CreatePhraseSet(ctx context.Context, req *speechpb.CreatePhraseSetRequest, opts ...gax.CallOption) (*speechpb.PhraseSet, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/phraseSets", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreatePhraseSet[0:len((*c.CallOptions).CreatePhraseSet):len((*c.CallOptions).CreatePhraseSet)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &speechpb.PhraseSet{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetPhraseSet get a phrase set. +func (c *adaptationRESTClient) GetPhraseSet(ctx context.Context, req *speechpb.GetPhraseSetRequest, opts ...gax.CallOption) (*speechpb.PhraseSet, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetPhraseSet[0:len((*c.CallOptions).GetPhraseSet):len((*c.CallOptions).GetPhraseSet)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &speechpb.PhraseSet{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListPhraseSet list phrase sets. +func (c *adaptationRESTClient) ListPhraseSet(ctx context.Context, req *speechpb.ListPhraseSetRequest, opts ...gax.CallOption) *PhraseSetIterator { + it := &PhraseSetIterator{} + req = proto.Clone(req).(*speechpb.ListPhraseSetRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*speechpb.PhraseSet, string, error) { + resp := &speechpb.ListPhraseSetResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/phraseSets", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetPhraseSets(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// UpdatePhraseSet update a phrase set. +func (c *adaptationRESTClient) UpdatePhraseSet(ctx context.Context, req *speechpb.UpdatePhraseSetRequest, opts ...gax.CallOption) (*speechpb.PhraseSet, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetPhraseSet() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetPhraseSet().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "phrase_set.name", url.QueryEscape(req.GetPhraseSet().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdatePhraseSet[0:len((*c.CallOptions).UpdatePhraseSet):len((*c.CallOptions).UpdatePhraseSet)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &speechpb.PhraseSet{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeletePhraseSet delete a phrase set. +func (c *adaptationRESTClient) DeletePhraseSet(ctx context.Context, req *speechpb.DeletePhraseSetRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// CreateCustomClass create a custom class. +func (c *adaptationRESTClient) CreateCustomClass(ctx context.Context, req *speechpb.CreateCustomClassRequest, opts ...gax.CallOption) (*speechpb.CustomClass, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/customClasses", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateCustomClass[0:len((*c.CallOptions).CreateCustomClass):len((*c.CallOptions).CreateCustomClass)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &speechpb.CustomClass{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetCustomClass get a custom class. +func (c *adaptationRESTClient) GetCustomClass(ctx context.Context, req *speechpb.GetCustomClassRequest, opts ...gax.CallOption) (*speechpb.CustomClass, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetCustomClass[0:len((*c.CallOptions).GetCustomClass):len((*c.CallOptions).GetCustomClass)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &speechpb.CustomClass{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListCustomClasses list custom classes. +func (c *adaptationRESTClient) ListCustomClasses(ctx context.Context, req *speechpb.ListCustomClassesRequest, opts ...gax.CallOption) *CustomClassIterator { + it := &CustomClassIterator{} + req = proto.Clone(req).(*speechpb.ListCustomClassesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*speechpb.CustomClass, string, error) { + resp := &speechpb.ListCustomClassesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/customClasses", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetCustomClasses(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// UpdateCustomClass update a custom class. +func (c *adaptationRESTClient) UpdateCustomClass(ctx context.Context, req *speechpb.UpdateCustomClassRequest, opts ...gax.CallOption) (*speechpb.CustomClass, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetCustomClass() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetCustomClass().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "custom_class.name", url.QueryEscape(req.GetCustomClass().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateCustomClass[0:len((*c.CallOptions).UpdateCustomClass):len((*c.CallOptions).UpdateCustomClass)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &speechpb.CustomClass{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteCustomClass delete a custom class. +func (c *adaptationRESTClient) DeleteCustomClass(ctx context.Context, req *speechpb.DeleteCustomClassRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *adaptationRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/operations/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *adaptationRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/operations") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetName() != "" { + params.Add("name", fmt.Sprintf("%v", req.GetName())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + // CustomClassIterator manages a stream of *speechpb.CustomClass. type CustomClassIterator struct { items []*speechpb.CustomClass diff --git a/speech/apiv1/adaptation_client_example_test.go b/speech/apiv1/adaptation_client_example_test.go index e69e898ecdb0..dce14d263770 100644 --- a/speech/apiv1/adaptation_client_example_test.go +++ b/speech/apiv1/adaptation_client_example_test.go @@ -22,6 +22,7 @@ import ( speech "cloud.google.com/go/speech/apiv1" speechpb "cloud.google.com/go/speech/apiv1/speechpb" "google.golang.org/api/iterator" + longrunningpb "google.golang.org/genproto/googleapis/longrunning" ) func ExampleNewAdaptationClient() { @@ -41,6 +42,23 @@ func ExampleNewAdaptationClient() { _ = c } +func ExampleNewAdaptationRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := speech.NewAdaptationRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleAdaptationClient_CreatePhraseSet() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. @@ -298,3 +316,59 @@ func ExampleAdaptationClient_DeleteCustomClass() { // TODO: Handle error. } } + +func ExampleAdaptationClient_GetOperation() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := speech.NewAdaptationClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + req := &longrunningpb.GetOperationRequest{ + // TODO: Fill request struct fields. + // See https://pkg.go.dev/google.golang.org/genproto/googleapis/longrunning#GetOperationRequest. + } + resp, err := c.GetOperation(ctx, req) + if err != nil { + // TODO: Handle error. + } + // TODO: Use resp. + _ = resp +} + +func ExampleAdaptationClient_ListOperations() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := speech.NewAdaptationClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + req := &longrunningpb.ListOperationsRequest{ + // TODO: Fill request struct fields. + // See https://pkg.go.dev/google.golang.org/genproto/googleapis/longrunning#ListOperationsRequest. + } + 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 + } +} diff --git a/speech/apiv1/doc.go b/speech/apiv1/doc.go index b4977d031bbf..3db6665aafed 100644 --- a/speech/apiv1/doc.go +++ b/speech/apiv1/doc.go @@ -80,6 +80,8 @@ package speech // import "cloud.google.com/go/speech/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -168,3 +170,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/speech/apiv1/gapic_metadata.json b/speech/apiv1/gapic_metadata.json index 20a2770f0b49..b1114f467846 100644 --- a/speech/apiv1/gapic_metadata.json +++ b/speech/apiv1/gapic_metadata.json @@ -35,6 +35,11 @@ "GetCustomClass" ] }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, "GetPhraseSet": { "methods": [ "GetPhraseSet" @@ -45,6 +50,76 @@ "ListCustomClasses" ] }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "ListPhraseSet": { + "methods": [ + "ListPhraseSet" + ] + }, + "UpdateCustomClass": { + "methods": [ + "UpdateCustomClass" + ] + }, + "UpdatePhraseSet": { + "methods": [ + "UpdatePhraseSet" + ] + } + } + }, + "rest": { + "libraryClient": "AdaptationClient", + "rpcs": { + "CreateCustomClass": { + "methods": [ + "CreateCustomClass" + ] + }, + "CreatePhraseSet": { + "methods": [ + "CreatePhraseSet" + ] + }, + "DeleteCustomClass": { + "methods": [ + "DeleteCustomClass" + ] + }, + "DeletePhraseSet": { + "methods": [ + "DeletePhraseSet" + ] + }, + "GetCustomClass": { + "methods": [ + "GetCustomClass" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "GetPhraseSet": { + "methods": [ + "GetPhraseSet" + ] + }, + "ListCustomClasses": { + "methods": [ + "ListCustomClasses" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, "ListPhraseSet": { "methods": [ "ListPhraseSet" @@ -69,6 +144,46 @@ "grpc": { "libraryClient": "Client", "rpcs": { + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "LongRunningRecognize": { + "methods": [ + "LongRunningRecognize" + ] + }, + "Recognize": { + "methods": [ + "Recognize" + ] + }, + "StreamingRecognize": { + "methods": [ + "StreamingRecognize" + ] + } + } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, "LongRunningRecognize": { "methods": [ "LongRunningRecognize" diff --git a/speech/apiv1/speech_client.go b/speech/apiv1/speech_client.go index 99e5a7066d9a..26ef9a013e30 100644 --- a/speech/apiv1/speech_client.go +++ b/speech/apiv1/speech_client.go @@ -17,21 +17,31 @@ package speech import ( + "bytes" "context" + "fmt" + "io/ioutil" "math" + "net/http" + "net/url" "time" "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" speechpb "cloud.google.com/go/speech/apiv1/speechpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" + "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" + "google.golang.org/protobuf/proto" ) var newClientHook clientHook @@ -41,6 +51,8 @@ type CallOptions struct { Recognize []gax.CallOption LongRunningRecognize []gax.CallOption StreamingRecognize []gax.CallOption + GetOperation []gax.CallOption + ListOperations []gax.CallOption } func defaultGRPCClientOptions() []option.ClientOption { @@ -82,6 +94,38 @@ func defaultCallOptions() *CallOptions { }) }), }, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + Recognize: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + LongRunningRecognize: []gax.CallOption{}, + StreamingRecognize: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, } } @@ -94,6 +138,8 @@ type internalClient interface { LongRunningRecognize(context.Context, *speechpb.LongRunningRecognizeRequest, ...gax.CallOption) (*LongRunningRecognizeOperation, error) LongRunningRecognizeOperation(name string) *LongRunningRecognizeOperation StreamingRecognize(context.Context, ...gax.CallOption) (speechpb.Speech_StreamingRecognizeClient, error) + GetOperation(context.Context, *longrunningpb.GetOperationRequest, ...gax.CallOption) (*longrunningpb.Operation, error) + ListOperations(context.Context, *longrunningpb.ListOperationsRequest, ...gax.CallOption) *OperationIterator } // Client is a client for interacting with Cloud Speech-to-Text API. @@ -160,10 +206,22 @@ func (c *Client) LongRunningRecognizeOperation(name string) *LongRunningRecogniz // StreamingRecognize performs bidirectional streaming speech recognition: receive results while // sending audio. This method is only available via the gRPC API (not REST). +// +// This method is not supported for the REST transport. func (c *Client) StreamingRecognize(ctx context.Context, opts ...gax.CallOption) (speechpb.Speech_StreamingRecognizeClient, error) { return c.internalClient.StreamingRecognize(ctx, opts...) } +// GetOperation is a utility method from google.longrunning.Operations. +func (c *Client) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + return c.internalClient.GetOperation(ctx, req, opts...) +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *Client) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + return c.internalClient.ListOperations(ctx, req, opts...) +} + // gRPCClient is a client for interacting with Cloud Speech-to-Text API over gRPC transport. // // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. @@ -185,6 +243,8 @@ type gRPCClient struct { // Users should not Close this client. LROClient **lroauto.OperationsClient + operationsClient longrunningpb.OperationsClient + // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } @@ -219,6 +279,7 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error disableDeadlines: disableDeadlines, client: speechpb.NewSpeechClient(connPool), CallOptions: &client.CallOptions, + operationsClient: longrunningpb.NewOperationsClient(connPool), } c.setGoogleClientInfo() @@ -261,6 +322,89 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new speech rest client. +// +// Service that implements Google Cloud Speech API. +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://speech.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://speech.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://speech.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) Recognize(ctx context.Context, req *speechpb.RecognizeRequest, opts ...gax.CallOption) (*speechpb.RecognizeResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 5000000*time.Millisecond) @@ -318,9 +462,364 @@ func (c *gRPCClient) StreamingRecognize(ctx context.Context, opts ...gax.CallOpt return resp, nil } +func (c *gRPCClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + 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 +} + +func (c *gRPCClient) 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{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + 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 + } + + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// Recognize performs synchronous speech recognition: receive results after all audio +// has been sent and processed. +func (c *restClient) Recognize(ctx context.Context, req *speechpb.RecognizeRequest, opts ...gax.CallOption) (*speechpb.RecognizeResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/speech:recognize") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).Recognize[0:len((*c.CallOptions).Recognize):len((*c.CallOptions).Recognize)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &speechpb.RecognizeResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// LongRunningRecognize performs asynchronous speech recognition: receive results via the +// google.longrunning.Operations interface. Returns either an +// Operation.error or an Operation.response which contains +// a LongRunningRecognizeResponse message. +// For more information on asynchronous speech recognition, see the +// how-to (at https://cloud.google.com/speech-to-text/docs/async-recognize). +func (c *restClient) LongRunningRecognize(ctx context.Context, req *speechpb.LongRunningRecognizeRequest, opts ...gax.CallOption) (*LongRunningRecognizeOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/speech:longrunningrecognize") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/operations/%s", resp.GetName()) + return &LongRunningRecognizeOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// StreamingRecognize performs bidirectional streaming speech recognition: receive results while +// sending audio. This method is only available via the gRPC API (not REST). +// +// This method is not supported for the REST transport. +func (c *restClient) StreamingRecognize(ctx context.Context, opts ...gax.CallOption) (speechpb.Speech_StreamingRecognizeClient, error) { + return nil, fmt.Errorf("StreamingRecognize not yet supported for REST clients") +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *restClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/operations/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *restClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/operations") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetName() != "" { + params.Add("name", fmt.Sprintf("%v", req.GetName())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + // LongRunningRecognizeOperation manages a long-running operation from LongRunningRecognize. type LongRunningRecognizeOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // LongRunningRecognizeOperation returns a new LongRunningRecognizeOperation from a given name. @@ -331,10 +830,21 @@ func (c *gRPCClient) LongRunningRecognizeOperation(name string) *LongRunningReco } } +// LongRunningRecognizeOperation returns a new LongRunningRecognizeOperation from a given name. +// The name must be that of a previously created LongRunningRecognizeOperation, possibly from a different process. +func (c *restClient) LongRunningRecognizeOperation(name string) *LongRunningRecognizeOperation { + override := fmt.Sprintf("/v1/operations/%s", name) + return &LongRunningRecognizeOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *LongRunningRecognizeOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*speechpb.LongRunningRecognizeResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp speechpb.LongRunningRecognizeResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -352,6 +862,7 @@ func (op *LongRunningRecognizeOperation) Wait(ctx context.Context, opts ...gax.C // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *LongRunningRecognizeOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*speechpb.LongRunningRecognizeResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp speechpb.LongRunningRecognizeResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -386,3 +897,50 @@ func (op *LongRunningRecognizeOperation) Done() bool { func (op *LongRunningRecognizeOperation) Name() string { return op.lro.Name() } + +// OperationIterator manages a stream of *longrunningpb.Operation. +type OperationIterator struct { + items []*longrunningpb.Operation + pageInfo *iterator.PageInfo + nextFunc func() error + + // Response is the raw response for the current page. + // It must be cast to the RPC response type. + // Calling Next() or InternalFetch() updates this value. + Response interface{} + + // 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 +} diff --git a/speech/apiv1/speech_client_example_test.go b/speech/apiv1/speech_client_example_test.go index 374b5406c23a..aba92c2491fb 100644 --- a/speech/apiv1/speech_client_example_test.go +++ b/speech/apiv1/speech_client_example_test.go @@ -22,6 +22,8 @@ import ( speech "cloud.google.com/go/speech/apiv1" speechpb "cloud.google.com/go/speech/apiv1/speechpb" + "google.golang.org/api/iterator" + longrunningpb "google.golang.org/genproto/googleapis/longrunning" ) func ExampleNewClient() { @@ -41,6 +43,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := speech.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_Recognize() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. @@ -135,3 +154,59 @@ func ExampleClient_StreamingRecognize() { _ = resp } } + +func ExampleClient_GetOperation() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := speech.NewClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + req := &longrunningpb.GetOperationRequest{ + // TODO: Fill request struct fields. + // See https://pkg.go.dev/google.golang.org/genproto/googleapis/longrunning#GetOperationRequest. + } + resp, err := c.GetOperation(ctx, req) + if err != nil { + // TODO: Handle error. + } + // TODO: Use resp. + _ = resp +} + +func ExampleClient_ListOperations() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := speech.NewClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + req := &longrunningpb.ListOperationsRequest{ + // TODO: Fill request struct fields. + // See https://pkg.go.dev/google.golang.org/genproto/googleapis/longrunning#ListOperationsRequest. + } + 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 + } +} diff --git a/speech/apiv1/speechpb/cloud_speech.pb.go b/speech/apiv1/speechpb/cloud_speech.pb.go index 5a3311100b68..50304236f505 100644 --- a/speech/apiv1/speechpb/cloud_speech.pb.go +++ b/speech/apiv1/speechpb/cloud_speech.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/speech/v1/cloud_speech.proto package speechpb @@ -621,7 +621,6 @@ type TranscriptOutputConfig struct { unknownFields protoimpl.UnknownFields // Types that are assignable to OutputType: - // // *TranscriptOutputConfig_GcsUri OutputType isTranscriptOutputConfig_OutputType `protobuf_oneof:"output_type"` } @@ -698,7 +697,6 @@ type StreamingRecognizeRequest struct { // The streaming request, which is either a streaming config or audio content. // // Types that are assignable to StreamingRequest: - // // *StreamingRecognizeRequest_StreamingConfig // *StreamingRecognizeRequest_AudioContent StreamingRequest isStreamingRecognizeRequest_StreamingRequest `protobuf_oneof:"streaming_request"` @@ -810,11 +808,11 @@ type StreamingRecognitionConfig struct { // otherwise an error is thrown. The `model` field in [`RecognitionConfig`][] // must be set to: // - // - `command_and_search` - // - `phone_call` AND additional field `useEnhanced`=`true` - // - The `model` field is left undefined. In this case the API auto-selects - // a model based on any other parameters that you set in - // `RecognitionConfig`. + // * `command_and_search` + // * `phone_call` AND additional field `useEnhanced`=`true` + // * The `model` field is left undefined. In this case the API auto-selects + // a model based on any other parameters that you set in + // `RecognitionConfig`. SingleUtterance bool `protobuf:"varint,2,opt,name=single_utterance,json=singleUtterance,proto3" json:"single_utterance,omitempty"` // If `true`, interim results (tentative hypotheses) may be // returned as they become available (these interim results are indicated with @@ -897,8 +895,7 @@ type RecognitionConfig struct { SampleRateHertz int32 `protobuf:"varint,2,opt,name=sample_rate_hertz,json=sampleRateHertz,proto3" json:"sample_rate_hertz,omitempty"` // The number of channels in the input audio data. // ONLY set this for MULTI-CHANNEL recognition. - // Valid values for LINEAR16 and FLAC are `1`-`8`. - // Valid values for OGG_OPUS are '1'-'254'. + // Valid values for LINEAR16, OGG_OPUS and FLAC are `1`-`8`. // Valid value for MULAW, AMR, AMR_WB and SPEEX_WITH_HEADER_BYTE is only `1`. // If `0` or omitted, defaults to one channel (mono). // Note: We only recognize the first channel by default. @@ -1000,53 +997,51 @@ type RecognitionConfig struct { // explicitly specified, then we auto-select a model based on the parameters // in the RecognitionConfig. // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // + // + // + // + // + // + // + // + // + // + // + // + // + // + // + // + // + // + // + // + // + // + // + // + // + // + // + // + // + // + // + // + // + // + // + // + // //
ModelDescription
latest_longBest for long form content like media or conversation.
latest_shortBest for short form content like commands or single shot directed - // speech.
command_and_searchBest for short queries such as voice commands or voice search.
phone_callBest for audio that originated from a phone call (typically - // recorded at an 8khz sampling rate).
videoBest for audio that originated from video or includes multiple - // speakers. Ideally the audio is recorded at a 16khz or greater - // sampling rate. This is a premium model that costs more than the - // standard rate.
defaultBest for audio that is not one of the specific audio models. - // For example, long-form audio. Ideally the audio is high-fidelity, - // recorded at a 16khz or greater sampling rate.
medical_conversationBest for audio that originated from a conversation between a - // medical provider and patient.
medical_dictationBest for audio that originated from dictation notes by a medical - // provider.
ModelDescription
latest_longBest for long form content like media or conversation.
latest_shortBest for short form content like commands or single shot directed + // speech.
command_and_searchBest for short queries such as voice commands or voice search.
phone_callBest for audio that originated from a phone call (typically + // recorded at an 8khz sampling rate).
videoBest for audio that originated from video or includes multiple + // speakers. Ideally the audio is recorded at a 16khz or greater + // sampling rate. This is a premium model that costs more than the + // standard rate.
defaultBest for audio that is not one of the specific audio models. + // For example, long-form audio. Ideally the audio is high-fidelity, + // recorded at a 16khz or greater sampling rate.
medical_conversationBest for audio that originated from a conversation between a + // medical provider and patient.
medical_dictationBest for audio that originated from dictation notes by a medical + // provider.
Model string `protobuf:"bytes,13,opt,name=model,proto3" json:"model,omitempty"` // Set to true to use an enhanced model for speech recognition. @@ -1523,7 +1518,6 @@ type RecognitionAudio struct { // Storage uri. // // Types that are assignable to AudioSource: - // // *RecognitionAudio_Content // *RecognitionAudio_Uri AudioSource isRecognitionAudio_AudioSource `protobuf_oneof:"audio_source"` @@ -1621,6 +1615,11 @@ type RecognizeResponse struct { Results []*SpeechRecognitionResult `protobuf:"bytes,2,rep,name=results,proto3" json:"results,omitempty"` // When available, billed audio seconds for the corresponding request. TotalBilledTime *durationpb.Duration `protobuf:"bytes,3,opt,name=total_billed_time,json=totalBilledTime,proto3" json:"total_billed_time,omitempty"` + // Provides information on adaptation behavior in response + SpeechAdaptationInfo *SpeechAdaptationInfo `protobuf:"bytes,7,opt,name=speech_adaptation_info,json=speechAdaptationInfo,proto3" json:"speech_adaptation_info,omitempty"` + // The ID associated with the request. This is a unique ID specific only to + // the given request. + RequestId int64 `protobuf:"varint,8,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"` } func (x *RecognizeResponse) Reset() { @@ -1669,6 +1668,20 @@ func (x *RecognizeResponse) GetTotalBilledTime() *durationpb.Duration { return nil } +func (x *RecognizeResponse) GetSpeechAdaptationInfo() *SpeechAdaptationInfo { + if x != nil { + return x.SpeechAdaptationInfo + } + return nil +} + +func (x *RecognizeResponse) GetRequestId() int64 { + if x != nil { + return x.RequestId + } + return 0 +} + // The only message returned to the client by the `LongRunningRecognize` method. // It contains the result as zero or more sequential `SpeechRecognitionResult` // messages. It is included in the `result.response` field of the `Operation` @@ -1688,6 +1701,11 @@ type LongRunningRecognizeResponse struct { OutputConfig *TranscriptOutputConfig `protobuf:"bytes,6,opt,name=output_config,json=outputConfig,proto3" json:"output_config,omitempty"` // If the transcript output fails this field contains the relevant error. OutputError *status.Status `protobuf:"bytes,7,opt,name=output_error,json=outputError,proto3" json:"output_error,omitempty"` + // Provides information on speech adaptation behavior in response + SpeechAdaptationInfo *SpeechAdaptationInfo `protobuf:"bytes,8,opt,name=speech_adaptation_info,json=speechAdaptationInfo,proto3" json:"speech_adaptation_info,omitempty"` + // The ID associated with the request. This is a unique ID specific only to + // the given request. + RequestId int64 `protobuf:"varint,9,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"` } func (x *LongRunningRecognizeResponse) Reset() { @@ -1750,6 +1768,20 @@ func (x *LongRunningRecognizeResponse) GetOutputError() *status.Status { return nil } +func (x *LongRunningRecognizeResponse) GetSpeechAdaptationInfo() *SpeechAdaptationInfo { + if x != nil { + return x.SpeechAdaptationInfo + } + return nil +} + +func (x *LongRunningRecognizeResponse) GetRequestId() int64 { + if x != nil { + return x.RequestId + } + return 0 +} + // Describes the progress of a long-running `LongRunningRecognize` call. It is // included in the `metadata` field of the `Operation` returned by the // `GetOperation` call of the `google::longrunning::Operations` service. @@ -1897,6 +1929,11 @@ type StreamingRecognizeResponse struct { // When available, billed audio seconds for the stream. // Set only if this is the last response in the stream. TotalBilledTime *durationpb.Duration `protobuf:"bytes,5,opt,name=total_billed_time,json=totalBilledTime,proto3" json:"total_billed_time,omitempty"` + // Provides information on adaptation behavior in response + SpeechAdaptationInfo *SpeechAdaptationInfo `protobuf:"bytes,9,opt,name=speech_adaptation_info,json=speechAdaptationInfo,proto3" json:"speech_adaptation_info,omitempty"` + // The ID associated with the request. This is a unique ID specific only to + // the given request. + RequestId int64 `protobuf:"varint,10,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"` } func (x *StreamingRecognizeResponse) Reset() { @@ -1959,6 +1996,20 @@ func (x *StreamingRecognizeResponse) GetTotalBilledTime() *durationpb.Duration { return nil } +func (x *StreamingRecognizeResponse) GetSpeechAdaptationInfo() *SpeechAdaptationInfo { + if x != nil { + return x.SpeechAdaptationInfo + } + return nil +} + +func (x *StreamingRecognizeResponse) GetRequestId() int64 { + if x != nil { + return x.RequestId + } + return 0 +} + // A streaming speech recognition result corresponding to a portion of the audio // that is currently being processed. type StreamingRecognitionResult struct { @@ -2337,6 +2388,66 @@ func (x *WordInfo) GetSpeakerTag() int32 { return 0 } +// Information on speech adaptation use in results +type SpeechAdaptationInfo struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // Whether there was a timeout when applying speech adaptation. If true, + // adaptation had no effect in the response transcript. + AdaptationTimeout bool `protobuf:"varint,1,opt,name=adaptation_timeout,json=adaptationTimeout,proto3" json:"adaptation_timeout,omitempty"` + // If set, returns a message specifying which part of the speech adaptation + // request timed out. + TimeoutMessage string `protobuf:"bytes,4,opt,name=timeout_message,json=timeoutMessage,proto3" json:"timeout_message,omitempty"` +} + +func (x *SpeechAdaptationInfo) Reset() { + *x = SpeechAdaptationInfo{} + if protoimpl.UnsafeEnabled { + mi := &file_google_cloud_speech_v1_cloud_speech_proto_msgTypes[18] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *SpeechAdaptationInfo) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SpeechAdaptationInfo) ProtoMessage() {} + +func (x *SpeechAdaptationInfo) ProtoReflect() protoreflect.Message { + mi := &file_google_cloud_speech_v1_cloud_speech_proto_msgTypes[18] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SpeechAdaptationInfo.ProtoReflect.Descriptor instead. +func (*SpeechAdaptationInfo) Descriptor() ([]byte, []int) { + return file_google_cloud_speech_v1_cloud_speech_proto_rawDescGZIP(), []int{18} +} + +func (x *SpeechAdaptationInfo) GetAdaptationTimeout() bool { + if x != nil { + return x.AdaptationTimeout + } + return false +} + +func (x *SpeechAdaptationInfo) GetTimeoutMessage() string { + if x != nil { + return x.TimeoutMessage + } + return "" +} + var File_google_cloud_speech_v1_cloud_speech_proto protoreflect.FileDescriptor var file_google_cloud_speech_v1_cloud_speech_proto_rawDesc = []byte{ @@ -2600,7 +2711,7 @@ var file_google_cloud_speech_v1_cloud_speech_proto_rawDesc = []byte{ 0x28, 0x0c, 0x48, 0x00, 0x52, 0x07, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x12, 0x12, 0x0a, 0x03, 0x75, 0x72, 0x69, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x48, 0x00, 0x52, 0x03, 0x75, 0x72, 0x69, 0x42, 0x0e, 0x0a, 0x0c, 0x61, 0x75, 0x64, 0x69, 0x6f, 0x5f, 0x73, 0x6f, 0x75, 0x72, 0x63, - 0x65, 0x22, 0xa5, 0x01, 0x0a, 0x11, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, 0x65, 0x52, + 0x65, 0x22, 0xa8, 0x02, 0x0a, 0x11, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x49, 0x0a, 0x07, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2f, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, @@ -2610,171 +2721,203 @@ var file_google_cloud_speech_v1_cloud_speech_proto_rawDesc = []byte{ 0x65, 0x64, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0f, 0x74, 0x6f, 0x74, 0x61, 0x6c, 0x42, - 0x69, 0x6c, 0x6c, 0x65, 0x64, 0x54, 0x69, 0x6d, 0x65, 0x22, 0xbc, 0x02, 0x0a, 0x1c, 0x4c, 0x6f, - 0x6e, 0x67, 0x52, 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, - 0x7a, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x49, 0x0a, 0x07, 0x72, 0x65, - 0x73, 0x75, 0x6c, 0x74, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2f, 0x2e, 0x67, 0x6f, - 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, - 0x68, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x70, 0x65, 0x65, 0x63, 0x68, 0x52, 0x65, 0x63, 0x6f, 0x67, - 0x6e, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x52, 0x07, 0x72, 0x65, - 0x73, 0x75, 0x6c, 0x74, 0x73, 0x12, 0x45, 0x0a, 0x11, 0x74, 0x6f, 0x74, 0x61, 0x6c, 0x5f, 0x62, - 0x69, 0x6c, 0x6c, 0x65, 0x64, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, - 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, - 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0f, 0x74, 0x6f, 0x74, - 0x61, 0x6c, 0x42, 0x69, 0x6c, 0x6c, 0x65, 0x64, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x53, 0x0a, 0x0d, - 0x6f, 0x75, 0x74, 0x70, 0x75, 0x74, 0x5f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x18, 0x06, 0x20, - 0x01, 0x28, 0x0b, 0x32, 0x2e, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, - 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, 0x31, 0x2e, 0x54, 0x72, 0x61, - 0x6e, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x4f, 0x75, 0x74, 0x70, 0x75, 0x74, 0x43, 0x6f, 0x6e, - 0x66, 0x69, 0x67, 0x52, 0x0c, 0x6f, 0x75, 0x74, 0x70, 0x75, 0x74, 0x43, 0x6f, 0x6e, 0x66, 0x69, - 0x67, 0x12, 0x35, 0x0a, 0x0c, 0x6f, 0x75, 0x74, 0x70, 0x75, 0x74, 0x5f, 0x65, 0x72, 0x72, 0x6f, - 0x72, 0x18, 0x07, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x12, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, - 0x2e, 0x72, 0x70, 0x63, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x0b, 0x6f, 0x75, 0x74, - 0x70, 0x75, 0x74, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x22, 0xe1, 0x01, 0x0a, 0x1c, 0x4c, 0x6f, 0x6e, - 0x67, 0x52, 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, - 0x65, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x12, 0x29, 0x0a, 0x10, 0x70, 0x72, 0x6f, - 0x67, 0x72, 0x65, 0x73, 0x73, 0x5f, 0x70, 0x65, 0x72, 0x63, 0x65, 0x6e, 0x74, 0x18, 0x01, 0x20, - 0x01, 0x28, 0x05, 0x52, 0x0f, 0x70, 0x72, 0x6f, 0x67, 0x72, 0x65, 0x73, 0x73, 0x50, 0x65, 0x72, - 0x63, 0x65, 0x6e, 0x74, 0x12, 0x39, 0x0a, 0x0a, 0x73, 0x74, 0x61, 0x72, 0x74, 0x5f, 0x74, 0x69, - 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, - 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, - 0x74, 0x61, 0x6d, 0x70, 0x52, 0x09, 0x73, 0x74, 0x61, 0x72, 0x74, 0x54, 0x69, 0x6d, 0x65, 0x12, - 0x44, 0x0a, 0x10, 0x6c, 0x61, 0x73, 0x74, 0x5f, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x5f, 0x74, - 0x69, 0x6d, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, - 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, - 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x0e, 0x6c, 0x61, 0x73, 0x74, 0x55, 0x70, 0x64, 0x61, 0x74, - 0x65, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x15, 0x0a, 0x03, 0x75, 0x72, 0x69, 0x18, 0x04, 0x20, 0x01, - 0x28, 0x09, 0x42, 0x03, 0xe0, 0x41, 0x03, 0x52, 0x03, 0x75, 0x72, 0x69, 0x22, 0x99, 0x03, 0x0a, - 0x1a, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, - 0x69, 0x7a, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x28, 0x0a, 0x05, 0x65, - 0x72, 0x72, 0x6f, 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x12, 0x2e, 0x67, 0x6f, 0x6f, - 0x67, 0x6c, 0x65, 0x2e, 0x72, 0x70, 0x63, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x05, - 0x65, 0x72, 0x72, 0x6f, 0x72, 0x12, 0x4c, 0x0a, 0x07, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x73, - 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x32, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, - 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, 0x31, 0x2e, - 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, - 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x52, 0x07, 0x72, 0x65, 0x73, 0x75, - 0x6c, 0x74, 0x73, 0x12, 0x6e, 0x0a, 0x11, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x5f, 0x65, 0x76, - 0x65, 0x6e, 0x74, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x42, + 0x69, 0x6c, 0x6c, 0x65, 0x64, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x62, 0x0a, 0x16, 0x73, 0x70, 0x65, + 0x65, 0x63, 0x68, 0x5f, 0x61, 0x64, 0x61, 0x70, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x69, + 0x6e, 0x66, 0x6f, 0x18, 0x07, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, + 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, + 0x76, 0x31, 0x2e, 0x53, 0x70, 0x65, 0x65, 0x63, 0x68, 0x41, 0x64, 0x61, 0x70, 0x74, 0x61, 0x74, + 0x69, 0x6f, 0x6e, 0x49, 0x6e, 0x66, 0x6f, 0x52, 0x14, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x41, + 0x64, 0x61, 0x70, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x49, 0x6e, 0x66, 0x6f, 0x12, 0x1d, 0x0a, + 0x0a, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x08, 0x20, 0x01, 0x28, + 0x03, 0x52, 0x09, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x49, 0x64, 0x22, 0xbf, 0x03, 0x0a, + 0x1c, 0x4c, 0x6f, 0x6e, 0x67, 0x52, 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x63, 0x6f, + 0x67, 0x6e, 0x69, 0x7a, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x49, 0x0a, + 0x07, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x2f, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, - 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x69, 0x6e, - 0x67, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, - 0x73, 0x65, 0x2e, 0x53, 0x70, 0x65, 0x65, 0x63, 0x68, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x54, 0x79, - 0x70, 0x65, 0x52, 0x0f, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x54, - 0x79, 0x70, 0x65, 0x12, 0x45, 0x0a, 0x11, 0x74, 0x6f, 0x74, 0x61, 0x6c, 0x5f, 0x62, 0x69, 0x6c, - 0x6c, 0x65, 0x64, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, - 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, - 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0f, 0x74, 0x6f, 0x74, 0x61, 0x6c, - 0x42, 0x69, 0x6c, 0x6c, 0x65, 0x64, 0x54, 0x69, 0x6d, 0x65, 0x22, 0x4c, 0x0a, 0x0f, 0x53, 0x70, - 0x65, 0x65, 0x63, 0x68, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x54, 0x79, 0x70, 0x65, 0x12, 0x1c, 0x0a, - 0x18, 0x53, 0x50, 0x45, 0x45, 0x43, 0x48, 0x5f, 0x45, 0x56, 0x45, 0x4e, 0x54, 0x5f, 0x55, 0x4e, - 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x1b, 0x0a, 0x17, 0x45, - 0x4e, 0x44, 0x5f, 0x4f, 0x46, 0x5f, 0x53, 0x49, 0x4e, 0x47, 0x4c, 0x45, 0x5f, 0x55, 0x54, 0x54, - 0x45, 0x52, 0x41, 0x4e, 0x43, 0x45, 0x10, 0x01, 0x22, 0xbd, 0x02, 0x0a, 0x1a, 0x53, 0x74, 0x72, - 0x65, 0x61, 0x6d, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x74, 0x69, 0x6f, - 0x6e, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x12, 0x58, 0x0a, 0x0c, 0x61, 0x6c, 0x74, 0x65, 0x72, - 0x6e, 0x61, 0x74, 0x69, 0x76, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x34, 0x2e, - 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, - 0x65, 0x63, 0x68, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x70, 0x65, 0x65, 0x63, 0x68, 0x52, 0x65, 0x63, - 0x6f, 0x67, 0x6e, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x41, 0x6c, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x74, - 0x69, 0x76, 0x65, 0x52, 0x0c, 0x61, 0x6c, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x74, 0x69, 0x76, 0x65, - 0x73, 0x12, 0x19, 0x0a, 0x08, 0x69, 0x73, 0x5f, 0x66, 0x69, 0x6e, 0x61, 0x6c, 0x18, 0x02, 0x20, - 0x01, 0x28, 0x08, 0x52, 0x07, 0x69, 0x73, 0x46, 0x69, 0x6e, 0x61, 0x6c, 0x12, 0x1c, 0x0a, 0x09, - 0x73, 0x74, 0x61, 0x62, 0x69, 0x6c, 0x69, 0x74, 0x79, 0x18, 0x03, 0x20, 0x01, 0x28, 0x02, 0x52, - 0x09, 0x73, 0x74, 0x61, 0x62, 0x69, 0x6c, 0x69, 0x74, 0x79, 0x12, 0x41, 0x0a, 0x0f, 0x72, 0x65, - 0x73, 0x75, 0x6c, 0x74, 0x5f, 0x65, 0x6e, 0x64, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x04, 0x20, + 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x70, 0x65, 0x65, 0x63, 0x68, 0x52, 0x65, + 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x52, + 0x07, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x73, 0x12, 0x45, 0x0a, 0x11, 0x74, 0x6f, 0x74, 0x61, + 0x6c, 0x5f, 0x62, 0x69, 0x6c, 0x6c, 0x65, 0x64, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, - 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0d, - 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x45, 0x6e, 0x64, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x1f, 0x0a, - 0x0b, 0x63, 0x68, 0x61, 0x6e, 0x6e, 0x65, 0x6c, 0x5f, 0x74, 0x61, 0x67, 0x18, 0x05, 0x20, 0x01, - 0x28, 0x05, 0x52, 0x0a, 0x63, 0x68, 0x61, 0x6e, 0x6e, 0x65, 0x6c, 0x54, 0x61, 0x67, 0x12, 0x28, - 0x0a, 0x0d, 0x6c, 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, 0x5f, 0x63, 0x6f, 0x64, 0x65, 0x18, - 0x06, 0x20, 0x01, 0x28, 0x09, 0x42, 0x03, 0xe0, 0x41, 0x03, 0x52, 0x0c, 0x6c, 0x61, 0x6e, 0x67, - 0x75, 0x61, 0x67, 0x65, 0x43, 0x6f, 0x64, 0x65, 0x22, 0x81, 0x02, 0x0a, 0x17, 0x53, 0x70, 0x65, - 0x65, 0x63, 0x68, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, - 0x73, 0x75, 0x6c, 0x74, 0x12, 0x58, 0x0a, 0x0c, 0x61, 0x6c, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x74, - 0x69, 0x76, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x34, 0x2e, 0x67, 0x6f, 0x6f, - 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, - 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x70, 0x65, 0x65, 0x63, 0x68, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, - 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x41, 0x6c, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x74, 0x69, 0x76, 0x65, - 0x52, 0x0c, 0x61, 0x6c, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x74, 0x69, 0x76, 0x65, 0x73, 0x12, 0x1f, - 0x0a, 0x0b, 0x63, 0x68, 0x61, 0x6e, 0x6e, 0x65, 0x6c, 0x5f, 0x74, 0x61, 0x67, 0x18, 0x02, 0x20, - 0x01, 0x28, 0x05, 0x52, 0x0a, 0x63, 0x68, 0x61, 0x6e, 0x6e, 0x65, 0x6c, 0x54, 0x61, 0x67, 0x12, - 0x41, 0x0a, 0x0f, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x5f, 0x65, 0x6e, 0x64, 0x5f, 0x74, 0x69, - 0x6d, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, - 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, - 0x69, 0x6f, 0x6e, 0x52, 0x0d, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x45, 0x6e, 0x64, 0x54, 0x69, - 0x6d, 0x65, 0x12, 0x28, 0x0a, 0x0d, 0x6c, 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, 0x5f, 0x63, - 0x6f, 0x64, 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x09, 0x42, 0x03, 0xe0, 0x41, 0x03, 0x52, 0x0c, - 0x6c, 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, 0x43, 0x6f, 0x64, 0x65, 0x22, 0x96, 0x01, 0x0a, - 0x1c, 0x53, 0x70, 0x65, 0x65, 0x63, 0x68, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x74, 0x69, - 0x6f, 0x6e, 0x41, 0x6c, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x74, 0x69, 0x76, 0x65, 0x12, 0x1e, 0x0a, - 0x0a, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, - 0x09, 0x52, 0x0a, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x12, 0x1e, 0x0a, - 0x0a, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x64, 0x65, 0x6e, 0x63, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, - 0x02, 0x52, 0x0a, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x64, 0x65, 0x6e, 0x63, 0x65, 0x12, 0x36, 0x0a, - 0x05, 0x77, 0x6f, 0x72, 0x64, 0x73, 0x18, 0x03, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x20, 0x2e, 0x67, - 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, - 0x63, 0x68, 0x2e, 0x76, 0x31, 0x2e, 0x57, 0x6f, 0x72, 0x64, 0x49, 0x6e, 0x66, 0x6f, 0x52, 0x05, - 0x77, 0x6f, 0x72, 0x64, 0x73, 0x22, 0xd4, 0x01, 0x0a, 0x08, 0x57, 0x6f, 0x72, 0x64, 0x49, 0x6e, - 0x66, 0x6f, 0x12, 0x38, 0x0a, 0x0a, 0x73, 0x74, 0x61, 0x72, 0x74, 0x5f, 0x74, 0x69, 0x6d, 0x65, - 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, - 0x6e, 0x52, 0x09, 0x73, 0x74, 0x61, 0x72, 0x74, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x34, 0x0a, 0x08, - 0x65, 0x6e, 0x64, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, + 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0f, + 0x74, 0x6f, 0x74, 0x61, 0x6c, 0x42, 0x69, 0x6c, 0x6c, 0x65, 0x64, 0x54, 0x69, 0x6d, 0x65, 0x12, + 0x53, 0x0a, 0x0d, 0x6f, 0x75, 0x74, 0x70, 0x75, 0x74, 0x5f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, + 0x18, 0x06, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2e, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, + 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, 0x31, 0x2e, + 0x54, 0x72, 0x61, 0x6e, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x4f, 0x75, 0x74, 0x70, 0x75, 0x74, + 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x0c, 0x6f, 0x75, 0x74, 0x70, 0x75, 0x74, 0x43, 0x6f, + 0x6e, 0x66, 0x69, 0x67, 0x12, 0x35, 0x0a, 0x0c, 0x6f, 0x75, 0x74, 0x70, 0x75, 0x74, 0x5f, 0x65, + 0x72, 0x72, 0x6f, 0x72, 0x18, 0x07, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x12, 0x2e, 0x67, 0x6f, 0x6f, + 0x67, 0x6c, 0x65, 0x2e, 0x72, 0x70, 0x63, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x0b, + 0x6f, 0x75, 0x74, 0x70, 0x75, 0x74, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x12, 0x62, 0x0a, 0x16, 0x73, + 0x70, 0x65, 0x65, 0x63, 0x68, 0x5f, 0x61, 0x64, 0x61, 0x70, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, + 0x5f, 0x69, 0x6e, 0x66, 0x6f, 0x18, 0x08, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2c, 0x2e, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, + 0x68, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x70, 0x65, 0x65, 0x63, 0x68, 0x41, 0x64, 0x61, 0x70, 0x74, + 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x49, 0x6e, 0x66, 0x6f, 0x52, 0x14, 0x73, 0x70, 0x65, 0x65, 0x63, + 0x68, 0x41, 0x64, 0x61, 0x70, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x49, 0x6e, 0x66, 0x6f, 0x12, + 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x09, 0x20, + 0x01, 0x28, 0x03, 0x52, 0x09, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x49, 0x64, 0x22, 0xe1, + 0x01, 0x0a, 0x1c, 0x4c, 0x6f, 0x6e, 0x67, 0x52, 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x52, 0x65, + 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, 0x65, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x12, + 0x29, 0x0a, 0x10, 0x70, 0x72, 0x6f, 0x67, 0x72, 0x65, 0x73, 0x73, 0x5f, 0x70, 0x65, 0x72, 0x63, + 0x65, 0x6e, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x05, 0x52, 0x0f, 0x70, 0x72, 0x6f, 0x67, 0x72, + 0x65, 0x73, 0x73, 0x50, 0x65, 0x72, 0x63, 0x65, 0x6e, 0x74, 0x12, 0x39, 0x0a, 0x0a, 0x73, 0x74, + 0x61, 0x72, 0x74, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, - 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x07, 0x65, 0x6e, 0x64, 0x54, 0x69, - 0x6d, 0x65, 0x12, 0x12, 0x0a, 0x04, 0x77, 0x6f, 0x72, 0x64, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, - 0x52, 0x04, 0x77, 0x6f, 0x72, 0x64, 0x12, 0x1e, 0x0a, 0x0a, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x64, - 0x65, 0x6e, 0x63, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x02, 0x52, 0x0a, 0x63, 0x6f, 0x6e, 0x66, - 0x69, 0x64, 0x65, 0x6e, 0x63, 0x65, 0x12, 0x24, 0x0a, 0x0b, 0x73, 0x70, 0x65, 0x61, 0x6b, 0x65, - 0x72, 0x5f, 0x74, 0x61, 0x67, 0x18, 0x05, 0x20, 0x01, 0x28, 0x05, 0x42, 0x03, 0xe0, 0x41, 0x03, - 0x52, 0x0a, 0x73, 0x70, 0x65, 0x61, 0x6b, 0x65, 0x72, 0x54, 0x61, 0x67, 0x32, 0xd1, 0x04, 0x0a, - 0x06, 0x53, 0x70, 0x65, 0x65, 0x63, 0x68, 0x12, 0x90, 0x01, 0x0a, 0x09, 0x52, 0x65, 0x63, 0x6f, - 0x67, 0x6e, 0x69, 0x7a, 0x65, 0x12, 0x28, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, - 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, 0x31, 0x2e, 0x52, - 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, - 0x29, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, - 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, 0x31, 0x2e, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, - 0x7a, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x2e, 0x82, 0xd3, 0xe4, 0x93, - 0x02, 0x19, 0x22, 0x14, 0x2f, 0x76, 0x31, 0x2f, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x3a, 0x72, - 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, 0x65, 0x3a, 0x01, 0x2a, 0xda, 0x41, 0x0c, 0x63, 0x6f, - 0x6e, 0x66, 0x69, 0x67, 0x2c, 0x61, 0x75, 0x64, 0x69, 0x6f, 0x12, 0xe4, 0x01, 0x0a, 0x14, 0x4c, - 0x6f, 0x6e, 0x67, 0x52, 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, - 0x69, 0x7a, 0x65, 0x12, 0x33, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, - 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, 0x31, 0x2e, 0x4c, 0x6f, 0x6e, - 0x67, 0x52, 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, - 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x1d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, - 0x65, 0x2e, 0x6c, 0x6f, 0x6e, 0x67, 0x72, 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x2e, 0x4f, 0x70, - 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x22, 0x78, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x24, 0x22, - 0x1f, 0x2f, 0x76, 0x31, 0x2f, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x3a, 0x6c, 0x6f, 0x6e, 0x67, - 0x72, 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x72, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, 0x65, - 0x3a, 0x01, 0x2a, 0xda, 0x41, 0x0c, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2c, 0x61, 0x75, 0x64, - 0x69, 0x6f, 0xca, 0x41, 0x3c, 0x0a, 0x1c, 0x4c, 0x6f, 0x6e, 0x67, 0x52, 0x75, 0x6e, 0x6e, 0x69, - 0x6e, 0x67, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, - 0x6e, 0x73, 0x65, 0x12, 0x1c, 0x4c, 0x6f, 0x6e, 0x67, 0x52, 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, - 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, 0x65, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, - 0x61, 0x12, 0x81, 0x01, 0x0a, 0x12, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x69, 0x6e, 0x67, 0x52, - 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, 0x65, 0x12, 0x31, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, + 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x09, 0x73, 0x74, 0x61, 0x72, + 0x74, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x44, 0x0a, 0x10, 0x6c, 0x61, 0x73, 0x74, 0x5f, 0x75, 0x70, + 0x64, 0x61, 0x74, 0x65, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, + 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, + 0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x0e, 0x6c, 0x61, 0x73, + 0x74, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x15, 0x0a, 0x03, 0x75, + 0x72, 0x69, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x42, 0x03, 0xe0, 0x41, 0x03, 0x52, 0x03, 0x75, + 0x72, 0x69, 0x22, 0x9c, 0x04, 0x0a, 0x1a, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x69, 0x6e, 0x67, + 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, + 0x65, 0x12, 0x28, 0x0a, 0x05, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, + 0x32, 0x12, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x72, 0x70, 0x63, 0x2e, 0x53, 0x74, + 0x61, 0x74, 0x75, 0x73, 0x52, 0x05, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x12, 0x4c, 0x0a, 0x07, 0x72, + 0x65, 0x73, 0x75, 0x6c, 0x74, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x32, 0x2e, 0x67, + 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, + 0x63, 0x68, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x69, 0x6e, 0x67, 0x52, + 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, + 0x52, 0x07, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x73, 0x12, 0x6e, 0x0a, 0x11, 0x73, 0x70, 0x65, + 0x65, 0x63, 0x68, 0x5f, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x18, 0x04, + 0x20, 0x01, 0x28, 0x0e, 0x32, 0x42, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, + 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x74, + 0x72, 0x65, 0x61, 0x6d, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, 0x65, + 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x53, 0x70, 0x65, 0x65, 0x63, 0x68, 0x45, + 0x76, 0x65, 0x6e, 0x74, 0x54, 0x79, 0x70, 0x65, 0x52, 0x0f, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, + 0x45, 0x76, 0x65, 0x6e, 0x74, 0x54, 0x79, 0x70, 0x65, 0x12, 0x45, 0x0a, 0x11, 0x74, 0x6f, 0x74, + 0x61, 0x6c, 0x5f, 0x62, 0x69, 0x6c, 0x6c, 0x65, 0x64, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x05, + 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, + 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, + 0x0f, 0x74, 0x6f, 0x74, 0x61, 0x6c, 0x42, 0x69, 0x6c, 0x6c, 0x65, 0x64, 0x54, 0x69, 0x6d, 0x65, + 0x12, 0x62, 0x0a, 0x16, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x5f, 0x61, 0x64, 0x61, 0x70, 0x74, + 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x69, 0x6e, 0x66, 0x6f, 0x18, 0x09, 0x20, 0x01, 0x28, 0x0b, + 0x32, 0x2c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, + 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x70, 0x65, 0x65, 0x63, 0x68, + 0x41, 0x64, 0x61, 0x70, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x49, 0x6e, 0x66, 0x6f, 0x52, 0x14, + 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x41, 0x64, 0x61, 0x70, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, + 0x49, 0x6e, 0x66, 0x6f, 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x5f, + 0x69, 0x64, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x03, 0x52, 0x09, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, + 0x74, 0x49, 0x64, 0x22, 0x4c, 0x0a, 0x0f, 0x53, 0x70, 0x65, 0x65, 0x63, 0x68, 0x45, 0x76, 0x65, + 0x6e, 0x74, 0x54, 0x79, 0x70, 0x65, 0x12, 0x1c, 0x0a, 0x18, 0x53, 0x50, 0x45, 0x45, 0x43, 0x48, + 0x5f, 0x45, 0x56, 0x45, 0x4e, 0x54, 0x5f, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, + 0x45, 0x44, 0x10, 0x00, 0x12, 0x1b, 0x0a, 0x17, 0x45, 0x4e, 0x44, 0x5f, 0x4f, 0x46, 0x5f, 0x53, + 0x49, 0x4e, 0x47, 0x4c, 0x45, 0x5f, 0x55, 0x54, 0x54, 0x45, 0x52, 0x41, 0x4e, 0x43, 0x45, 0x10, + 0x01, 0x22, 0xbd, 0x02, 0x0a, 0x1a, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x69, 0x6e, 0x67, 0x52, + 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, + 0x12, 0x58, 0x0a, 0x0c, 0x61, 0x6c, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x74, 0x69, 0x76, 0x65, 0x73, + 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x34, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, + 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, 0x31, 0x2e, + 0x53, 0x70, 0x65, 0x65, 0x63, 0x68, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x74, 0x69, 0x6f, + 0x6e, 0x41, 0x6c, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x74, 0x69, 0x76, 0x65, 0x52, 0x0c, 0x61, 0x6c, + 0x74, 0x65, 0x72, 0x6e, 0x61, 0x74, 0x69, 0x76, 0x65, 0x73, 0x12, 0x19, 0x0a, 0x08, 0x69, 0x73, + 0x5f, 0x66, 0x69, 0x6e, 0x61, 0x6c, 0x18, 0x02, 0x20, 0x01, 0x28, 0x08, 0x52, 0x07, 0x69, 0x73, + 0x46, 0x69, 0x6e, 0x61, 0x6c, 0x12, 0x1c, 0x0a, 0x09, 0x73, 0x74, 0x61, 0x62, 0x69, 0x6c, 0x69, + 0x74, 0x79, 0x18, 0x03, 0x20, 0x01, 0x28, 0x02, 0x52, 0x09, 0x73, 0x74, 0x61, 0x62, 0x69, 0x6c, + 0x69, 0x74, 0x79, 0x12, 0x41, 0x0a, 0x0f, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x5f, 0x65, 0x6e, + 0x64, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, + 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, + 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0d, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x45, + 0x6e, 0x64, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x1f, 0x0a, 0x0b, 0x63, 0x68, 0x61, 0x6e, 0x6e, 0x65, + 0x6c, 0x5f, 0x74, 0x61, 0x67, 0x18, 0x05, 0x20, 0x01, 0x28, 0x05, 0x52, 0x0a, 0x63, 0x68, 0x61, + 0x6e, 0x6e, 0x65, 0x6c, 0x54, 0x61, 0x67, 0x12, 0x28, 0x0a, 0x0d, 0x6c, 0x61, 0x6e, 0x67, 0x75, + 0x61, 0x67, 0x65, 0x5f, 0x63, 0x6f, 0x64, 0x65, 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, 0x42, 0x03, + 0xe0, 0x41, 0x03, 0x52, 0x0c, 0x6c, 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, 0x43, 0x6f, 0x64, + 0x65, 0x22, 0x81, 0x02, 0x0a, 0x17, 0x53, 0x70, 0x65, 0x65, 0x63, 0x68, 0x52, 0x65, 0x63, 0x6f, + 0x67, 0x6e, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x12, 0x58, 0x0a, + 0x0c, 0x61, 0x6c, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x74, 0x69, 0x76, 0x65, 0x73, 0x18, 0x01, 0x20, + 0x03, 0x28, 0x0b, 0x32, 0x34, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, + 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x70, 0x65, + 0x65, 0x63, 0x68, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x41, 0x6c, + 0x74, 0x65, 0x72, 0x6e, 0x61, 0x74, 0x69, 0x76, 0x65, 0x52, 0x0c, 0x61, 0x6c, 0x74, 0x65, 0x72, + 0x6e, 0x61, 0x74, 0x69, 0x76, 0x65, 0x73, 0x12, 0x1f, 0x0a, 0x0b, 0x63, 0x68, 0x61, 0x6e, 0x6e, + 0x65, 0x6c, 0x5f, 0x74, 0x61, 0x67, 0x18, 0x02, 0x20, 0x01, 0x28, 0x05, 0x52, 0x0a, 0x63, 0x68, + 0x61, 0x6e, 0x6e, 0x65, 0x6c, 0x54, 0x61, 0x67, 0x12, 0x41, 0x0a, 0x0f, 0x72, 0x65, 0x73, 0x75, + 0x6c, 0x74, 0x5f, 0x65, 0x6e, 0x64, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, + 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, + 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0d, 0x72, 0x65, + 0x73, 0x75, 0x6c, 0x74, 0x45, 0x6e, 0x64, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x28, 0x0a, 0x0d, 0x6c, + 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, 0x5f, 0x63, 0x6f, 0x64, 0x65, 0x18, 0x05, 0x20, 0x01, + 0x28, 0x09, 0x42, 0x03, 0xe0, 0x41, 0x03, 0x52, 0x0c, 0x6c, 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, + 0x65, 0x43, 0x6f, 0x64, 0x65, 0x22, 0x96, 0x01, 0x0a, 0x1c, 0x53, 0x70, 0x65, 0x65, 0x63, 0x68, + 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x41, 0x6c, 0x74, 0x65, 0x72, + 0x6e, 0x61, 0x74, 0x69, 0x76, 0x65, 0x12, 0x1e, 0x0a, 0x0a, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x63, + 0x72, 0x69, 0x70, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, 0x74, 0x72, 0x61, 0x6e, + 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x12, 0x1e, 0x0a, 0x0a, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x64, + 0x65, 0x6e, 0x63, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x02, 0x52, 0x0a, 0x63, 0x6f, 0x6e, 0x66, + 0x69, 0x64, 0x65, 0x6e, 0x63, 0x65, 0x12, 0x36, 0x0a, 0x05, 0x77, 0x6f, 0x72, 0x64, 0x73, 0x18, + 0x03, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x20, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, + 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, 0x31, 0x2e, 0x57, + 0x6f, 0x72, 0x64, 0x49, 0x6e, 0x66, 0x6f, 0x52, 0x05, 0x77, 0x6f, 0x72, 0x64, 0x73, 0x22, 0xd4, + 0x01, 0x0a, 0x08, 0x57, 0x6f, 0x72, 0x64, 0x49, 0x6e, 0x66, 0x6f, 0x12, 0x38, 0x0a, 0x0a, 0x73, + 0x74, 0x61, 0x72, 0x74, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, + 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, + 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x09, 0x73, 0x74, 0x61, 0x72, + 0x74, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x34, 0x0a, 0x08, 0x65, 0x6e, 0x64, 0x5f, 0x74, 0x69, 0x6d, + 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, + 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, + 0x6f, 0x6e, 0x52, 0x07, 0x65, 0x6e, 0x64, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x12, 0x0a, 0x04, 0x77, + 0x6f, 0x72, 0x64, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x77, 0x6f, 0x72, 0x64, 0x12, + 0x1e, 0x0a, 0x0a, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x64, 0x65, 0x6e, 0x63, 0x65, 0x18, 0x04, 0x20, + 0x01, 0x28, 0x02, 0x52, 0x0a, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x64, 0x65, 0x6e, 0x63, 0x65, 0x12, + 0x24, 0x0a, 0x0b, 0x73, 0x70, 0x65, 0x61, 0x6b, 0x65, 0x72, 0x5f, 0x74, 0x61, 0x67, 0x18, 0x05, + 0x20, 0x01, 0x28, 0x05, 0x42, 0x03, 0xe0, 0x41, 0x03, 0x52, 0x0a, 0x73, 0x70, 0x65, 0x61, 0x6b, + 0x65, 0x72, 0x54, 0x61, 0x67, 0x22, 0x6e, 0x0a, 0x14, 0x53, 0x70, 0x65, 0x65, 0x63, 0x68, 0x41, + 0x64, 0x61, 0x70, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x49, 0x6e, 0x66, 0x6f, 0x12, 0x2d, 0x0a, + 0x12, 0x61, 0x64, 0x61, 0x70, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x74, 0x69, 0x6d, 0x65, + 0x6f, 0x75, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x08, 0x52, 0x11, 0x61, 0x64, 0x61, 0x70, 0x74, + 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x54, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x12, 0x27, 0x0a, 0x0f, + 0x74, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x5f, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x18, + 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0e, 0x74, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x4d, 0x65, + 0x73, 0x73, 0x61, 0x67, 0x65, 0x32, 0xd1, 0x04, 0x0a, 0x06, 0x53, 0x70, 0x65, 0x65, 0x63, 0x68, + 0x12, 0x90, 0x01, 0x0a, 0x09, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, 0x65, 0x12, 0x28, + 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, + 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, 0x31, 0x2e, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, + 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x29, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, - 0x31, 0x2e, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x63, 0x6f, 0x67, - 0x6e, 0x69, 0x7a, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x32, 0x2e, 0x67, 0x6f, - 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, - 0x68, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x69, 0x6e, 0x67, 0x52, 0x65, - 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, - 0x00, 0x28, 0x01, 0x30, 0x01, 0x1a, 0x49, 0xca, 0x41, 0x15, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, - 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2e, 0x63, 0x6f, 0x6d, 0xd2, - 0x41, 0x2e, 0x68, 0x74, 0x74, 0x70, 0x73, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x67, 0x6f, - 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x61, 0x75, 0x74, - 0x68, 0x2f, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2d, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, - 0x42, 0x72, 0x0a, 0x1a, 0x63, 0x6f, 0x6d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, - 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, 0x31, 0x42, 0x0b, - 0x53, 0x70, 0x65, 0x65, 0x63, 0x68, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x3c, 0x67, - 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2e, 0x6f, 0x72, 0x67, - 0x2f, 0x67, 0x65, 0x6e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, - 0x61, 0x70, 0x69, 0x73, 0x2f, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2f, 0x73, 0x70, 0x65, 0x65, 0x63, - 0x68, 0x2f, 0x76, 0x31, 0x3b, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0xf8, 0x01, 0x01, 0xa2, 0x02, - 0x03, 0x47, 0x43, 0x53, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, + 0x31, 0x2e, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, + 0x6e, 0x73, 0x65, 0x22, 0x2e, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x19, 0x22, 0x14, 0x2f, 0x76, 0x31, + 0x2f, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x3a, 0x72, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, + 0x65, 0x3a, 0x01, 0x2a, 0xda, 0x41, 0x0c, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2c, 0x61, 0x75, + 0x64, 0x69, 0x6f, 0x12, 0xe4, 0x01, 0x0a, 0x14, 0x4c, 0x6f, 0x6e, 0x67, 0x52, 0x75, 0x6e, 0x6e, + 0x69, 0x6e, 0x67, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, 0x65, 0x12, 0x33, 0x2e, 0x67, + 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, + 0x63, 0x68, 0x2e, 0x76, 0x31, 0x2e, 0x4c, 0x6f, 0x6e, 0x67, 0x52, 0x75, 0x6e, 0x6e, 0x69, 0x6e, + 0x67, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, + 0x74, 0x1a, 0x1d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x6c, 0x6f, 0x6e, 0x67, 0x72, + 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x2e, 0x4f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, + 0x22, 0x78, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x24, 0x22, 0x1f, 0x2f, 0x76, 0x31, 0x2f, 0x73, 0x70, + 0x65, 0x65, 0x63, 0x68, 0x3a, 0x6c, 0x6f, 0x6e, 0x67, 0x72, 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, + 0x72, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, 0x65, 0x3a, 0x01, 0x2a, 0xda, 0x41, 0x0c, 0x63, + 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2c, 0x61, 0x75, 0x64, 0x69, 0x6f, 0xca, 0x41, 0x3c, 0x0a, 0x1c, + 0x4c, 0x6f, 0x6e, 0x67, 0x52, 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x63, 0x6f, 0x67, + 0x6e, 0x69, 0x7a, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x1c, 0x4c, 0x6f, + 0x6e, 0x67, 0x52, 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, + 0x7a, 0x65, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x12, 0x81, 0x01, 0x0a, 0x12, 0x53, + 0x74, 0x72, 0x65, 0x61, 0x6d, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, + 0x65, 0x12, 0x31, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, + 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x74, 0x72, 0x65, 0x61, + 0x6d, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, 0x65, 0x52, 0x65, 0x71, + 0x75, 0x65, 0x73, 0x74, 0x1a, 0x32, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, + 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x74, + 0x72, 0x65, 0x61, 0x6d, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, 0x65, + 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x28, 0x01, 0x30, 0x01, 0x1a, 0x49, + 0xca, 0x41, 0x15, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, + 0x61, 0x70, 0x69, 0x73, 0x2e, 0x63, 0x6f, 0x6d, 0xd2, 0x41, 0x2e, 0x68, 0x74, 0x74, 0x70, 0x73, + 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, + 0x73, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x61, 0x75, 0x74, 0x68, 0x2f, 0x63, 0x6c, 0x6f, 0x75, 0x64, + 0x2d, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x42, 0x72, 0x0a, 0x1a, 0x63, 0x6f, 0x6d, + 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, + 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, 0x31, 0x42, 0x0b, 0x53, 0x70, 0x65, 0x65, 0x63, 0x68, 0x50, + 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x3c, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x67, + 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x67, 0x65, 0x6e, 0x70, 0x72, 0x6f, + 0x74, 0x6f, 0x2f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2f, 0x63, 0x6c, + 0x6f, 0x75, 0x64, 0x2f, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2f, 0x76, 0x31, 0x3b, 0x73, 0x70, + 0x65, 0x65, 0x63, 0x68, 0xf8, 0x01, 0x01, 0xa2, 0x02, 0x03, 0x47, 0x43, 0x53, 0x62, 0x06, 0x70, + 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( @@ -2790,7 +2933,7 @@ func file_google_cloud_speech_v1_cloud_speech_proto_rawDescGZIP() []byte { } var file_google_cloud_speech_v1_cloud_speech_proto_enumTypes = make([]protoimpl.EnumInfo, 6) -var file_google_cloud_speech_v1_cloud_speech_proto_msgTypes = make([]protoimpl.MessageInfo, 18) +var file_google_cloud_speech_v1_cloud_speech_proto_msgTypes = make([]protoimpl.MessageInfo, 19) var file_google_cloud_speech_v1_cloud_speech_proto_goTypes = []interface{}{ (RecognitionConfig_AudioEncoding)(0), // 0: google.cloud.speech.v1.RecognitionConfig.AudioEncoding (RecognitionMetadata_InteractionType)(0), // 1: google.cloud.speech.v1.RecognitionMetadata.InteractionType @@ -2816,12 +2959,13 @@ var file_google_cloud_speech_v1_cloud_speech_proto_goTypes = []interface{}{ (*SpeechRecognitionResult)(nil), // 21: google.cloud.speech.v1.SpeechRecognitionResult (*SpeechRecognitionAlternative)(nil), // 22: google.cloud.speech.v1.SpeechRecognitionAlternative (*WordInfo)(nil), // 23: google.cloud.speech.v1.WordInfo - (*SpeechAdaptation)(nil), // 24: google.cloud.speech.v1.SpeechAdaptation - (*wrapperspb.BoolValue)(nil), // 25: google.protobuf.BoolValue - (*durationpb.Duration)(nil), // 26: google.protobuf.Duration - (*status.Status)(nil), // 27: google.rpc.Status - (*timestamppb.Timestamp)(nil), // 28: google.protobuf.Timestamp - (*longrunning.Operation)(nil), // 29: google.longrunning.Operation + (*SpeechAdaptationInfo)(nil), // 24: google.cloud.speech.v1.SpeechAdaptationInfo + (*SpeechAdaptation)(nil), // 25: google.cloud.speech.v1.SpeechAdaptation + (*wrapperspb.BoolValue)(nil), // 26: google.protobuf.BoolValue + (*durationpb.Duration)(nil), // 27: google.protobuf.Duration + (*status.Status)(nil), // 28: google.rpc.Status + (*timestamppb.Timestamp)(nil), // 29: google.protobuf.Timestamp + (*longrunning.Operation)(nil), // 30: google.longrunning.Operation } var file_google_cloud_speech_v1_cloud_speech_proto_depIdxs = []int32{ 11, // 0: google.cloud.speech.v1.RecognizeRequest.config:type_name -> google.cloud.speech.v1.RecognitionConfig @@ -2832,10 +2976,10 @@ var file_google_cloud_speech_v1_cloud_speech_proto_depIdxs = []int32{ 10, // 5: google.cloud.speech.v1.StreamingRecognizeRequest.streaming_config:type_name -> google.cloud.speech.v1.StreamingRecognitionConfig 11, // 6: google.cloud.speech.v1.StreamingRecognitionConfig.config:type_name -> google.cloud.speech.v1.RecognitionConfig 0, // 7: google.cloud.speech.v1.RecognitionConfig.encoding:type_name -> google.cloud.speech.v1.RecognitionConfig.AudioEncoding - 24, // 8: google.cloud.speech.v1.RecognitionConfig.adaptation:type_name -> google.cloud.speech.v1.SpeechAdaptation + 25, // 8: google.cloud.speech.v1.RecognitionConfig.adaptation:type_name -> google.cloud.speech.v1.SpeechAdaptation 14, // 9: google.cloud.speech.v1.RecognitionConfig.speech_contexts:type_name -> google.cloud.speech.v1.SpeechContext - 25, // 10: google.cloud.speech.v1.RecognitionConfig.enable_spoken_punctuation:type_name -> google.protobuf.BoolValue - 25, // 11: google.cloud.speech.v1.RecognitionConfig.enable_spoken_emojis:type_name -> google.protobuf.BoolValue + 26, // 10: google.cloud.speech.v1.RecognitionConfig.enable_spoken_punctuation:type_name -> google.protobuf.BoolValue + 26, // 11: google.cloud.speech.v1.RecognitionConfig.enable_spoken_emojis:type_name -> google.protobuf.BoolValue 12, // 12: google.cloud.speech.v1.RecognitionConfig.diarization_config:type_name -> google.cloud.speech.v1.SpeakerDiarizationConfig 13, // 13: google.cloud.speech.v1.RecognitionConfig.metadata:type_name -> google.cloud.speech.v1.RecognitionMetadata 1, // 14: google.cloud.speech.v1.RecognitionMetadata.interaction_type:type_name -> google.cloud.speech.v1.RecognitionMetadata.InteractionType @@ -2843,35 +2987,38 @@ var file_google_cloud_speech_v1_cloud_speech_proto_depIdxs = []int32{ 3, // 16: google.cloud.speech.v1.RecognitionMetadata.original_media_type:type_name -> google.cloud.speech.v1.RecognitionMetadata.OriginalMediaType 4, // 17: google.cloud.speech.v1.RecognitionMetadata.recording_device_type:type_name -> google.cloud.speech.v1.RecognitionMetadata.RecordingDeviceType 21, // 18: google.cloud.speech.v1.RecognizeResponse.results:type_name -> google.cloud.speech.v1.SpeechRecognitionResult - 26, // 19: google.cloud.speech.v1.RecognizeResponse.total_billed_time:type_name -> google.protobuf.Duration - 21, // 20: google.cloud.speech.v1.LongRunningRecognizeResponse.results:type_name -> google.cloud.speech.v1.SpeechRecognitionResult - 26, // 21: google.cloud.speech.v1.LongRunningRecognizeResponse.total_billed_time:type_name -> google.protobuf.Duration - 8, // 22: google.cloud.speech.v1.LongRunningRecognizeResponse.output_config:type_name -> google.cloud.speech.v1.TranscriptOutputConfig - 27, // 23: google.cloud.speech.v1.LongRunningRecognizeResponse.output_error:type_name -> google.rpc.Status - 28, // 24: google.cloud.speech.v1.LongRunningRecognizeMetadata.start_time:type_name -> google.protobuf.Timestamp - 28, // 25: google.cloud.speech.v1.LongRunningRecognizeMetadata.last_update_time:type_name -> google.protobuf.Timestamp - 27, // 26: google.cloud.speech.v1.StreamingRecognizeResponse.error:type_name -> google.rpc.Status - 20, // 27: google.cloud.speech.v1.StreamingRecognizeResponse.results:type_name -> google.cloud.speech.v1.StreamingRecognitionResult - 5, // 28: google.cloud.speech.v1.StreamingRecognizeResponse.speech_event_type:type_name -> google.cloud.speech.v1.StreamingRecognizeResponse.SpeechEventType - 26, // 29: google.cloud.speech.v1.StreamingRecognizeResponse.total_billed_time:type_name -> google.protobuf.Duration - 22, // 30: google.cloud.speech.v1.StreamingRecognitionResult.alternatives:type_name -> google.cloud.speech.v1.SpeechRecognitionAlternative - 26, // 31: google.cloud.speech.v1.StreamingRecognitionResult.result_end_time:type_name -> google.protobuf.Duration - 22, // 32: google.cloud.speech.v1.SpeechRecognitionResult.alternatives:type_name -> google.cloud.speech.v1.SpeechRecognitionAlternative - 26, // 33: google.cloud.speech.v1.SpeechRecognitionResult.result_end_time:type_name -> google.protobuf.Duration - 23, // 34: google.cloud.speech.v1.SpeechRecognitionAlternative.words:type_name -> google.cloud.speech.v1.WordInfo - 26, // 35: google.cloud.speech.v1.WordInfo.start_time:type_name -> google.protobuf.Duration - 26, // 36: google.cloud.speech.v1.WordInfo.end_time:type_name -> google.protobuf.Duration - 6, // 37: google.cloud.speech.v1.Speech.Recognize:input_type -> google.cloud.speech.v1.RecognizeRequest - 7, // 38: google.cloud.speech.v1.Speech.LongRunningRecognize:input_type -> google.cloud.speech.v1.LongRunningRecognizeRequest - 9, // 39: google.cloud.speech.v1.Speech.StreamingRecognize:input_type -> google.cloud.speech.v1.StreamingRecognizeRequest - 16, // 40: google.cloud.speech.v1.Speech.Recognize:output_type -> google.cloud.speech.v1.RecognizeResponse - 29, // 41: google.cloud.speech.v1.Speech.LongRunningRecognize:output_type -> google.longrunning.Operation - 19, // 42: google.cloud.speech.v1.Speech.StreamingRecognize:output_type -> google.cloud.speech.v1.StreamingRecognizeResponse - 40, // [40:43] is the sub-list for method output_type - 37, // [37:40] is the sub-list for method input_type - 37, // [37:37] is the sub-list for extension type_name - 37, // [37:37] is the sub-list for extension extendee - 0, // [0:37] is the sub-list for field type_name + 27, // 19: google.cloud.speech.v1.RecognizeResponse.total_billed_time:type_name -> google.protobuf.Duration + 24, // 20: google.cloud.speech.v1.RecognizeResponse.speech_adaptation_info:type_name -> google.cloud.speech.v1.SpeechAdaptationInfo + 21, // 21: google.cloud.speech.v1.LongRunningRecognizeResponse.results:type_name -> google.cloud.speech.v1.SpeechRecognitionResult + 27, // 22: google.cloud.speech.v1.LongRunningRecognizeResponse.total_billed_time:type_name -> google.protobuf.Duration + 8, // 23: google.cloud.speech.v1.LongRunningRecognizeResponse.output_config:type_name -> google.cloud.speech.v1.TranscriptOutputConfig + 28, // 24: google.cloud.speech.v1.LongRunningRecognizeResponse.output_error:type_name -> google.rpc.Status + 24, // 25: google.cloud.speech.v1.LongRunningRecognizeResponse.speech_adaptation_info:type_name -> google.cloud.speech.v1.SpeechAdaptationInfo + 29, // 26: google.cloud.speech.v1.LongRunningRecognizeMetadata.start_time:type_name -> google.protobuf.Timestamp + 29, // 27: google.cloud.speech.v1.LongRunningRecognizeMetadata.last_update_time:type_name -> google.protobuf.Timestamp + 28, // 28: google.cloud.speech.v1.StreamingRecognizeResponse.error:type_name -> google.rpc.Status + 20, // 29: google.cloud.speech.v1.StreamingRecognizeResponse.results:type_name -> google.cloud.speech.v1.StreamingRecognitionResult + 5, // 30: google.cloud.speech.v1.StreamingRecognizeResponse.speech_event_type:type_name -> google.cloud.speech.v1.StreamingRecognizeResponse.SpeechEventType + 27, // 31: google.cloud.speech.v1.StreamingRecognizeResponse.total_billed_time:type_name -> google.protobuf.Duration + 24, // 32: google.cloud.speech.v1.StreamingRecognizeResponse.speech_adaptation_info:type_name -> google.cloud.speech.v1.SpeechAdaptationInfo + 22, // 33: google.cloud.speech.v1.StreamingRecognitionResult.alternatives:type_name -> google.cloud.speech.v1.SpeechRecognitionAlternative + 27, // 34: google.cloud.speech.v1.StreamingRecognitionResult.result_end_time:type_name -> google.protobuf.Duration + 22, // 35: google.cloud.speech.v1.SpeechRecognitionResult.alternatives:type_name -> google.cloud.speech.v1.SpeechRecognitionAlternative + 27, // 36: google.cloud.speech.v1.SpeechRecognitionResult.result_end_time:type_name -> google.protobuf.Duration + 23, // 37: google.cloud.speech.v1.SpeechRecognitionAlternative.words:type_name -> google.cloud.speech.v1.WordInfo + 27, // 38: google.cloud.speech.v1.WordInfo.start_time:type_name -> google.protobuf.Duration + 27, // 39: google.cloud.speech.v1.WordInfo.end_time:type_name -> google.protobuf.Duration + 6, // 40: google.cloud.speech.v1.Speech.Recognize:input_type -> google.cloud.speech.v1.RecognizeRequest + 7, // 41: google.cloud.speech.v1.Speech.LongRunningRecognize:input_type -> google.cloud.speech.v1.LongRunningRecognizeRequest + 9, // 42: google.cloud.speech.v1.Speech.StreamingRecognize:input_type -> google.cloud.speech.v1.StreamingRecognizeRequest + 16, // 43: google.cloud.speech.v1.Speech.Recognize:output_type -> google.cloud.speech.v1.RecognizeResponse + 30, // 44: google.cloud.speech.v1.Speech.LongRunningRecognize:output_type -> google.longrunning.Operation + 19, // 45: google.cloud.speech.v1.Speech.StreamingRecognize:output_type -> google.cloud.speech.v1.StreamingRecognizeResponse + 43, // [43:46] is the sub-list for method output_type + 40, // [40:43] is the sub-list for method input_type + 40, // [40:40] is the sub-list for extension type_name + 40, // [40:40] is the sub-list for extension extendee + 0, // [0:40] is the sub-list for field type_name } func init() { file_google_cloud_speech_v1_cloud_speech_proto_init() } @@ -3097,6 +3244,18 @@ func file_google_cloud_speech_v1_cloud_speech_proto_init() { return nil } } + file_google_cloud_speech_v1_cloud_speech_proto_msgTypes[18].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*SpeechAdaptationInfo); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } } file_google_cloud_speech_v1_cloud_speech_proto_msgTypes[2].OneofWrappers = []interface{}{ (*TranscriptOutputConfig_GcsUri)(nil), @@ -3115,7 +3274,7 @@ func file_google_cloud_speech_v1_cloud_speech_proto_init() { GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_google_cloud_speech_v1_cloud_speech_proto_rawDesc, NumEnums: 6, - NumMessages: 18, + NumMessages: 19, NumExtensions: 0, NumServices: 1, }, diff --git a/speech/apiv1/speechpb/cloud_speech_adaptation.pb.go b/speech/apiv1/speechpb/cloud_speech_adaptation.pb.go index 04b8d60b87ea..005f24e5e89f 100644 --- a/speech/apiv1/speechpb/cloud_speech_adaptation.pb.go +++ b/speech/apiv1/speechpb/cloud_speech_adaptation.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/speech/v1/cloud_speech_adaptation.proto package speechpb diff --git a/speech/apiv1/speechpb/resource.pb.go b/speech/apiv1/speechpb/resource.pb.go index 903db0f1ae28..ee14588b9c81 100644 --- a/speech/apiv1/speechpb/resource.pb.go +++ b/speech/apiv1/speechpb/resource.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/speech/v1/resource.proto package speechpb diff --git a/speech/apiv1p1beta1/adaptation_client.go b/speech/apiv1p1beta1/adaptation_client.go index 3eabbfbd0012..729fa931b2bf 100644 --- a/speech/apiv1p1beta1/adaptation_client.go +++ b/speech/apiv1p1beta1/adaptation_client.go @@ -33,6 +33,7 @@ import ( "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" httptransport "google.golang.org/api/transport/http" + longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/metadata" "google.golang.org/protobuf/encoding/protojson" @@ -53,6 +54,8 @@ type AdaptationCallOptions struct { ListCustomClasses []gax.CallOption UpdateCustomClass []gax.CallOption DeleteCustomClass []gax.CallOption + GetOperation []gax.CallOption + ListOperations []gax.CallOption } func defaultAdaptationGRPCClientOptions() []option.ClientOption { @@ -79,6 +82,8 @@ func defaultAdaptationCallOptions() *AdaptationCallOptions { ListCustomClasses: []gax.CallOption{}, UpdateCustomClass: []gax.CallOption{}, DeleteCustomClass: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, } } @@ -94,6 +99,8 @@ func defaultAdaptationRESTCallOptions() *AdaptationCallOptions { ListCustomClasses: []gax.CallOption{}, UpdateCustomClass: []gax.CallOption{}, DeleteCustomClass: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, } } @@ -112,6 +119,8 @@ type internalAdaptationClient interface { ListCustomClasses(context.Context, *speechpb.ListCustomClassesRequest, ...gax.CallOption) *CustomClassIterator UpdateCustomClass(context.Context, *speechpb.UpdateCustomClassRequest, ...gax.CallOption) (*speechpb.CustomClass, error) DeleteCustomClass(context.Context, *speechpb.DeleteCustomClassRequest, ...gax.CallOption) error + GetOperation(context.Context, *longrunningpb.GetOperationRequest, ...gax.CallOption) (*longrunningpb.Operation, error) + ListOperations(context.Context, *longrunningpb.ListOperationsRequest, ...gax.CallOption) *OperationIterator } // AdaptationClient is a client for interacting with Cloud Speech-to-Text API. @@ -201,6 +210,16 @@ func (c *AdaptationClient) DeleteCustomClass(ctx context.Context, req *speechpb. return c.internalClient.DeleteCustomClass(ctx, req, opts...) } +// GetOperation is a utility method from google.longrunning.Operations. +func (c *AdaptationClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + return c.internalClient.GetOperation(ctx, req, opts...) +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *AdaptationClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + return c.internalClient.ListOperations(ctx, req, opts...) +} + // adaptationGRPCClient is a client for interacting with Cloud Speech-to-Text API over gRPC transport. // // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. @@ -217,6 +236,8 @@ type adaptationGRPCClient struct { // The gRPC API client. adaptationClient speechpb.AdaptationClient + operationsClient longrunningpb.OperationsClient + // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } @@ -251,6 +272,7 @@ func NewAdaptationClient(ctx context.Context, opts ...option.ClientOption) (*Ada disableDeadlines: disableDeadlines, adaptationClient: speechpb.NewAdaptationClient(connPool), CallOptions: &client.CallOptions, + operationsClient: longrunningpb.NewOperationsClient(connPool), } c.setGoogleClientInfo() @@ -568,6 +590,66 @@ func (c *adaptationGRPCClient) DeleteCustomClass(ctx context.Context, req *speec return err } +func (c *adaptationGRPCClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + 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 +} + +func (c *adaptationGRPCClient) 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{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + 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 + } + + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + // CreatePhraseSet create a set of phrase hints. Each item in the set can be a single word or // a multi-word phrase. The items in the PhraseSet are favored by the // recognition model when you send a call that includes the PhraseSet. @@ -584,6 +666,11 @@ func (c *adaptationRESTClient) CreatePhraseSet(ctx context.Context, req *speechp } baseUrl.Path += fmt.Sprintf("/v1p1beta1/%v/phraseSets", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -637,6 +724,11 @@ func (c *adaptationRESTClient) GetPhraseSet(ctx context.Context, req *speechpb.G } baseUrl.Path += fmt.Sprintf("/v1p1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -704,6 +796,7 @@ func (c *adaptationRESTClient) ListPhraseSet(ctx context.Context, req *speechpb. baseUrl.Path += fmt.Sprintf("/v1p1beta1/%v/phraseSets", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -785,6 +878,7 @@ func (c *adaptationRESTClient) UpdatePhraseSet(ctx context.Context, req *speechp baseUrl.Path += fmt.Sprintf("/v1p1beta1/%v", req.GetPhraseSet().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -848,6 +942,11 @@ func (c *adaptationRESTClient) DeletePhraseSet(ctx context.Context, req *speechp } baseUrl.Path += fmt.Sprintf("/v1p1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -889,6 +988,11 @@ func (c *adaptationRESTClient) CreateCustomClass(ctx context.Context, req *speec } baseUrl.Path += fmt.Sprintf("/v1p1beta1/%v/customClasses", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -942,6 +1046,11 @@ func (c *adaptationRESTClient) GetCustomClass(ctx context.Context, req *speechpb } baseUrl.Path += fmt.Sprintf("/v1p1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1009,6 +1118,7 @@ func (c *adaptationRESTClient) ListCustomClasses(ctx context.Context, req *speec baseUrl.Path += fmt.Sprintf("/v1p1beta1/%v/customClasses", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -1090,6 +1200,7 @@ func (c *adaptationRESTClient) UpdateCustomClass(ctx context.Context, req *speec baseUrl.Path += fmt.Sprintf("/v1p1beta1/%v", req.GetCustomClass().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { @@ -1153,6 +1264,11 @@ func (c *adaptationRESTClient) DeleteCustomClass(ctx context.Context, req *speec } baseUrl.Path += fmt.Sprintf("/v1p1beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1180,6 +1296,158 @@ func (c *adaptationRESTClient) DeleteCustomClass(ctx context.Context, req *speec }, opts...) } +// GetOperation is a utility method from google.longrunning.Operations. +func (c *adaptationRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1p1beta1/operations/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *adaptationRESTClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1p1beta1/operations") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetName() != "" { + params.Add("name", fmt.Sprintf("%v", req.GetName())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + // CustomClassIterator manages a stream of *speechpb.CustomClass. type CustomClassIterator struct { items []*speechpb.CustomClass diff --git a/speech/apiv1p1beta1/adaptation_client_example_test.go b/speech/apiv1p1beta1/adaptation_client_example_test.go index 3c1e91f0b88b..670766f17691 100644 --- a/speech/apiv1p1beta1/adaptation_client_example_test.go +++ b/speech/apiv1p1beta1/adaptation_client_example_test.go @@ -22,6 +22,7 @@ import ( speech "cloud.google.com/go/speech/apiv1p1beta1" speechpb "cloud.google.com/go/speech/apiv1p1beta1/speechpb" "google.golang.org/api/iterator" + longrunningpb "google.golang.org/genproto/googleapis/longrunning" ) func ExampleNewAdaptationClient() { @@ -315,3 +316,59 @@ func ExampleAdaptationClient_DeleteCustomClass() { // TODO: Handle error. } } + +func ExampleAdaptationClient_GetOperation() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := speech.NewAdaptationClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + req := &longrunningpb.GetOperationRequest{ + // TODO: Fill request struct fields. + // See https://pkg.go.dev/google.golang.org/genproto/googleapis/longrunning#GetOperationRequest. + } + resp, err := c.GetOperation(ctx, req) + if err != nil { + // TODO: Handle error. + } + // TODO: Use resp. + _ = resp +} + +func ExampleAdaptationClient_ListOperations() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := speech.NewAdaptationClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + req := &longrunningpb.ListOperationsRequest{ + // TODO: Fill request struct fields. + // See https://pkg.go.dev/google.golang.org/genproto/googleapis/longrunning#ListOperationsRequest. + } + 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 + } +} diff --git a/speech/apiv1p1beta1/gapic_metadata.json b/speech/apiv1p1beta1/gapic_metadata.json index 1d26bcc56829..1895ced7676f 100644 --- a/speech/apiv1p1beta1/gapic_metadata.json +++ b/speech/apiv1p1beta1/gapic_metadata.json @@ -35,6 +35,11 @@ "GetCustomClass" ] }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, "GetPhraseSet": { "methods": [ "GetPhraseSet" @@ -45,6 +50,11 @@ "ListCustomClasses" ] }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, "ListPhraseSet": { "methods": [ "ListPhraseSet" @@ -90,6 +100,11 @@ "GetCustomClass" ] }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, "GetPhraseSet": { "methods": [ "GetPhraseSet" @@ -100,6 +115,11 @@ "ListCustomClasses" ] }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, "ListPhraseSet": { "methods": [ "ListPhraseSet" @@ -124,6 +144,16 @@ "grpc": { "libraryClient": "Client", "rpcs": { + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, "LongRunningRecognize": { "methods": [ "LongRunningRecognize" @@ -144,6 +174,16 @@ "rest": { "libraryClient": "Client", "rpcs": { + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, "LongRunningRecognize": { "methods": [ "LongRunningRecognize" diff --git a/speech/apiv1p1beta1/speech_client.go b/speech/apiv1p1beta1/speech_client.go index 363f529a0bb0..999da779caf4 100644 --- a/speech/apiv1p1beta1/speech_client.go +++ b/speech/apiv1p1beta1/speech_client.go @@ -31,6 +31,7 @@ import ( speechpb "cloud.google.com/go/speech/apiv1p1beta1/speechpb" gax "github.com/googleapis/gax-go/v2" "google.golang.org/api/googleapi" + "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" @@ -40,6 +41,7 @@ import ( "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" "google.golang.org/protobuf/encoding/protojson" + "google.golang.org/protobuf/proto" ) var newClientHook clientHook @@ -49,6 +51,8 @@ type CallOptions struct { Recognize []gax.CallOption LongRunningRecognize []gax.CallOption StreamingRecognize []gax.CallOption + GetOperation []gax.CallOption + ListOperations []gax.CallOption } func defaultGRPCClientOptions() []option.ClientOption { @@ -90,6 +94,8 @@ func defaultCallOptions() *CallOptions { }) }), }, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, } } @@ -118,6 +124,8 @@ func defaultRESTCallOptions() *CallOptions { http.StatusServiceUnavailable) }), }, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, } } @@ -130,6 +138,8 @@ type internalClient interface { LongRunningRecognize(context.Context, *speechpb.LongRunningRecognizeRequest, ...gax.CallOption) (*LongRunningRecognizeOperation, error) LongRunningRecognizeOperation(name string) *LongRunningRecognizeOperation StreamingRecognize(context.Context, ...gax.CallOption) (speechpb.Speech_StreamingRecognizeClient, error) + GetOperation(context.Context, *longrunningpb.GetOperationRequest, ...gax.CallOption) (*longrunningpb.Operation, error) + ListOperations(context.Context, *longrunningpb.ListOperationsRequest, ...gax.CallOption) *OperationIterator } // Client is a client for interacting with Cloud Speech-to-Text API. @@ -196,10 +206,22 @@ func (c *Client) LongRunningRecognizeOperation(name string) *LongRunningRecogniz // StreamingRecognize performs bidirectional streaming speech recognition: receive results while // sending audio. This method is only available via the gRPC API (not REST). +// +// This method is not supported for the REST transport. func (c *Client) StreamingRecognize(ctx context.Context, opts ...gax.CallOption) (speechpb.Speech_StreamingRecognizeClient, error) { return c.internalClient.StreamingRecognize(ctx, opts...) } +// GetOperation is a utility method from google.longrunning.Operations. +func (c *Client) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + return c.internalClient.GetOperation(ctx, req, opts...) +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *Client) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + return c.internalClient.ListOperations(ctx, req, opts...) +} + // gRPCClient is a client for interacting with Cloud Speech-to-Text API over gRPC transport. // // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. @@ -221,6 +243,8 @@ type gRPCClient struct { // Users should not Close this client. LROClient **lroauto.OperationsClient + operationsClient longrunningpb.OperationsClient + // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } @@ -255,6 +279,7 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error disableDeadlines: disableDeadlines, client: speechpb.NewSpeechClient(connPool), CallOptions: &client.CallOptions, + operationsClient: longrunningpb.NewOperationsClient(connPool), } c.setGoogleClientInfo() @@ -437,6 +462,66 @@ func (c *gRPCClient) StreamingRecognize(ctx context.Context, opts ...gax.CallOpt return resp, nil } +func (c *gRPCClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + 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 +} + +func (c *gRPCClient) 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{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + 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 + } + + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + // Recognize performs synchronous speech recognition: receive results after all audio // has been sent and processed. func (c *restClient) Recognize(ctx context.Context, req *speechpb.RecognizeRequest, opts ...gax.CallOption) (*speechpb.RecognizeResponse, error) { @@ -452,6 +537,11 @@ func (c *restClient) Recognize(ctx context.Context, req *speechpb.RecognizeReque } baseUrl.Path += fmt.Sprintf("/v1p1beta1/speech:recognize") + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) opts = append((*c.CallOptions).Recognize[0:len((*c.CallOptions).Recognize):len((*c.CallOptions).Recognize)], opts...) @@ -514,6 +604,11 @@ func (c *restClient) LongRunningRecognize(ctx context.Context, req *speechpb.Lon } baseUrl.Path += fmt.Sprintf("/v1p1beta1/speech:longrunningrecognize") + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} @@ -563,10 +658,164 @@ func (c *restClient) LongRunningRecognize(ctx context.Context, req *speechpb.Lon // StreamingRecognize performs bidirectional streaming speech recognition: receive results while // sending audio. This method is only available via the gRPC API (not REST). +// +// This method is not supported for the REST transport. func (c *restClient) StreamingRecognize(ctx context.Context, opts ...gax.CallOption) (speechpb.Speech_StreamingRecognizeClient, error) { return nil, fmt.Errorf("StreamingRecognize not yet supported for REST clients") } +// GetOperation is a utility method from google.longrunning.Operations. +func (c *restClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1p1beta1/operations/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *restClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1p1beta1/operations") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetName() != "" { + params.Add("name", fmt.Sprintf("%v", req.GetName())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + // LongRunningRecognizeOperation manages a long-running operation from LongRunningRecognize. type LongRunningRecognizeOperation struct { lro *longrunning.Operation @@ -648,3 +897,50 @@ func (op *LongRunningRecognizeOperation) Done() bool { func (op *LongRunningRecognizeOperation) Name() string { return op.lro.Name() } + +// OperationIterator manages a stream of *longrunningpb.Operation. +type OperationIterator struct { + items []*longrunningpb.Operation + pageInfo *iterator.PageInfo + nextFunc func() error + + // Response is the raw response for the current page. + // It must be cast to the RPC response type. + // Calling Next() or InternalFetch() updates this value. + Response interface{} + + // 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 +} diff --git a/speech/apiv1p1beta1/speech_client_example_test.go b/speech/apiv1p1beta1/speech_client_example_test.go index 92367a14a787..af385e44e738 100644 --- a/speech/apiv1p1beta1/speech_client_example_test.go +++ b/speech/apiv1p1beta1/speech_client_example_test.go @@ -22,6 +22,8 @@ import ( speech "cloud.google.com/go/speech/apiv1p1beta1" speechpb "cloud.google.com/go/speech/apiv1p1beta1/speechpb" + "google.golang.org/api/iterator" + longrunningpb "google.golang.org/genproto/googleapis/longrunning" ) func ExampleNewClient() { @@ -152,3 +154,59 @@ func ExampleClient_StreamingRecognize() { _ = resp } } + +func ExampleClient_GetOperation() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := speech.NewClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + req := &longrunningpb.GetOperationRequest{ + // TODO: Fill request struct fields. + // See https://pkg.go.dev/google.golang.org/genproto/googleapis/longrunning#GetOperationRequest. + } + resp, err := c.GetOperation(ctx, req) + if err != nil { + // TODO: Handle error. + } + // TODO: Use resp. + _ = resp +} + +func ExampleClient_ListOperations() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := speech.NewClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + req := &longrunningpb.ListOperationsRequest{ + // TODO: Fill request struct fields. + // See https://pkg.go.dev/google.golang.org/genproto/googleapis/longrunning#ListOperationsRequest. + } + 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 + } +} diff --git a/speech/apiv1p1beta1/speechpb/cloud_speech.pb.go b/speech/apiv1p1beta1/speechpb/cloud_speech.pb.go index 58852b132ac4..d10b5081366d 100644 --- a/speech/apiv1p1beta1/speechpb/cloud_speech.pb.go +++ b/speech/apiv1p1beta1/speechpb/cloud_speech.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/speech/v1p1beta1/cloud_speech.proto package speechpb @@ -628,7 +628,6 @@ type TranscriptOutputConfig struct { unknownFields protoimpl.UnknownFields // Types that are assignable to OutputType: - // // *TranscriptOutputConfig_GcsUri OutputType isTranscriptOutputConfig_OutputType `protobuf_oneof:"output_type"` } @@ -705,7 +704,6 @@ type StreamingRecognizeRequest struct { // The streaming request, which is either a streaming config or audio content. // // Types that are assignable to StreamingRequest: - // // *StreamingRecognizeRequest_StreamingConfig // *StreamingRecognizeRequest_AudioContent StreamingRequest isStreamingRecognizeRequest_StreamingRequest `protobuf_oneof:"streaming_request"` @@ -817,11 +815,11 @@ type StreamingRecognitionConfig struct { // otherwise an error is thrown. The `model` field in [`RecognitionConfig`][] // must be set to: // - // - `command_and_search` - // - `phone_call` AND additional field `useEnhanced`=`true` - // - The `model` field is left undefined. In this case the API auto-selects - // a model based on any other parameters that you set in - // `RecognitionConfig`. + // * `command_and_search` + // * `phone_call` AND additional field `useEnhanced`=`true` + // * The `model` field is left undefined. In this case the API auto-selects + // a model based on any other parameters that you set in + // `RecognitionConfig`. SingleUtterance bool `protobuf:"varint,2,opt,name=single_utterance,json=singleUtterance,proto3" json:"single_utterance,omitempty"` // If `true`, interim results (tentative hypotheses) may be // returned as they become available (these interim results are indicated with @@ -904,8 +902,7 @@ type RecognitionConfig struct { SampleRateHertz int32 `protobuf:"varint,2,opt,name=sample_rate_hertz,json=sampleRateHertz,proto3" json:"sample_rate_hertz,omitempty"` // The number of channels in the input audio data. // ONLY set this for MULTI-CHANNEL recognition. - // Valid values for LINEAR16 and FLAC are `1`-`8`. - // Valid values for OGG_OPUS are '1'-'254'. + // Valid values for LINEAR16, OGG_OPUS and FLAC are `1`-`8`. // Valid value for MULAW, AMR, AMR_WB and SPEEX_WITH_HEADER_BYTE is only `1`. // If `0` or omitted, defaults to one channel (mono). // Note: We only recognize the first channel by default. @@ -1025,53 +1022,51 @@ type RecognitionConfig struct { // explicitly specified, then we auto-select a model based on the parameters // in the RecognitionConfig. // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // + // + // + // + // + // + // + // + // + // + // + // + // + // + // + // + // + // + // + // + // + // + // + // + // + // + // + // + // + // + // + // + // + // + // + // + // //
ModelDescription
latest_longBest for long form content like media or conversation.
latest_shortBest for short form content like commands or single shot directed - // speech.
command_and_searchBest for short queries such as voice commands or voice search.
phone_callBest for audio that originated from a phone call (typically - // recorded at an 8khz sampling rate).
videoBest for audio that originated from video or includes multiple - // speakers. Ideally the audio is recorded at a 16khz or greater - // sampling rate. This is a premium model that costs more than the - // standard rate.
defaultBest for audio that is not one of the specific audio models. - // For example, long-form audio. Ideally the audio is high-fidelity, - // recorded at a 16khz or greater sampling rate.
medical_conversationBest for audio that originated from a conversation between a - // medical provider and patient.
medical_dictationBest for audio that originated from dictation notes by a medical - // provider.
ModelDescription
latest_longBest for long form content like media or conversation.
latest_shortBest for short form content like commands or single shot directed + // speech.
command_and_searchBest for short queries such as voice commands or voice search.
phone_callBest for audio that originated from a phone call (typically + // recorded at an 8khz sampling rate).
videoBest for audio that originated from video or includes multiple + // speakers. Ideally the audio is recorded at a 16khz or greater + // sampling rate. This is a premium model that costs more than the + // standard rate.
defaultBest for audio that is not one of the specific audio models. + // For example, long-form audio. Ideally the audio is high-fidelity, + // recorded at a 16khz or greater sampling rate.
medical_conversationBest for audio that originated from a conversation between a + // medical provider and patient.
medical_dictationBest for audio that originated from dictation notes by a medical + // provider.
Model string `protobuf:"bytes,13,opt,name=model,proto3" json:"model,omitempty"` // Set to true to use an enhanced model for speech recognition. @@ -1584,7 +1579,6 @@ type RecognitionAudio struct { // Storage uri. // // Types that are assignable to AudioSource: - // // *RecognitionAudio_Content // *RecognitionAudio_Uri AudioSource isRecognitionAudio_AudioSource `protobuf_oneof:"audio_source"` @@ -1682,6 +1676,11 @@ type RecognizeResponse struct { Results []*SpeechRecognitionResult `protobuf:"bytes,2,rep,name=results,proto3" json:"results,omitempty"` // When available, billed audio seconds for the corresponding request. TotalBilledTime *durationpb.Duration `protobuf:"bytes,3,opt,name=total_billed_time,json=totalBilledTime,proto3" json:"total_billed_time,omitempty"` + // Provides information on adaptation behavior in response + SpeechAdaptationInfo *SpeechAdaptationInfo `protobuf:"bytes,7,opt,name=speech_adaptation_info,json=speechAdaptationInfo,proto3" json:"speech_adaptation_info,omitempty"` + // The ID associated with the request. This is a unique ID specific only to + // the given request. + RequestId int64 `protobuf:"varint,8,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"` } func (x *RecognizeResponse) Reset() { @@ -1730,6 +1729,20 @@ func (x *RecognizeResponse) GetTotalBilledTime() *durationpb.Duration { return nil } +func (x *RecognizeResponse) GetSpeechAdaptationInfo() *SpeechAdaptationInfo { + if x != nil { + return x.SpeechAdaptationInfo + } + return nil +} + +func (x *RecognizeResponse) GetRequestId() int64 { + if x != nil { + return x.RequestId + } + return 0 +} + // The only message returned to the client by the `LongRunningRecognize` method. // It contains the result as zero or more sequential `SpeechRecognitionResult` // messages. It is included in the `result.response` field of the `Operation` @@ -1749,6 +1762,11 @@ type LongRunningRecognizeResponse struct { OutputConfig *TranscriptOutputConfig `protobuf:"bytes,6,opt,name=output_config,json=outputConfig,proto3" json:"output_config,omitempty"` // If the transcript output fails this field contains the relevant error. OutputError *status.Status `protobuf:"bytes,7,opt,name=output_error,json=outputError,proto3" json:"output_error,omitempty"` + // Provides information on speech adaptation behavior in response + SpeechAdaptationInfo *SpeechAdaptationInfo `protobuf:"bytes,8,opt,name=speech_adaptation_info,json=speechAdaptationInfo,proto3" json:"speech_adaptation_info,omitempty"` + // The ID associated with the request. This is a unique ID specific only to + // the given request. + RequestId int64 `protobuf:"varint,9,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"` } func (x *LongRunningRecognizeResponse) Reset() { @@ -1811,6 +1829,20 @@ func (x *LongRunningRecognizeResponse) GetOutputError() *status.Status { return nil } +func (x *LongRunningRecognizeResponse) GetSpeechAdaptationInfo() *SpeechAdaptationInfo { + if x != nil { + return x.SpeechAdaptationInfo + } + return nil +} + +func (x *LongRunningRecognizeResponse) GetRequestId() int64 { + if x != nil { + return x.RequestId + } + return 0 +} + // Describes the progress of a long-running `LongRunningRecognize` call. It is // included in the `metadata` field of the `Operation` returned by the // `GetOperation` call of the `google::longrunning::Operations` service. @@ -1967,6 +1999,11 @@ type StreamingRecognizeResponse struct { // When available, billed audio seconds for the stream. // Set only if this is the last response in the stream. TotalBilledTime *durationpb.Duration `protobuf:"bytes,5,opt,name=total_billed_time,json=totalBilledTime,proto3" json:"total_billed_time,omitempty"` + // Provides information on adaptation behavior in response + SpeechAdaptationInfo *SpeechAdaptationInfo `protobuf:"bytes,9,opt,name=speech_adaptation_info,json=speechAdaptationInfo,proto3" json:"speech_adaptation_info,omitempty"` + // The ID associated with the request. This is a unique ID specific only to + // the given request. + RequestId int64 `protobuf:"varint,10,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"` } func (x *StreamingRecognizeResponse) Reset() { @@ -2029,6 +2066,20 @@ func (x *StreamingRecognizeResponse) GetTotalBilledTime() *durationpb.Duration { return nil } +func (x *StreamingRecognizeResponse) GetSpeechAdaptationInfo() *SpeechAdaptationInfo { + if x != nil { + return x.SpeechAdaptationInfo + } + return nil +} + +func (x *StreamingRecognizeResponse) GetRequestId() int64 { + if x != nil { + return x.RequestId + } + return 0 +} + // A streaming speech recognition result corresponding to a portion of the audio // that is currently being processed. type StreamingRecognitionResult struct { @@ -2407,6 +2458,66 @@ func (x *WordInfo) GetSpeakerTag() int32 { return 0 } +// Information on speech adaptation use in results +type SpeechAdaptationInfo struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // Whether there was a timeout when applying speech adaptation. If true, + // adaptation had no effect in the response transcript. + AdaptationTimeout bool `protobuf:"varint,1,opt,name=adaptation_timeout,json=adaptationTimeout,proto3" json:"adaptation_timeout,omitempty"` + // If set, returns a message specifying which part of the speech adaptation + // request timed out. + TimeoutMessage string `protobuf:"bytes,4,opt,name=timeout_message,json=timeoutMessage,proto3" json:"timeout_message,omitempty"` +} + +func (x *SpeechAdaptationInfo) Reset() { + *x = SpeechAdaptationInfo{} + if protoimpl.UnsafeEnabled { + mi := &file_google_cloud_speech_v1p1beta1_cloud_speech_proto_msgTypes[18] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *SpeechAdaptationInfo) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SpeechAdaptationInfo) ProtoMessage() {} + +func (x *SpeechAdaptationInfo) ProtoReflect() protoreflect.Message { + mi := &file_google_cloud_speech_v1p1beta1_cloud_speech_proto_msgTypes[18] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SpeechAdaptationInfo.ProtoReflect.Descriptor instead. +func (*SpeechAdaptationInfo) Descriptor() ([]byte, []int) { + return file_google_cloud_speech_v1p1beta1_cloud_speech_proto_rawDescGZIP(), []int{18} +} + +func (x *SpeechAdaptationInfo) GetAdaptationTimeout() bool { + if x != nil { + return x.AdaptationTimeout + } + return false +} + +func (x *SpeechAdaptationInfo) GetTimeoutMessage() string { + if x != nil { + return x.TimeoutMessage + } + return "" +} + var File_google_cloud_speech_v1p1beta1_cloud_speech_proto protoreflect.FileDescriptor var file_google_cloud_speech_v1p1beta1_cloud_speech_proto_rawDesc = []byte{ @@ -2696,7 +2807,7 @@ var file_google_cloud_speech_v1p1beta1_cloud_speech_proto_rawDesc = []byte{ 0x07, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x48, 0x00, 0x52, 0x07, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x12, 0x12, 0x0a, 0x03, 0x75, 0x72, 0x69, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x48, 0x00, 0x52, 0x03, 0x75, 0x72, 0x69, 0x42, 0x0e, 0x0a, - 0x0c, 0x61, 0x75, 0x64, 0x69, 0x6f, 0x5f, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x22, 0xac, 0x01, + 0x0c, 0x61, 0x75, 0x64, 0x69, 0x6f, 0x5f, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x22, 0xb6, 0x02, 0x0a, 0x11, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x50, 0x0a, 0x07, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x36, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, @@ -2707,185 +2818,217 @@ var file_google_cloud_speech_v1p1beta1_cloud_speech_proto_rawDesc = []byte{ 0x69, 0x6c, 0x6c, 0x65, 0x64, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0f, 0x74, 0x6f, 0x74, - 0x61, 0x6c, 0x42, 0x69, 0x6c, 0x6c, 0x65, 0x64, 0x54, 0x69, 0x6d, 0x65, 0x22, 0xca, 0x02, 0x0a, - 0x1c, 0x4c, 0x6f, 0x6e, 0x67, 0x52, 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x63, 0x6f, - 0x67, 0x6e, 0x69, 0x7a, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x50, 0x0a, - 0x07, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x36, - 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, - 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, 0x31, 0x70, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x53, - 0x70, 0x65, 0x65, 0x63, 0x68, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x74, 0x69, 0x6f, 0x6e, - 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x52, 0x07, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x73, 0x12, - 0x45, 0x0a, 0x11, 0x74, 0x6f, 0x74, 0x61, 0x6c, 0x5f, 0x62, 0x69, 0x6c, 0x6c, 0x65, 0x64, 0x5f, - 0x74, 0x69, 0x6d, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, - 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, - 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0f, 0x74, 0x6f, 0x74, 0x61, 0x6c, 0x42, 0x69, 0x6c, 0x6c, - 0x65, 0x64, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x5a, 0x0a, 0x0d, 0x6f, 0x75, 0x74, 0x70, 0x75, 0x74, - 0x5f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x35, 0x2e, - 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, - 0x65, 0x63, 0x68, 0x2e, 0x76, 0x31, 0x70, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x54, 0x72, - 0x61, 0x6e, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x4f, 0x75, 0x74, 0x70, 0x75, 0x74, 0x43, 0x6f, - 0x6e, 0x66, 0x69, 0x67, 0x52, 0x0c, 0x6f, 0x75, 0x74, 0x70, 0x75, 0x74, 0x43, 0x6f, 0x6e, 0x66, - 0x69, 0x67, 0x12, 0x35, 0x0a, 0x0c, 0x6f, 0x75, 0x74, 0x70, 0x75, 0x74, 0x5f, 0x65, 0x72, 0x72, - 0x6f, 0x72, 0x18, 0x07, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x12, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, - 0x65, 0x2e, 0x72, 0x70, 0x63, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x0b, 0x6f, 0x75, - 0x74, 0x70, 0x75, 0x74, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x22, 0xc2, 0x02, 0x0a, 0x1c, 0x4c, 0x6f, - 0x6e, 0x67, 0x52, 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, - 0x7a, 0x65, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x12, 0x29, 0x0a, 0x10, 0x70, 0x72, - 0x6f, 0x67, 0x72, 0x65, 0x73, 0x73, 0x5f, 0x70, 0x65, 0x72, 0x63, 0x65, 0x6e, 0x74, 0x18, 0x01, - 0x20, 0x01, 0x28, 0x05, 0x52, 0x0f, 0x70, 0x72, 0x6f, 0x67, 0x72, 0x65, 0x73, 0x73, 0x50, 0x65, - 0x72, 0x63, 0x65, 0x6e, 0x74, 0x12, 0x39, 0x0a, 0x0a, 0x73, 0x74, 0x61, 0x72, 0x74, 0x5f, 0x74, - 0x69, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, - 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, - 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x09, 0x73, 0x74, 0x61, 0x72, 0x74, 0x54, 0x69, 0x6d, 0x65, - 0x12, 0x44, 0x0a, 0x10, 0x6c, 0x61, 0x73, 0x74, 0x5f, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x5f, - 0x74, 0x69, 0x6d, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, - 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, 0x6d, - 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x0e, 0x6c, 0x61, 0x73, 0x74, 0x55, 0x70, 0x64, 0x61, - 0x74, 0x65, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x15, 0x0a, 0x03, 0x75, 0x72, 0x69, 0x18, 0x04, 0x20, - 0x01, 0x28, 0x09, 0x42, 0x03, 0xe0, 0x41, 0x03, 0x52, 0x03, 0x75, 0x72, 0x69, 0x12, 0x5f, 0x0a, - 0x0d, 0x6f, 0x75, 0x74, 0x70, 0x75, 0x74, 0x5f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x18, 0x05, - 0x20, 0x01, 0x28, 0x0b, 0x32, 0x35, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, - 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, 0x31, 0x70, 0x31, 0x62, - 0x65, 0x74, 0x61, 0x31, 0x2e, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x4f, - 0x75, 0x74, 0x70, 0x75, 0x74, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x42, 0x03, 0xe0, 0x41, 0x03, - 0x52, 0x0c, 0x6f, 0x75, 0x74, 0x70, 0x75, 0x74, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x22, 0xa7, - 0x03, 0x0a, 0x1a, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x63, 0x6f, - 0x67, 0x6e, 0x69, 0x7a, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x28, 0x0a, - 0x05, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x12, 0x2e, 0x67, - 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x72, 0x70, 0x63, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, - 0x52, 0x05, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x12, 0x53, 0x0a, 0x07, 0x72, 0x65, 0x73, 0x75, 0x6c, - 0x74, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x39, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, + 0x61, 0x6c, 0x42, 0x69, 0x6c, 0x6c, 0x65, 0x64, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x69, 0x0a, 0x16, + 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x5f, 0x61, 0x64, 0x61, 0x70, 0x74, 0x61, 0x74, 0x69, 0x6f, + 0x6e, 0x5f, 0x69, 0x6e, 0x66, 0x6f, 0x18, 0x07, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x33, 0x2e, 0x67, + 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, + 0x63, 0x68, 0x2e, 0x76, 0x31, 0x70, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x53, 0x70, 0x65, + 0x65, 0x63, 0x68, 0x41, 0x64, 0x61, 0x70, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x49, 0x6e, 0x66, + 0x6f, 0x52, 0x14, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x41, 0x64, 0x61, 0x70, 0x74, 0x61, 0x74, + 0x69, 0x6f, 0x6e, 0x49, 0x6e, 0x66, 0x6f, 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x71, 0x75, 0x65, + 0x73, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x08, 0x20, 0x01, 0x28, 0x03, 0x52, 0x09, 0x72, 0x65, 0x71, + 0x75, 0x65, 0x73, 0x74, 0x49, 0x64, 0x22, 0xd4, 0x03, 0x0a, 0x1c, 0x4c, 0x6f, 0x6e, 0x67, 0x52, + 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, 0x65, 0x52, + 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x50, 0x0a, 0x07, 0x72, 0x65, 0x73, 0x75, 0x6c, + 0x74, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x36, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, - 0x31, 0x70, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x69, - 0x6e, 0x67, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, - 0x75, 0x6c, 0x74, 0x52, 0x07, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x73, 0x12, 0x75, 0x0a, 0x11, - 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x5f, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x5f, 0x74, 0x79, 0x70, - 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x49, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, + 0x31, 0x70, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x53, 0x70, 0x65, 0x65, 0x63, 0x68, 0x52, + 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, + 0x52, 0x07, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x73, 0x12, 0x45, 0x0a, 0x11, 0x74, 0x6f, 0x74, + 0x61, 0x6c, 0x5f, 0x62, 0x69, 0x6c, 0x6c, 0x65, 0x64, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x03, + 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, + 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, + 0x0f, 0x74, 0x6f, 0x74, 0x61, 0x6c, 0x42, 0x69, 0x6c, 0x6c, 0x65, 0x64, 0x54, 0x69, 0x6d, 0x65, + 0x12, 0x5a, 0x0a, 0x0d, 0x6f, 0x75, 0x74, 0x70, 0x75, 0x74, 0x5f, 0x63, 0x6f, 0x6e, 0x66, 0x69, + 0x67, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x35, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, 0x31, - 0x70, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x69, 0x6e, - 0x67, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, - 0x73, 0x65, 0x2e, 0x53, 0x70, 0x65, 0x65, 0x63, 0x68, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x54, 0x79, - 0x70, 0x65, 0x52, 0x0f, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x54, - 0x79, 0x70, 0x65, 0x12, 0x45, 0x0a, 0x11, 0x74, 0x6f, 0x74, 0x61, 0x6c, 0x5f, 0x62, 0x69, 0x6c, - 0x6c, 0x65, 0x64, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, + 0x70, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x63, 0x72, 0x69, + 0x70, 0x74, 0x4f, 0x75, 0x74, 0x70, 0x75, 0x74, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x0c, + 0x6f, 0x75, 0x74, 0x70, 0x75, 0x74, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x35, 0x0a, 0x0c, + 0x6f, 0x75, 0x74, 0x70, 0x75, 0x74, 0x5f, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x18, 0x07, 0x20, 0x01, + 0x28, 0x0b, 0x32, 0x12, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x72, 0x70, 0x63, 0x2e, + 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x0b, 0x6f, 0x75, 0x74, 0x70, 0x75, 0x74, 0x45, 0x72, + 0x72, 0x6f, 0x72, 0x12, 0x69, 0x0a, 0x16, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x5f, 0x61, 0x64, + 0x61, 0x70, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x69, 0x6e, 0x66, 0x6f, 0x18, 0x08, 0x20, + 0x01, 0x28, 0x0b, 0x32, 0x33, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, + 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, 0x31, 0x70, 0x31, 0x62, 0x65, + 0x74, 0x61, 0x31, 0x2e, 0x53, 0x70, 0x65, 0x65, 0x63, 0x68, 0x41, 0x64, 0x61, 0x70, 0x74, 0x61, + 0x74, 0x69, 0x6f, 0x6e, 0x49, 0x6e, 0x66, 0x6f, 0x52, 0x14, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, + 0x41, 0x64, 0x61, 0x70, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x49, 0x6e, 0x66, 0x6f, 0x12, 0x1d, + 0x0a, 0x0a, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x09, 0x20, 0x01, + 0x28, 0x03, 0x52, 0x09, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x49, 0x64, 0x22, 0xc2, 0x02, + 0x0a, 0x1c, 0x4c, 0x6f, 0x6e, 0x67, 0x52, 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x63, + 0x6f, 0x67, 0x6e, 0x69, 0x7a, 0x65, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x12, 0x29, + 0x0a, 0x10, 0x70, 0x72, 0x6f, 0x67, 0x72, 0x65, 0x73, 0x73, 0x5f, 0x70, 0x65, 0x72, 0x63, 0x65, + 0x6e, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x05, 0x52, 0x0f, 0x70, 0x72, 0x6f, 0x67, 0x72, 0x65, + 0x73, 0x73, 0x50, 0x65, 0x72, 0x63, 0x65, 0x6e, 0x74, 0x12, 0x39, 0x0a, 0x0a, 0x73, 0x74, 0x61, + 0x72, 0x74, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, + 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, + 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x09, 0x73, 0x74, 0x61, 0x72, 0x74, + 0x54, 0x69, 0x6d, 0x65, 0x12, 0x44, 0x0a, 0x10, 0x6c, 0x61, 0x73, 0x74, 0x5f, 0x75, 0x70, 0x64, + 0x61, 0x74, 0x65, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, - 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0f, 0x74, 0x6f, 0x74, 0x61, 0x6c, - 0x42, 0x69, 0x6c, 0x6c, 0x65, 0x64, 0x54, 0x69, 0x6d, 0x65, 0x22, 0x4c, 0x0a, 0x0f, 0x53, 0x70, - 0x65, 0x65, 0x63, 0x68, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x54, 0x79, 0x70, 0x65, 0x12, 0x1c, 0x0a, - 0x18, 0x53, 0x50, 0x45, 0x45, 0x43, 0x48, 0x5f, 0x45, 0x56, 0x45, 0x4e, 0x54, 0x5f, 0x55, 0x4e, - 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x1b, 0x0a, 0x17, 0x45, - 0x4e, 0x44, 0x5f, 0x4f, 0x46, 0x5f, 0x53, 0x49, 0x4e, 0x47, 0x4c, 0x45, 0x5f, 0x55, 0x54, 0x54, - 0x45, 0x52, 0x41, 0x4e, 0x43, 0x45, 0x10, 0x01, 0x22, 0xc4, 0x02, 0x0a, 0x1a, 0x53, 0x74, 0x72, + 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x0e, 0x6c, 0x61, 0x73, 0x74, + 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x15, 0x0a, 0x03, 0x75, 0x72, + 0x69, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x42, 0x03, 0xe0, 0x41, 0x03, 0x52, 0x03, 0x75, 0x72, + 0x69, 0x12, 0x5f, 0x0a, 0x0d, 0x6f, 0x75, 0x74, 0x70, 0x75, 0x74, 0x5f, 0x63, 0x6f, 0x6e, 0x66, + 0x69, 0x67, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x35, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, + 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, + 0x31, 0x70, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x63, 0x72, + 0x69, 0x70, 0x74, 0x4f, 0x75, 0x74, 0x70, 0x75, 0x74, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x42, + 0x03, 0xe0, 0x41, 0x03, 0x52, 0x0c, 0x6f, 0x75, 0x74, 0x70, 0x75, 0x74, 0x43, 0x6f, 0x6e, 0x66, + 0x69, 0x67, 0x22, 0xb1, 0x04, 0x0a, 0x1a, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x69, 0x6e, 0x67, + 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, + 0x65, 0x12, 0x28, 0x0a, 0x05, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, + 0x32, 0x12, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x72, 0x70, 0x63, 0x2e, 0x53, 0x74, + 0x61, 0x74, 0x75, 0x73, 0x52, 0x05, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x12, 0x53, 0x0a, 0x07, 0x72, + 0x65, 0x73, 0x75, 0x6c, 0x74, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x39, 0x2e, 0x67, + 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, + 0x63, 0x68, 0x2e, 0x76, 0x31, 0x70, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x74, 0x69, 0x6f, - 0x6e, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x12, 0x5f, 0x0a, 0x0c, 0x61, 0x6c, 0x74, 0x65, 0x72, - 0x6e, 0x61, 0x74, 0x69, 0x76, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x3b, 0x2e, - 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, - 0x65, 0x63, 0x68, 0x2e, 0x76, 0x31, 0x70, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x53, 0x70, - 0x65, 0x65, 0x63, 0x68, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x41, - 0x6c, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x74, 0x69, 0x76, 0x65, 0x52, 0x0c, 0x61, 0x6c, 0x74, 0x65, - 0x72, 0x6e, 0x61, 0x74, 0x69, 0x76, 0x65, 0x73, 0x12, 0x19, 0x0a, 0x08, 0x69, 0x73, 0x5f, 0x66, - 0x69, 0x6e, 0x61, 0x6c, 0x18, 0x02, 0x20, 0x01, 0x28, 0x08, 0x52, 0x07, 0x69, 0x73, 0x46, 0x69, - 0x6e, 0x61, 0x6c, 0x12, 0x1c, 0x0a, 0x09, 0x73, 0x74, 0x61, 0x62, 0x69, 0x6c, 0x69, 0x74, 0x79, - 0x18, 0x03, 0x20, 0x01, 0x28, 0x02, 0x52, 0x09, 0x73, 0x74, 0x61, 0x62, 0x69, 0x6c, 0x69, 0x74, - 0x79, 0x12, 0x41, 0x0a, 0x0f, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x5f, 0x65, 0x6e, 0x64, 0x5f, - 0x74, 0x69, 0x6d, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, - 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, - 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0d, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x45, 0x6e, 0x64, - 0x54, 0x69, 0x6d, 0x65, 0x12, 0x1f, 0x0a, 0x0b, 0x63, 0x68, 0x61, 0x6e, 0x6e, 0x65, 0x6c, 0x5f, - 0x74, 0x61, 0x67, 0x18, 0x05, 0x20, 0x01, 0x28, 0x05, 0x52, 0x0a, 0x63, 0x68, 0x61, 0x6e, 0x6e, - 0x65, 0x6c, 0x54, 0x61, 0x67, 0x12, 0x28, 0x0a, 0x0d, 0x6c, 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, - 0x65, 0x5f, 0x63, 0x6f, 0x64, 0x65, 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, 0x42, 0x03, 0xe0, 0x41, - 0x03, 0x52, 0x0c, 0x6c, 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, 0x43, 0x6f, 0x64, 0x65, 0x22, - 0x88, 0x02, 0x0a, 0x17, 0x53, 0x70, 0x65, 0x65, 0x63, 0x68, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, - 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x12, 0x5f, 0x0a, 0x0c, 0x61, - 0x6c, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x74, 0x69, 0x76, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, - 0x0b, 0x32, 0x3b, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, - 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, 0x31, 0x70, 0x31, 0x62, 0x65, 0x74, 0x61, - 0x31, 0x2e, 0x53, 0x70, 0x65, 0x65, 0x63, 0x68, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x74, - 0x69, 0x6f, 0x6e, 0x41, 0x6c, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x74, 0x69, 0x76, 0x65, 0x52, 0x0c, - 0x61, 0x6c, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x74, 0x69, 0x76, 0x65, 0x73, 0x12, 0x1f, 0x0a, 0x0b, - 0x63, 0x68, 0x61, 0x6e, 0x6e, 0x65, 0x6c, 0x5f, 0x74, 0x61, 0x67, 0x18, 0x02, 0x20, 0x01, 0x28, - 0x05, 0x52, 0x0a, 0x63, 0x68, 0x61, 0x6e, 0x6e, 0x65, 0x6c, 0x54, 0x61, 0x67, 0x12, 0x41, 0x0a, - 0x0f, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x5f, 0x65, 0x6e, 0x64, 0x5f, 0x74, 0x69, 0x6d, 0x65, - 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, - 0x6e, 0x52, 0x0d, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x45, 0x6e, 0x64, 0x54, 0x69, 0x6d, 0x65, - 0x12, 0x28, 0x0a, 0x0d, 0x6c, 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, 0x5f, 0x63, 0x6f, 0x64, - 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x09, 0x42, 0x03, 0xe0, 0x41, 0x03, 0x52, 0x0c, 0x6c, 0x61, - 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, 0x43, 0x6f, 0x64, 0x65, 0x22, 0x9d, 0x01, 0x0a, 0x1c, 0x53, - 0x70, 0x65, 0x65, 0x63, 0x68, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x74, 0x69, 0x6f, 0x6e, - 0x41, 0x6c, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x74, 0x69, 0x76, 0x65, 0x12, 0x1e, 0x0a, 0x0a, 0x74, - 0x72, 0x61, 0x6e, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, - 0x0a, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x12, 0x1e, 0x0a, 0x0a, 0x63, - 0x6f, 0x6e, 0x66, 0x69, 0x64, 0x65, 0x6e, 0x63, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x02, 0x52, - 0x0a, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x64, 0x65, 0x6e, 0x63, 0x65, 0x12, 0x3d, 0x0a, 0x05, 0x77, - 0x6f, 0x72, 0x64, 0x73, 0x18, 0x03, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x27, 0x2e, 0x67, 0x6f, 0x6f, - 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, - 0x2e, 0x76, 0x31, 0x70, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x57, 0x6f, 0x72, 0x64, 0x49, - 0x6e, 0x66, 0x6f, 0x52, 0x05, 0x77, 0x6f, 0x72, 0x64, 0x73, 0x22, 0xd4, 0x01, 0x0a, 0x08, 0x57, - 0x6f, 0x72, 0x64, 0x49, 0x6e, 0x66, 0x6f, 0x12, 0x38, 0x0a, 0x0a, 0x73, 0x74, 0x61, 0x72, 0x74, - 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, - 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, - 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x09, 0x73, 0x74, 0x61, 0x72, 0x74, 0x54, 0x69, 0x6d, - 0x65, 0x12, 0x34, 0x0a, 0x08, 0x65, 0x6e, 0x64, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x02, 0x20, - 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, - 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x07, - 0x65, 0x6e, 0x64, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x12, 0x0a, 0x04, 0x77, 0x6f, 0x72, 0x64, 0x18, - 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x77, 0x6f, 0x72, 0x64, 0x12, 0x1e, 0x0a, 0x0a, 0x63, - 0x6f, 0x6e, 0x66, 0x69, 0x64, 0x65, 0x6e, 0x63, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x02, 0x52, - 0x0a, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x64, 0x65, 0x6e, 0x63, 0x65, 0x12, 0x24, 0x0a, 0x0b, 0x73, - 0x70, 0x65, 0x61, 0x6b, 0x65, 0x72, 0x5f, 0x74, 0x61, 0x67, 0x18, 0x05, 0x20, 0x01, 0x28, 0x05, - 0x42, 0x03, 0xe0, 0x41, 0x03, 0x52, 0x0a, 0x73, 0x70, 0x65, 0x61, 0x6b, 0x65, 0x72, 0x54, 0x61, - 0x67, 0x32, 0x82, 0x05, 0x0a, 0x06, 0x53, 0x70, 0x65, 0x65, 0x63, 0x68, 0x12, 0xa5, 0x01, 0x0a, - 0x09, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, 0x65, 0x12, 0x2f, 0x2e, 0x67, 0x6f, 0x6f, - 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, - 0x2e, 0x76, 0x31, 0x70, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x52, 0x65, 0x63, 0x6f, 0x67, - 0x6e, 0x69, 0x7a, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x30, 0x2e, 0x67, 0x6f, + 0x6e, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x52, 0x07, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x73, + 0x12, 0x75, 0x0a, 0x11, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x5f, 0x65, 0x76, 0x65, 0x6e, 0x74, + 0x5f, 0x74, 0x79, 0x70, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x49, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, - 0x68, 0x2e, 0x76, 0x31, 0x70, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x52, 0x65, 0x63, 0x6f, - 0x67, 0x6e, 0x69, 0x7a, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x35, 0x82, - 0xd3, 0xe4, 0x93, 0x02, 0x20, 0x22, 0x1b, 0x2f, 0x76, 0x31, 0x70, 0x31, 0x62, 0x65, 0x74, 0x61, - 0x31, 0x2f, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x3a, 0x72, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, - 0x7a, 0x65, 0x3a, 0x01, 0x2a, 0xda, 0x41, 0x0c, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2c, 0x61, - 0x75, 0x64, 0x69, 0x6f, 0x12, 0xf2, 0x01, 0x0a, 0x14, 0x4c, 0x6f, 0x6e, 0x67, 0x52, 0x75, 0x6e, - 0x6e, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, 0x65, 0x12, 0x3a, 0x2e, - 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, - 0x65, 0x63, 0x68, 0x2e, 0x76, 0x31, 0x70, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x4c, 0x6f, - 0x6e, 0x67, 0x52, 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, - 0x7a, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x1d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, - 0x6c, 0x65, 0x2e, 0x6c, 0x6f, 0x6e, 0x67, 0x72, 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x2e, 0x4f, - 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x22, 0x7f, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x2b, - 0x22, 0x26, 0x2f, 0x76, 0x31, 0x70, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2f, 0x73, 0x70, 0x65, - 0x65, 0x63, 0x68, 0x3a, 0x6c, 0x6f, 0x6e, 0x67, 0x72, 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x72, - 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, 0x65, 0x3a, 0x01, 0x2a, 0xda, 0x41, 0x0c, 0x63, 0x6f, - 0x6e, 0x66, 0x69, 0x67, 0x2c, 0x61, 0x75, 0x64, 0x69, 0x6f, 0xca, 0x41, 0x3c, 0x0a, 0x1c, 0x4c, - 0x6f, 0x6e, 0x67, 0x52, 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, - 0x69, 0x7a, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x1c, 0x4c, 0x6f, 0x6e, + 0x68, 0x2e, 0x76, 0x31, 0x70, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x53, 0x74, 0x72, 0x65, + 0x61, 0x6d, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, 0x65, 0x52, 0x65, + 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x53, 0x70, 0x65, 0x65, 0x63, 0x68, 0x45, 0x76, 0x65, + 0x6e, 0x74, 0x54, 0x79, 0x70, 0x65, 0x52, 0x0f, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x45, 0x76, + 0x65, 0x6e, 0x74, 0x54, 0x79, 0x70, 0x65, 0x12, 0x45, 0x0a, 0x11, 0x74, 0x6f, 0x74, 0x61, 0x6c, + 0x5f, 0x62, 0x69, 0x6c, 0x6c, 0x65, 0x64, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x05, 0x20, 0x01, + 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, + 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0f, 0x74, + 0x6f, 0x74, 0x61, 0x6c, 0x42, 0x69, 0x6c, 0x6c, 0x65, 0x64, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x69, + 0x0a, 0x16, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x5f, 0x61, 0x64, 0x61, 0x70, 0x74, 0x61, 0x74, + 0x69, 0x6f, 0x6e, 0x5f, 0x69, 0x6e, 0x66, 0x6f, 0x18, 0x09, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x33, + 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, + 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, 0x31, 0x70, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x53, + 0x70, 0x65, 0x65, 0x63, 0x68, 0x41, 0x64, 0x61, 0x70, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x49, + 0x6e, 0x66, 0x6f, 0x52, 0x14, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x41, 0x64, 0x61, 0x70, 0x74, + 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x49, 0x6e, 0x66, 0x6f, 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x71, + 0x75, 0x65, 0x73, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x03, 0x52, 0x09, 0x72, + 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x49, 0x64, 0x22, 0x4c, 0x0a, 0x0f, 0x53, 0x70, 0x65, 0x65, + 0x63, 0x68, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x54, 0x79, 0x70, 0x65, 0x12, 0x1c, 0x0a, 0x18, 0x53, + 0x50, 0x45, 0x45, 0x43, 0x48, 0x5f, 0x45, 0x56, 0x45, 0x4e, 0x54, 0x5f, 0x55, 0x4e, 0x53, 0x50, + 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x1b, 0x0a, 0x17, 0x45, 0x4e, 0x44, + 0x5f, 0x4f, 0x46, 0x5f, 0x53, 0x49, 0x4e, 0x47, 0x4c, 0x45, 0x5f, 0x55, 0x54, 0x54, 0x45, 0x52, + 0x41, 0x4e, 0x43, 0x45, 0x10, 0x01, 0x22, 0xc4, 0x02, 0x0a, 0x1a, 0x53, 0x74, 0x72, 0x65, 0x61, + 0x6d, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x52, + 0x65, 0x73, 0x75, 0x6c, 0x74, 0x12, 0x5f, 0x0a, 0x0c, 0x61, 0x6c, 0x74, 0x65, 0x72, 0x6e, 0x61, + 0x74, 0x69, 0x76, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x3b, 0x2e, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, + 0x68, 0x2e, 0x76, 0x31, 0x70, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x53, 0x70, 0x65, 0x65, + 0x63, 0x68, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x41, 0x6c, 0x74, + 0x65, 0x72, 0x6e, 0x61, 0x74, 0x69, 0x76, 0x65, 0x52, 0x0c, 0x61, 0x6c, 0x74, 0x65, 0x72, 0x6e, + 0x61, 0x74, 0x69, 0x76, 0x65, 0x73, 0x12, 0x19, 0x0a, 0x08, 0x69, 0x73, 0x5f, 0x66, 0x69, 0x6e, + 0x61, 0x6c, 0x18, 0x02, 0x20, 0x01, 0x28, 0x08, 0x52, 0x07, 0x69, 0x73, 0x46, 0x69, 0x6e, 0x61, + 0x6c, 0x12, 0x1c, 0x0a, 0x09, 0x73, 0x74, 0x61, 0x62, 0x69, 0x6c, 0x69, 0x74, 0x79, 0x18, 0x03, + 0x20, 0x01, 0x28, 0x02, 0x52, 0x09, 0x73, 0x74, 0x61, 0x62, 0x69, 0x6c, 0x69, 0x74, 0x79, 0x12, + 0x41, 0x0a, 0x0f, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x5f, 0x65, 0x6e, 0x64, 0x5f, 0x74, 0x69, + 0x6d, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, + 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, + 0x69, 0x6f, 0x6e, 0x52, 0x0d, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x45, 0x6e, 0x64, 0x54, 0x69, + 0x6d, 0x65, 0x12, 0x1f, 0x0a, 0x0b, 0x63, 0x68, 0x61, 0x6e, 0x6e, 0x65, 0x6c, 0x5f, 0x74, 0x61, + 0x67, 0x18, 0x05, 0x20, 0x01, 0x28, 0x05, 0x52, 0x0a, 0x63, 0x68, 0x61, 0x6e, 0x6e, 0x65, 0x6c, + 0x54, 0x61, 0x67, 0x12, 0x28, 0x0a, 0x0d, 0x6c, 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, 0x5f, + 0x63, 0x6f, 0x64, 0x65, 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, 0x42, 0x03, 0xe0, 0x41, 0x03, 0x52, + 0x0c, 0x6c, 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, 0x43, 0x6f, 0x64, 0x65, 0x22, 0x88, 0x02, + 0x0a, 0x17, 0x53, 0x70, 0x65, 0x65, 0x63, 0x68, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x74, + 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x12, 0x5f, 0x0a, 0x0c, 0x61, 0x6c, 0x74, + 0x65, 0x72, 0x6e, 0x61, 0x74, 0x69, 0x76, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, + 0x3b, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, + 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, 0x31, 0x70, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, + 0x53, 0x70, 0x65, 0x65, 0x63, 0x68, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x74, 0x69, 0x6f, + 0x6e, 0x41, 0x6c, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x74, 0x69, 0x76, 0x65, 0x52, 0x0c, 0x61, 0x6c, + 0x74, 0x65, 0x72, 0x6e, 0x61, 0x74, 0x69, 0x76, 0x65, 0x73, 0x12, 0x1f, 0x0a, 0x0b, 0x63, 0x68, + 0x61, 0x6e, 0x6e, 0x65, 0x6c, 0x5f, 0x74, 0x61, 0x67, 0x18, 0x02, 0x20, 0x01, 0x28, 0x05, 0x52, + 0x0a, 0x63, 0x68, 0x61, 0x6e, 0x6e, 0x65, 0x6c, 0x54, 0x61, 0x67, 0x12, 0x41, 0x0a, 0x0f, 0x72, + 0x65, 0x73, 0x75, 0x6c, 0x74, 0x5f, 0x65, 0x6e, 0x64, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x04, + 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, + 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, + 0x0d, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x45, 0x6e, 0x64, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x28, + 0x0a, 0x0d, 0x6c, 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, 0x5f, 0x63, 0x6f, 0x64, 0x65, 0x18, + 0x05, 0x20, 0x01, 0x28, 0x09, 0x42, 0x03, 0xe0, 0x41, 0x03, 0x52, 0x0c, 0x6c, 0x61, 0x6e, 0x67, + 0x75, 0x61, 0x67, 0x65, 0x43, 0x6f, 0x64, 0x65, 0x22, 0x9d, 0x01, 0x0a, 0x1c, 0x53, 0x70, 0x65, + 0x65, 0x63, 0x68, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x41, 0x6c, + 0x74, 0x65, 0x72, 0x6e, 0x61, 0x74, 0x69, 0x76, 0x65, 0x12, 0x1e, 0x0a, 0x0a, 0x74, 0x72, 0x61, + 0x6e, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, 0x74, + 0x72, 0x61, 0x6e, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x12, 0x1e, 0x0a, 0x0a, 0x63, 0x6f, 0x6e, + 0x66, 0x69, 0x64, 0x65, 0x6e, 0x63, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x02, 0x52, 0x0a, 0x63, + 0x6f, 0x6e, 0x66, 0x69, 0x64, 0x65, 0x6e, 0x63, 0x65, 0x12, 0x3d, 0x0a, 0x05, 0x77, 0x6f, 0x72, + 0x64, 0x73, 0x18, 0x03, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x27, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, + 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, + 0x31, 0x70, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x57, 0x6f, 0x72, 0x64, 0x49, 0x6e, 0x66, + 0x6f, 0x52, 0x05, 0x77, 0x6f, 0x72, 0x64, 0x73, 0x22, 0xd4, 0x01, 0x0a, 0x08, 0x57, 0x6f, 0x72, + 0x64, 0x49, 0x6e, 0x66, 0x6f, 0x12, 0x38, 0x0a, 0x0a, 0x73, 0x74, 0x61, 0x72, 0x74, 0x5f, 0x74, + 0x69, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, + 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, + 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x09, 0x73, 0x74, 0x61, 0x72, 0x74, 0x54, 0x69, 0x6d, 0x65, 0x12, + 0x34, 0x0a, 0x08, 0x65, 0x6e, 0x64, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, + 0x0b, 0x32, 0x19, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, + 0x62, 0x75, 0x66, 0x2e, 0x44, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x07, 0x65, 0x6e, + 0x64, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x12, 0x0a, 0x04, 0x77, 0x6f, 0x72, 0x64, 0x18, 0x03, 0x20, + 0x01, 0x28, 0x09, 0x52, 0x04, 0x77, 0x6f, 0x72, 0x64, 0x12, 0x1e, 0x0a, 0x0a, 0x63, 0x6f, 0x6e, + 0x66, 0x69, 0x64, 0x65, 0x6e, 0x63, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x02, 0x52, 0x0a, 0x63, + 0x6f, 0x6e, 0x66, 0x69, 0x64, 0x65, 0x6e, 0x63, 0x65, 0x12, 0x24, 0x0a, 0x0b, 0x73, 0x70, 0x65, + 0x61, 0x6b, 0x65, 0x72, 0x5f, 0x74, 0x61, 0x67, 0x18, 0x05, 0x20, 0x01, 0x28, 0x05, 0x42, 0x03, + 0xe0, 0x41, 0x03, 0x52, 0x0a, 0x73, 0x70, 0x65, 0x61, 0x6b, 0x65, 0x72, 0x54, 0x61, 0x67, 0x22, + 0x6e, 0x0a, 0x14, 0x53, 0x70, 0x65, 0x65, 0x63, 0x68, 0x41, 0x64, 0x61, 0x70, 0x74, 0x61, 0x74, + 0x69, 0x6f, 0x6e, 0x49, 0x6e, 0x66, 0x6f, 0x12, 0x2d, 0x0a, 0x12, 0x61, 0x64, 0x61, 0x70, 0x74, + 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x18, 0x01, 0x20, + 0x01, 0x28, 0x08, 0x52, 0x11, 0x61, 0x64, 0x61, 0x70, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x54, + 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x12, 0x27, 0x0a, 0x0f, 0x74, 0x69, 0x6d, 0x65, 0x6f, 0x75, + 0x74, 0x5f, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, + 0x0e, 0x74, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x32, + 0x82, 0x05, 0x0a, 0x06, 0x53, 0x70, 0x65, 0x65, 0x63, 0x68, 0x12, 0xa5, 0x01, 0x0a, 0x09, 0x52, + 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, 0x65, 0x12, 0x2f, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, + 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, + 0x31, 0x70, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, + 0x7a, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x30, 0x2e, 0x67, 0x6f, 0x6f, 0x67, + 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, + 0x76, 0x31, 0x70, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, + 0x69, 0x7a, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x35, 0x82, 0xd3, 0xe4, + 0x93, 0x02, 0x20, 0x22, 0x1b, 0x2f, 0x76, 0x31, 0x70, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2f, + 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x3a, 0x72, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, 0x65, + 0x3a, 0x01, 0x2a, 0xda, 0x41, 0x0c, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2c, 0x61, 0x75, 0x64, + 0x69, 0x6f, 0x12, 0xf2, 0x01, 0x0a, 0x14, 0x4c, 0x6f, 0x6e, 0x67, 0x52, 0x75, 0x6e, 0x6e, 0x69, + 0x6e, 0x67, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, 0x65, 0x12, 0x3a, 0x2e, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, + 0x68, 0x2e, 0x76, 0x31, 0x70, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x4c, 0x6f, 0x6e, 0x67, + 0x52, 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, 0x65, + 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x1d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, + 0x2e, 0x6c, 0x6f, 0x6e, 0x67, 0x72, 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x2e, 0x4f, 0x70, 0x65, + 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x22, 0x7f, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x2b, 0x22, 0x26, + 0x2f, 0x76, 0x31, 0x70, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2f, 0x73, 0x70, 0x65, 0x65, 0x63, + 0x68, 0x3a, 0x6c, 0x6f, 0x6e, 0x67, 0x72, 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x72, 0x65, 0x63, + 0x6f, 0x67, 0x6e, 0x69, 0x7a, 0x65, 0x3a, 0x01, 0x2a, 0xda, 0x41, 0x0c, 0x63, 0x6f, 0x6e, 0x66, + 0x69, 0x67, 0x2c, 0x61, 0x75, 0x64, 0x69, 0x6f, 0xca, 0x41, 0x3c, 0x0a, 0x1c, 0x4c, 0x6f, 0x6e, 0x67, 0x52, 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, - 0x65, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x12, 0x8f, 0x01, 0x0a, 0x12, 0x53, 0x74, - 0x72, 0x65, 0x61, 0x6d, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, 0x65, - 0x12, 0x38, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, - 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, 0x31, 0x70, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, - 0x2e, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, - 0x69, 0x7a, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x39, 0x2e, 0x67, 0x6f, 0x6f, + 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x1c, 0x4c, 0x6f, 0x6e, 0x67, 0x52, + 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, 0x65, 0x4d, + 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x12, 0x8f, 0x01, 0x0a, 0x12, 0x53, 0x74, 0x72, 0x65, + 0x61, 0x6d, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, 0x65, 0x12, 0x38, + 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, + 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, 0x31, 0x70, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x53, + 0x74, 0x72, 0x65, 0x61, 0x6d, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, + 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x39, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, + 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, 0x76, + 0x31, 0x70, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x69, + 0x6e, 0x67, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, + 0x6e, 0x73, 0x65, 0x22, 0x00, 0x28, 0x01, 0x30, 0x01, 0x1a, 0x49, 0xca, 0x41, 0x15, 0x73, 0x70, + 0x65, 0x65, 0x63, 0x68, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2e, + 0x63, 0x6f, 0x6d, 0xd2, 0x41, 0x2e, 0x68, 0x74, 0x74, 0x70, 0x73, 0x3a, 0x2f, 0x2f, 0x77, 0x77, + 0x77, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2e, 0x63, 0x6f, 0x6d, + 0x2f, 0x61, 0x75, 0x74, 0x68, 0x2f, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2d, 0x70, 0x6c, 0x61, 0x74, + 0x66, 0x6f, 0x72, 0x6d, 0x42, 0x80, 0x01, 0x0a, 0x21, 0x63, 0x6f, 0x6d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, - 0x2e, 0x76, 0x31, 0x70, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2e, 0x53, 0x74, 0x72, 0x65, 0x61, - 0x6d, 0x69, 0x6e, 0x67, 0x52, 0x65, 0x63, 0x6f, 0x67, 0x6e, 0x69, 0x7a, 0x65, 0x52, 0x65, 0x73, - 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x28, 0x01, 0x30, 0x01, 0x1a, 0x49, 0xca, 0x41, 0x15, - 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, - 0x73, 0x2e, 0x63, 0x6f, 0x6d, 0xd2, 0x41, 0x2e, 0x68, 0x74, 0x74, 0x70, 0x73, 0x3a, 0x2f, 0x2f, - 0x77, 0x77, 0x77, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2e, 0x63, - 0x6f, 0x6d, 0x2f, 0x61, 0x75, 0x74, 0x68, 0x2f, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2d, 0x70, 0x6c, - 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x42, 0x80, 0x01, 0x0a, 0x21, 0x63, 0x6f, 0x6d, 0x2e, 0x67, - 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x73, 0x70, 0x65, 0x65, - 0x63, 0x68, 0x2e, 0x76, 0x31, 0x70, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x42, 0x0b, 0x53, 0x70, - 0x65, 0x65, 0x63, 0x68, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x43, 0x67, 0x6f, 0x6f, - 0x67, 0x6c, 0x65, 0x2e, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x67, - 0x65, 0x6e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, - 0x69, 0x73, 0x2f, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2f, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2f, - 0x76, 0x31, 0x70, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x3b, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, - 0xf8, 0x01, 0x01, 0xa2, 0x02, 0x03, 0x47, 0x43, 0x53, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, - 0x33, + 0x2e, 0x76, 0x31, 0x70, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x42, 0x0b, 0x53, 0x70, 0x65, 0x65, + 0x63, 0x68, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x43, 0x67, 0x6f, 0x6f, 0x67, 0x6c, + 0x65, 0x2e, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x67, 0x65, 0x6e, + 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, + 0x2f, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2f, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0x2f, 0x76, 0x31, + 0x70, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x3b, 0x73, 0x70, 0x65, 0x65, 0x63, 0x68, 0xf8, 0x01, + 0x01, 0xa2, 0x02, 0x03, 0x47, 0x43, 0x53, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( @@ -2901,7 +3044,7 @@ func file_google_cloud_speech_v1p1beta1_cloud_speech_proto_rawDescGZIP() []byte } var file_google_cloud_speech_v1p1beta1_cloud_speech_proto_enumTypes = make([]protoimpl.EnumInfo, 6) -var file_google_cloud_speech_v1p1beta1_cloud_speech_proto_msgTypes = make([]protoimpl.MessageInfo, 18) +var file_google_cloud_speech_v1p1beta1_cloud_speech_proto_msgTypes = make([]protoimpl.MessageInfo, 19) var file_google_cloud_speech_v1p1beta1_cloud_speech_proto_goTypes = []interface{}{ (RecognitionConfig_AudioEncoding)(0), // 0: google.cloud.speech.v1p1beta1.RecognitionConfig.AudioEncoding (RecognitionMetadata_InteractionType)(0), // 1: google.cloud.speech.v1p1beta1.RecognitionMetadata.InteractionType @@ -2927,13 +3070,14 @@ var file_google_cloud_speech_v1p1beta1_cloud_speech_proto_goTypes = []interface{ (*SpeechRecognitionResult)(nil), // 21: google.cloud.speech.v1p1beta1.SpeechRecognitionResult (*SpeechRecognitionAlternative)(nil), // 22: google.cloud.speech.v1p1beta1.SpeechRecognitionAlternative (*WordInfo)(nil), // 23: google.cloud.speech.v1p1beta1.WordInfo - (*SpeechAdaptation)(nil), // 24: google.cloud.speech.v1p1beta1.SpeechAdaptation - (*TranscriptNormalization)(nil), // 25: google.cloud.speech.v1p1beta1.TranscriptNormalization - (*wrapperspb.BoolValue)(nil), // 26: google.protobuf.BoolValue - (*durationpb.Duration)(nil), // 27: google.protobuf.Duration - (*status.Status)(nil), // 28: google.rpc.Status - (*timestamppb.Timestamp)(nil), // 29: google.protobuf.Timestamp - (*longrunning.Operation)(nil), // 30: google.longrunning.Operation + (*SpeechAdaptationInfo)(nil), // 24: google.cloud.speech.v1p1beta1.SpeechAdaptationInfo + (*SpeechAdaptation)(nil), // 25: google.cloud.speech.v1p1beta1.SpeechAdaptation + (*TranscriptNormalization)(nil), // 26: google.cloud.speech.v1p1beta1.TranscriptNormalization + (*wrapperspb.BoolValue)(nil), // 27: google.protobuf.BoolValue + (*durationpb.Duration)(nil), // 28: google.protobuf.Duration + (*status.Status)(nil), // 29: google.rpc.Status + (*timestamppb.Timestamp)(nil), // 30: google.protobuf.Timestamp + (*longrunning.Operation)(nil), // 31: google.longrunning.Operation } var file_google_cloud_speech_v1p1beta1_cloud_speech_proto_depIdxs = []int32{ 11, // 0: google.cloud.speech.v1p1beta1.RecognizeRequest.config:type_name -> google.cloud.speech.v1p1beta1.RecognitionConfig @@ -2944,11 +3088,11 @@ var file_google_cloud_speech_v1p1beta1_cloud_speech_proto_depIdxs = []int32{ 10, // 5: google.cloud.speech.v1p1beta1.StreamingRecognizeRequest.streaming_config:type_name -> google.cloud.speech.v1p1beta1.StreamingRecognitionConfig 11, // 6: google.cloud.speech.v1p1beta1.StreamingRecognitionConfig.config:type_name -> google.cloud.speech.v1p1beta1.RecognitionConfig 0, // 7: google.cloud.speech.v1p1beta1.RecognitionConfig.encoding:type_name -> google.cloud.speech.v1p1beta1.RecognitionConfig.AudioEncoding - 24, // 8: google.cloud.speech.v1p1beta1.RecognitionConfig.adaptation:type_name -> google.cloud.speech.v1p1beta1.SpeechAdaptation - 25, // 9: google.cloud.speech.v1p1beta1.RecognitionConfig.transcript_normalization:type_name -> google.cloud.speech.v1p1beta1.TranscriptNormalization + 25, // 8: google.cloud.speech.v1p1beta1.RecognitionConfig.adaptation:type_name -> google.cloud.speech.v1p1beta1.SpeechAdaptation + 26, // 9: google.cloud.speech.v1p1beta1.RecognitionConfig.transcript_normalization:type_name -> google.cloud.speech.v1p1beta1.TranscriptNormalization 14, // 10: google.cloud.speech.v1p1beta1.RecognitionConfig.speech_contexts:type_name -> google.cloud.speech.v1p1beta1.SpeechContext - 26, // 11: google.cloud.speech.v1p1beta1.RecognitionConfig.enable_spoken_punctuation:type_name -> google.protobuf.BoolValue - 26, // 12: google.cloud.speech.v1p1beta1.RecognitionConfig.enable_spoken_emojis:type_name -> google.protobuf.BoolValue + 27, // 11: google.cloud.speech.v1p1beta1.RecognitionConfig.enable_spoken_punctuation:type_name -> google.protobuf.BoolValue + 27, // 12: google.cloud.speech.v1p1beta1.RecognitionConfig.enable_spoken_emojis:type_name -> google.protobuf.BoolValue 12, // 13: google.cloud.speech.v1p1beta1.RecognitionConfig.diarization_config:type_name -> google.cloud.speech.v1p1beta1.SpeakerDiarizationConfig 13, // 14: google.cloud.speech.v1p1beta1.RecognitionConfig.metadata:type_name -> google.cloud.speech.v1p1beta1.RecognitionMetadata 1, // 15: google.cloud.speech.v1p1beta1.RecognitionMetadata.interaction_type:type_name -> google.cloud.speech.v1p1beta1.RecognitionMetadata.InteractionType @@ -2956,36 +3100,39 @@ var file_google_cloud_speech_v1p1beta1_cloud_speech_proto_depIdxs = []int32{ 3, // 17: google.cloud.speech.v1p1beta1.RecognitionMetadata.original_media_type:type_name -> google.cloud.speech.v1p1beta1.RecognitionMetadata.OriginalMediaType 4, // 18: google.cloud.speech.v1p1beta1.RecognitionMetadata.recording_device_type:type_name -> google.cloud.speech.v1p1beta1.RecognitionMetadata.RecordingDeviceType 21, // 19: google.cloud.speech.v1p1beta1.RecognizeResponse.results:type_name -> google.cloud.speech.v1p1beta1.SpeechRecognitionResult - 27, // 20: google.cloud.speech.v1p1beta1.RecognizeResponse.total_billed_time:type_name -> google.protobuf.Duration - 21, // 21: google.cloud.speech.v1p1beta1.LongRunningRecognizeResponse.results:type_name -> google.cloud.speech.v1p1beta1.SpeechRecognitionResult - 27, // 22: google.cloud.speech.v1p1beta1.LongRunningRecognizeResponse.total_billed_time:type_name -> google.protobuf.Duration - 8, // 23: google.cloud.speech.v1p1beta1.LongRunningRecognizeResponse.output_config:type_name -> google.cloud.speech.v1p1beta1.TranscriptOutputConfig - 28, // 24: google.cloud.speech.v1p1beta1.LongRunningRecognizeResponse.output_error:type_name -> google.rpc.Status - 29, // 25: google.cloud.speech.v1p1beta1.LongRunningRecognizeMetadata.start_time:type_name -> google.protobuf.Timestamp - 29, // 26: google.cloud.speech.v1p1beta1.LongRunningRecognizeMetadata.last_update_time:type_name -> google.protobuf.Timestamp - 8, // 27: google.cloud.speech.v1p1beta1.LongRunningRecognizeMetadata.output_config:type_name -> google.cloud.speech.v1p1beta1.TranscriptOutputConfig - 28, // 28: google.cloud.speech.v1p1beta1.StreamingRecognizeResponse.error:type_name -> google.rpc.Status - 20, // 29: google.cloud.speech.v1p1beta1.StreamingRecognizeResponse.results:type_name -> google.cloud.speech.v1p1beta1.StreamingRecognitionResult - 5, // 30: google.cloud.speech.v1p1beta1.StreamingRecognizeResponse.speech_event_type:type_name -> google.cloud.speech.v1p1beta1.StreamingRecognizeResponse.SpeechEventType - 27, // 31: google.cloud.speech.v1p1beta1.StreamingRecognizeResponse.total_billed_time:type_name -> google.protobuf.Duration - 22, // 32: google.cloud.speech.v1p1beta1.StreamingRecognitionResult.alternatives:type_name -> google.cloud.speech.v1p1beta1.SpeechRecognitionAlternative - 27, // 33: google.cloud.speech.v1p1beta1.StreamingRecognitionResult.result_end_time:type_name -> google.protobuf.Duration - 22, // 34: google.cloud.speech.v1p1beta1.SpeechRecognitionResult.alternatives:type_name -> google.cloud.speech.v1p1beta1.SpeechRecognitionAlternative - 27, // 35: google.cloud.speech.v1p1beta1.SpeechRecognitionResult.result_end_time:type_name -> google.protobuf.Duration - 23, // 36: google.cloud.speech.v1p1beta1.SpeechRecognitionAlternative.words:type_name -> google.cloud.speech.v1p1beta1.WordInfo - 27, // 37: google.cloud.speech.v1p1beta1.WordInfo.start_time:type_name -> google.protobuf.Duration - 27, // 38: google.cloud.speech.v1p1beta1.WordInfo.end_time:type_name -> google.protobuf.Duration - 6, // 39: google.cloud.speech.v1p1beta1.Speech.Recognize:input_type -> google.cloud.speech.v1p1beta1.RecognizeRequest - 7, // 40: google.cloud.speech.v1p1beta1.Speech.LongRunningRecognize:input_type -> google.cloud.speech.v1p1beta1.LongRunningRecognizeRequest - 9, // 41: google.cloud.speech.v1p1beta1.Speech.StreamingRecognize:input_type -> google.cloud.speech.v1p1beta1.StreamingRecognizeRequest - 16, // 42: google.cloud.speech.v1p1beta1.Speech.Recognize:output_type -> google.cloud.speech.v1p1beta1.RecognizeResponse - 30, // 43: google.cloud.speech.v1p1beta1.Speech.LongRunningRecognize:output_type -> google.longrunning.Operation - 19, // 44: google.cloud.speech.v1p1beta1.Speech.StreamingRecognize:output_type -> google.cloud.speech.v1p1beta1.StreamingRecognizeResponse - 42, // [42:45] is the sub-list for method output_type - 39, // [39:42] is the sub-list for method input_type - 39, // [39:39] is the sub-list for extension type_name - 39, // [39:39] is the sub-list for extension extendee - 0, // [0:39] is the sub-list for field type_name + 28, // 20: google.cloud.speech.v1p1beta1.RecognizeResponse.total_billed_time:type_name -> google.protobuf.Duration + 24, // 21: google.cloud.speech.v1p1beta1.RecognizeResponse.speech_adaptation_info:type_name -> google.cloud.speech.v1p1beta1.SpeechAdaptationInfo + 21, // 22: google.cloud.speech.v1p1beta1.LongRunningRecognizeResponse.results:type_name -> google.cloud.speech.v1p1beta1.SpeechRecognitionResult + 28, // 23: google.cloud.speech.v1p1beta1.LongRunningRecognizeResponse.total_billed_time:type_name -> google.protobuf.Duration + 8, // 24: google.cloud.speech.v1p1beta1.LongRunningRecognizeResponse.output_config:type_name -> google.cloud.speech.v1p1beta1.TranscriptOutputConfig + 29, // 25: google.cloud.speech.v1p1beta1.LongRunningRecognizeResponse.output_error:type_name -> google.rpc.Status + 24, // 26: google.cloud.speech.v1p1beta1.LongRunningRecognizeResponse.speech_adaptation_info:type_name -> google.cloud.speech.v1p1beta1.SpeechAdaptationInfo + 30, // 27: google.cloud.speech.v1p1beta1.LongRunningRecognizeMetadata.start_time:type_name -> google.protobuf.Timestamp + 30, // 28: google.cloud.speech.v1p1beta1.LongRunningRecognizeMetadata.last_update_time:type_name -> google.protobuf.Timestamp + 8, // 29: google.cloud.speech.v1p1beta1.LongRunningRecognizeMetadata.output_config:type_name -> google.cloud.speech.v1p1beta1.TranscriptOutputConfig + 29, // 30: google.cloud.speech.v1p1beta1.StreamingRecognizeResponse.error:type_name -> google.rpc.Status + 20, // 31: google.cloud.speech.v1p1beta1.StreamingRecognizeResponse.results:type_name -> google.cloud.speech.v1p1beta1.StreamingRecognitionResult + 5, // 32: google.cloud.speech.v1p1beta1.StreamingRecognizeResponse.speech_event_type:type_name -> google.cloud.speech.v1p1beta1.StreamingRecognizeResponse.SpeechEventType + 28, // 33: google.cloud.speech.v1p1beta1.StreamingRecognizeResponse.total_billed_time:type_name -> google.protobuf.Duration + 24, // 34: google.cloud.speech.v1p1beta1.StreamingRecognizeResponse.speech_adaptation_info:type_name -> google.cloud.speech.v1p1beta1.SpeechAdaptationInfo + 22, // 35: google.cloud.speech.v1p1beta1.StreamingRecognitionResult.alternatives:type_name -> google.cloud.speech.v1p1beta1.SpeechRecognitionAlternative + 28, // 36: google.cloud.speech.v1p1beta1.StreamingRecognitionResult.result_end_time:type_name -> google.protobuf.Duration + 22, // 37: google.cloud.speech.v1p1beta1.SpeechRecognitionResult.alternatives:type_name -> google.cloud.speech.v1p1beta1.SpeechRecognitionAlternative + 28, // 38: google.cloud.speech.v1p1beta1.SpeechRecognitionResult.result_end_time:type_name -> google.protobuf.Duration + 23, // 39: google.cloud.speech.v1p1beta1.SpeechRecognitionAlternative.words:type_name -> google.cloud.speech.v1p1beta1.WordInfo + 28, // 40: google.cloud.speech.v1p1beta1.WordInfo.start_time:type_name -> google.protobuf.Duration + 28, // 41: google.cloud.speech.v1p1beta1.WordInfo.end_time:type_name -> google.protobuf.Duration + 6, // 42: google.cloud.speech.v1p1beta1.Speech.Recognize:input_type -> google.cloud.speech.v1p1beta1.RecognizeRequest + 7, // 43: google.cloud.speech.v1p1beta1.Speech.LongRunningRecognize:input_type -> google.cloud.speech.v1p1beta1.LongRunningRecognizeRequest + 9, // 44: google.cloud.speech.v1p1beta1.Speech.StreamingRecognize:input_type -> google.cloud.speech.v1p1beta1.StreamingRecognizeRequest + 16, // 45: google.cloud.speech.v1p1beta1.Speech.Recognize:output_type -> google.cloud.speech.v1p1beta1.RecognizeResponse + 31, // 46: google.cloud.speech.v1p1beta1.Speech.LongRunningRecognize:output_type -> google.longrunning.Operation + 19, // 47: google.cloud.speech.v1p1beta1.Speech.StreamingRecognize:output_type -> google.cloud.speech.v1p1beta1.StreamingRecognizeResponse + 45, // [45:48] is the sub-list for method output_type + 42, // [42:45] is the sub-list for method input_type + 42, // [42:42] is the sub-list for extension type_name + 42, // [42:42] is the sub-list for extension extendee + 0, // [0:42] is the sub-list for field type_name } func init() { file_google_cloud_speech_v1p1beta1_cloud_speech_proto_init() } @@ -3211,6 +3358,18 @@ func file_google_cloud_speech_v1p1beta1_cloud_speech_proto_init() { return nil } } + file_google_cloud_speech_v1p1beta1_cloud_speech_proto_msgTypes[18].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*SpeechAdaptationInfo); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } } file_google_cloud_speech_v1p1beta1_cloud_speech_proto_msgTypes[2].OneofWrappers = []interface{}{ (*TranscriptOutputConfig_GcsUri)(nil), @@ -3229,7 +3388,7 @@ func file_google_cloud_speech_v1p1beta1_cloud_speech_proto_init() { GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_google_cloud_speech_v1p1beta1_cloud_speech_proto_rawDesc, NumEnums: 6, - NumMessages: 18, + NumMessages: 19, NumExtensions: 0, NumServices: 1, }, diff --git a/speech/apiv1p1beta1/speechpb/cloud_speech_adaptation.pb.go b/speech/apiv1p1beta1/speechpb/cloud_speech_adaptation.pb.go index 1cbbd6b7924a..229a37e551b7 100644 --- a/speech/apiv1p1beta1/speechpb/cloud_speech_adaptation.pb.go +++ b/speech/apiv1p1beta1/speechpb/cloud_speech_adaptation.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/speech/v1p1beta1/cloud_speech_adaptation.proto package speechpb diff --git a/speech/apiv1p1beta1/speechpb/resource.pb.go b/speech/apiv1p1beta1/speechpb/resource.pb.go index ff99fac00a56..3ec529b82b33 100644 --- a/speech/apiv1p1beta1/speechpb/resource.pb.go +++ b/speech/apiv1p1beta1/speechpb/resource.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/speech/v1p1beta1/resource.proto package speechpb diff --git a/speech/apiv2/doc.go b/speech/apiv2/doc.go index 29f1f281c4a4..76cab93abfd6 100644 --- a/speech/apiv2/doc.go +++ b/speech/apiv2/doc.go @@ -87,6 +87,8 @@ package speech // import "cloud.google.com/go/speech/apiv2" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -175,3 +177,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/speech/apiv2/gapic_metadata.json b/speech/apiv2/gapic_metadata.json index 2e246af0d0ce..64908a867296 100644 --- a/speech/apiv2/gapic_metadata.json +++ b/speech/apiv2/gapic_metadata.json @@ -146,6 +146,146 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "BatchRecognize": { + "methods": [ + "BatchRecognize" + ] + }, + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "CreateCustomClass": { + "methods": [ + "CreateCustomClass" + ] + }, + "CreatePhraseSet": { + "methods": [ + "CreatePhraseSet" + ] + }, + "CreateRecognizer": { + "methods": [ + "CreateRecognizer" + ] + }, + "DeleteCustomClass": { + "methods": [ + "DeleteCustomClass" + ] + }, + "DeleteOperation": { + "methods": [ + "DeleteOperation" + ] + }, + "DeletePhraseSet": { + "methods": [ + "DeletePhraseSet" + ] + }, + "DeleteRecognizer": { + "methods": [ + "DeleteRecognizer" + ] + }, + "GetConfig": { + "methods": [ + "GetConfig" + ] + }, + "GetCustomClass": { + "methods": [ + "GetCustomClass" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "GetPhraseSet": { + "methods": [ + "GetPhraseSet" + ] + }, + "GetRecognizer": { + "methods": [ + "GetRecognizer" + ] + }, + "ListCustomClasses": { + "methods": [ + "ListCustomClasses" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "ListPhraseSets": { + "methods": [ + "ListPhraseSets" + ] + }, + "ListRecognizers": { + "methods": [ + "ListRecognizers" + ] + }, + "Recognize": { + "methods": [ + "Recognize" + ] + }, + "StreamingRecognize": { + "methods": [ + "StreamingRecognize" + ] + }, + "UndeleteCustomClass": { + "methods": [ + "UndeleteCustomClass" + ] + }, + "UndeletePhraseSet": { + "methods": [ + "UndeletePhraseSet" + ] + }, + "UndeleteRecognizer": { + "methods": [ + "UndeleteRecognizer" + ] + }, + "UpdateConfig": { + "methods": [ + "UpdateConfig" + ] + }, + "UpdateCustomClass": { + "methods": [ + "UpdateCustomClass" + ] + }, + "UpdatePhraseSet": { + "methods": [ + "UpdatePhraseSet" + ] + }, + "UpdateRecognizer": { + "methods": [ + "UpdateRecognizer" + ] + } + } } } } diff --git a/speech/apiv2/speech_client.go b/speech/apiv2/speech_client.go index 664468874658..a19dd00b4bfb 100644 --- a/speech/apiv2/speech_client.go +++ b/speech/apiv2/speech_client.go @@ -17,9 +17,12 @@ package speech import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,14 +30,17 @@ import ( lroauto "cloud.google.com/go/longrunning/autogen" speechpb "cloud.google.com/go/speech/apiv2/speechpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -368,6 +374,268 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + CreateRecognizer: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + ListRecognizers: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + GetRecognizer: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + UpdateRecognizer: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + DeleteRecognizer: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + UndeleteRecognizer: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + Recognize: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + StreamingRecognize: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + BatchRecognize: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + GetConfig: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + UpdateConfig: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + CreateCustomClass: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + ListCustomClasses: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + GetCustomClass: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + UpdateCustomClass: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + DeleteCustomClass: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + UndeleteCustomClass: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + CreatePhraseSet: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + ListPhraseSets: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + GetPhraseSet: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + UpdatePhraseSet: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + DeletePhraseSet: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + UndeletePhraseSet: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + CancelOperation: []gax.CallOption{}, + DeleteOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalClient is an interface that defines the methods available from Cloud Speech-to-Text API. type internalClient interface { Close() error @@ -520,6 +788,8 @@ func (c *Client) Recognize(ctx context.Context, req *speechpb.RecognizeRequest, // StreamingRecognize performs bidirectional streaming speech recognition: receive results while // sending audio. This method is only available via the gRPC API (not REST). +// +// This method is not supported for the REST transport. func (c *Client) StreamingRecognize(ctx context.Context, opts ...gax.CallOption) (speechpb.Speech_StreamingRecognizeClient, error) { return c.internalClient.StreamingRecognize(ctx, opts...) } @@ -777,6 +1047,89 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new speech rest client. +// +// Enables speech transcription and resource management. +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://speech.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://speech.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://speech.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) CreateRecognizer(ctx context.Context, req *speechpb.CreateRecognizerRequest, opts ...gax.CallOption) (*CreateRecognizerOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 5000000*time.Millisecond) @@ -1459,43 +1812,1895 @@ func (c *gRPCClient) ListOperations(ctx context.Context, req *longrunningpb.List return it } -// BatchRecognizeOperation manages a long-running operation from BatchRecognize. -type BatchRecognizeOperation struct { - lro *longrunning.Operation -} - -// BatchRecognizeOperation returns a new BatchRecognizeOperation from a given name. -// The name must be that of a previously created BatchRecognizeOperation, possibly from a different process. -func (c *gRPCClient) BatchRecognizeOperation(name string) *BatchRecognizeOperation { - return &BatchRecognizeOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), +// CreateRecognizer creates a Recognizer. +func (c *restClient) CreateRecognizer(ctx context.Context, req *speechpb.CreateRecognizerRequest, opts ...gax.CallOption) (*CreateRecognizerOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetRecognizer() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err } -} -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *BatchRecognizeOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*speechpb.BatchRecognizeResponse, error) { - var resp speechpb.BatchRecognizeResponse - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - return &resp, nil -} + baseUrl.Path += fmt.Sprintf("/v2/%v/recognizers", req.GetParent()) -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *BatchRecognizeOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*speechpb.BatchRecognizeResponse, error) { - var resp speechpb.BatchRecognizeResponse - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { - return nil, err + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRecognizerId() != "" { + params.Add("recognizerId", fmt.Sprintf("%v", req.GetRecognizerId())) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &CreateRecognizerOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListRecognizers lists Recognizers. +func (c *restClient) ListRecognizers(ctx context.Context, req *speechpb.ListRecognizersRequest, opts ...gax.CallOption) *RecognizerIterator { + it := &RecognizerIterator{} + req = proto.Clone(req).(*speechpb.ListRecognizersRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*speechpb.Recognizer, string, error) { + resp := &speechpb.ListRecognizersResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/recognizers", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + if req.GetShowDeleted() { + params.Add("showDeleted", fmt.Sprintf("%v", req.GetShowDeleted())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetRecognizers(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetRecognizer returns the requested +// Recognizer. Fails with +// NOT_FOUND if the requested recognizer doesn’t +// exist. +func (c *restClient) GetRecognizer(ctx context.Context, req *speechpb.GetRecognizerRequest, opts ...gax.CallOption) (*speechpb.Recognizer, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetRecognizer[0:len((*c.CallOptions).GetRecognizer):len((*c.CallOptions).GetRecognizer)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &speechpb.Recognizer{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateRecognizer updates the Recognizer. +func (c *restClient) UpdateRecognizer(ctx context.Context, req *speechpb.UpdateRecognizerRequest, opts ...gax.CallOption) (*UpdateRecognizerOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetRecognizer() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetRecognizer().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "recognizer.name", url.QueryEscape(req.GetRecognizer().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &UpdateRecognizerOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteRecognizer deletes the Recognizer. +func (c *restClient) DeleteRecognizer(ctx context.Context, req *speechpb.DeleteRecognizerRequest, opts ...gax.CallOption) (*DeleteRecognizerOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetAllowMissing() { + params.Add("allowMissing", fmt.Sprintf("%v", req.GetAllowMissing())) + } + if req.GetEtag() != "" { + params.Add("etag", fmt.Sprintf("%v", req.GetEtag())) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &DeleteRecognizerOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UndeleteRecognizer undeletes the Recognizer. +func (c *restClient) UndeleteRecognizer(ctx context.Context, req *speechpb.UndeleteRecognizerRequest, opts ...gax.CallOption) (*UndeleteRecognizerOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:undelete", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &UndeleteRecognizerOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// Recognize performs synchronous Speech recognition: receive results after all audio +// has been sent and processed. +func (c *restClient) Recognize(ctx context.Context, req *speechpb.RecognizeRequest, opts ...gax.CallOption) (*speechpb.RecognizeResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:recognize", req.GetRecognizer()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "recognizer", url.QueryEscape(req.GetRecognizer()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).Recognize[0:len((*c.CallOptions).Recognize):len((*c.CallOptions).Recognize)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &speechpb.RecognizeResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// StreamingRecognize performs bidirectional streaming speech recognition: receive results while +// sending audio. This method is only available via the gRPC API (not REST). +// +// This method is not supported for the REST transport. +func (c *restClient) StreamingRecognize(ctx context.Context, opts ...gax.CallOption) (speechpb.Speech_StreamingRecognizeClient, error) { + return nil, fmt.Errorf("StreamingRecognize not yet supported for REST clients") +} + +// BatchRecognize performs batch asynchronous speech recognition: send a request with N +// audio files and receive a long running operation that can be polled to see +// when the transcriptions are finished. +func (c *restClient) BatchRecognize(ctx context.Context, req *speechpb.BatchRecognizeRequest, opts ...gax.CallOption) (*BatchRecognizeOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:batchRecognize", req.GetRecognizer()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "recognizer", url.QueryEscape(req.GetRecognizer()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &BatchRecognizeOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetConfig returns the requested Config. +func (c *restClient) GetConfig(ctx context.Context, req *speechpb.GetConfigRequest, opts ...gax.CallOption) (*speechpb.Config, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetConfig[0:len((*c.CallOptions).GetConfig):len((*c.CallOptions).GetConfig)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &speechpb.Config{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateConfig updates the Config. +func (c *restClient) UpdateConfig(ctx context.Context, req *speechpb.UpdateConfigRequest, opts ...gax.CallOption) (*speechpb.Config, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetConfig() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetConfig().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "config.name", url.QueryEscape(req.GetConfig().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateConfig[0:len((*c.CallOptions).UpdateConfig):len((*c.CallOptions).UpdateConfig)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &speechpb.Config{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateCustomClass creates a CustomClass. +func (c *restClient) CreateCustomClass(ctx context.Context, req *speechpb.CreateCustomClassRequest, opts ...gax.CallOption) (*CreateCustomClassOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetCustomClass() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/customClasses", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetCustomClassId() != "" { + params.Add("customClassId", fmt.Sprintf("%v", req.GetCustomClassId())) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &CreateCustomClassOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListCustomClasses lists CustomClasses. +func (c *restClient) ListCustomClasses(ctx context.Context, req *speechpb.ListCustomClassesRequest, opts ...gax.CallOption) *CustomClassIterator { + it := &CustomClassIterator{} + req = proto.Clone(req).(*speechpb.ListCustomClassesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*speechpb.CustomClass, string, error) { + resp := &speechpb.ListCustomClassesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/customClasses", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + if req.GetShowDeleted() { + params.Add("showDeleted", fmt.Sprintf("%v", req.GetShowDeleted())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetCustomClasses(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetCustomClass returns the requested +// CustomClass. +func (c *restClient) GetCustomClass(ctx context.Context, req *speechpb.GetCustomClassRequest, opts ...gax.CallOption) (*speechpb.CustomClass, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetCustomClass[0:len((*c.CallOptions).GetCustomClass):len((*c.CallOptions).GetCustomClass)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &speechpb.CustomClass{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateCustomClass updates the CustomClass. +func (c *restClient) UpdateCustomClass(ctx context.Context, req *speechpb.UpdateCustomClassRequest, opts ...gax.CallOption) (*UpdateCustomClassOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetCustomClass() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetCustomClass().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "custom_class.name", url.QueryEscape(req.GetCustomClass().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &UpdateCustomClassOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteCustomClass deletes the CustomClass. +func (c *restClient) DeleteCustomClass(ctx context.Context, req *speechpb.DeleteCustomClassRequest, opts ...gax.CallOption) (*DeleteCustomClassOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetAllowMissing() { + params.Add("allowMissing", fmt.Sprintf("%v", req.GetAllowMissing())) + } + if req.GetEtag() != "" { + params.Add("etag", fmt.Sprintf("%v", req.GetEtag())) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &DeleteCustomClassOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UndeleteCustomClass undeletes the CustomClass. +func (c *restClient) UndeleteCustomClass(ctx context.Context, req *speechpb.UndeleteCustomClassRequest, opts ...gax.CallOption) (*UndeleteCustomClassOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:undelete", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &UndeleteCustomClassOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// CreatePhraseSet creates a PhraseSet. +func (c *restClient) CreatePhraseSet(ctx context.Context, req *speechpb.CreatePhraseSetRequest, opts ...gax.CallOption) (*CreatePhraseSetOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetPhraseSet() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/phraseSets", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPhraseSetId() != "" { + params.Add("phraseSetId", fmt.Sprintf("%v", req.GetPhraseSetId())) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &CreatePhraseSetOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListPhraseSets lists PhraseSets. +func (c *restClient) ListPhraseSets(ctx context.Context, req *speechpb.ListPhraseSetsRequest, opts ...gax.CallOption) *PhraseSetIterator { + it := &PhraseSetIterator{} + req = proto.Clone(req).(*speechpb.ListPhraseSetsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*speechpb.PhraseSet, string, error) { + resp := &speechpb.ListPhraseSetsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/phraseSets", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + if req.GetShowDeleted() { + params.Add("showDeleted", fmt.Sprintf("%v", req.GetShowDeleted())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetPhraseSets(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetPhraseSet returns the requested +// PhraseSet. +func (c *restClient) GetPhraseSet(ctx context.Context, req *speechpb.GetPhraseSetRequest, opts ...gax.CallOption) (*speechpb.PhraseSet, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetPhraseSet[0:len((*c.CallOptions).GetPhraseSet):len((*c.CallOptions).GetPhraseSet)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &speechpb.PhraseSet{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdatePhraseSet updates the PhraseSet. +func (c *restClient) UpdatePhraseSet(ctx context.Context, req *speechpb.UpdatePhraseSetRequest, opts ...gax.CallOption) (*UpdatePhraseSetOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetPhraseSet() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetPhraseSet().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "phrase_set.name", url.QueryEscape(req.GetPhraseSet().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &UpdatePhraseSetOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeletePhraseSet deletes the PhraseSet. +func (c *restClient) DeletePhraseSet(ctx context.Context, req *speechpb.DeletePhraseSetRequest, opts ...gax.CallOption) (*DeletePhraseSetOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetAllowMissing() { + params.Add("allowMissing", fmt.Sprintf("%v", req.GetAllowMissing())) + } + if req.GetEtag() != "" { + params.Add("etag", fmt.Sprintf("%v", req.GetEtag())) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &DeletePhraseSetOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UndeletePhraseSet undeletes the PhraseSet. +func (c *restClient) UndeletePhraseSet(ctx context.Context, req *speechpb.UndeletePhraseSetRequest, opts ...gax.CallOption) (*UndeletePhraseSetOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:undelete", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v2/%s", resp.GetName()) + return &UndeletePhraseSetOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *restClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// DeleteOperation is a utility method from google.longrunning.Operations. +func (c *restClient) DeleteOperation(ctx context.Context, req *longrunningpb.DeleteOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *restClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *restClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// BatchRecognizeOperation manages a long-running operation from BatchRecognize. +type BatchRecognizeOperation struct { + lro *longrunning.Operation + pollPath string +} + +// BatchRecognizeOperation returns a new BatchRecognizeOperation from a given name. +// The name must be that of a previously created BatchRecognizeOperation, possibly from a different process. +func (c *gRPCClient) BatchRecognizeOperation(name string) *BatchRecognizeOperation { + return &BatchRecognizeOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// BatchRecognizeOperation returns a new BatchRecognizeOperation from a given name. +// The name must be that of a previously created BatchRecognizeOperation, possibly from a different process. +func (c *restClient) BatchRecognizeOperation(name string) *BatchRecognizeOperation { + override := fmt.Sprintf("/v2/%s", name) + return &BatchRecognizeOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *BatchRecognizeOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*speechpb.BatchRecognizeResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp speechpb.BatchRecognizeResponse + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *BatchRecognizeOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*speechpb.BatchRecognizeResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp speechpb.BatchRecognizeResponse + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err } if !op.Done() { return nil, nil @@ -1530,7 +3735,8 @@ func (op *BatchRecognizeOperation) Name() string { // CreateCustomClassOperation manages a long-running operation from CreateCustomClass. type CreateCustomClassOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateCustomClassOperation returns a new CreateCustomClassOperation from a given name. @@ -1541,10 +3747,21 @@ func (c *gRPCClient) CreateCustomClassOperation(name string) *CreateCustomClassO } } +// CreateCustomClassOperation returns a new CreateCustomClassOperation from a given name. +// The name must be that of a previously created CreateCustomClassOperation, possibly from a different process. +func (c *restClient) CreateCustomClassOperation(name string) *CreateCustomClassOperation { + override := fmt.Sprintf("/v2/%s", name) + return &CreateCustomClassOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateCustomClassOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*speechpb.CustomClass, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp speechpb.CustomClass if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1562,6 +3779,7 @@ func (op *CreateCustomClassOperation) Wait(ctx context.Context, opts ...gax.Call // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateCustomClassOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*speechpb.CustomClass, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp speechpb.CustomClass if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1599,7 +3817,8 @@ func (op *CreateCustomClassOperation) Name() string { // CreatePhraseSetOperation manages a long-running operation from CreatePhraseSet. type CreatePhraseSetOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreatePhraseSetOperation returns a new CreatePhraseSetOperation from a given name. @@ -1610,10 +3829,21 @@ func (c *gRPCClient) CreatePhraseSetOperation(name string) *CreatePhraseSetOpera } } +// CreatePhraseSetOperation returns a new CreatePhraseSetOperation from a given name. +// The name must be that of a previously created CreatePhraseSetOperation, possibly from a different process. +func (c *restClient) CreatePhraseSetOperation(name string) *CreatePhraseSetOperation { + override := fmt.Sprintf("/v2/%s", name) + return &CreatePhraseSetOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreatePhraseSetOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*speechpb.PhraseSet, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp speechpb.PhraseSet if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1631,6 +3861,7 @@ func (op *CreatePhraseSetOperation) Wait(ctx context.Context, opts ...gax.CallOp // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreatePhraseSetOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*speechpb.PhraseSet, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp speechpb.PhraseSet if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1668,7 +3899,8 @@ func (op *CreatePhraseSetOperation) Name() string { // CreateRecognizerOperation manages a long-running operation from CreateRecognizer. type CreateRecognizerOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateRecognizerOperation returns a new CreateRecognizerOperation from a given name. @@ -1679,10 +3911,21 @@ func (c *gRPCClient) CreateRecognizerOperation(name string) *CreateRecognizerOpe } } +// CreateRecognizerOperation returns a new CreateRecognizerOperation from a given name. +// The name must be that of a previously created CreateRecognizerOperation, possibly from a different process. +func (c *restClient) CreateRecognizerOperation(name string) *CreateRecognizerOperation { + override := fmt.Sprintf("/v2/%s", name) + return &CreateRecognizerOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateRecognizerOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*speechpb.Recognizer, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp speechpb.Recognizer if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1700,6 +3943,7 @@ func (op *CreateRecognizerOperation) Wait(ctx context.Context, opts ...gax.CallO // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateRecognizerOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*speechpb.Recognizer, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp speechpb.Recognizer if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1737,7 +3981,8 @@ func (op *CreateRecognizerOperation) Name() string { // DeleteCustomClassOperation manages a long-running operation from DeleteCustomClass. type DeleteCustomClassOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteCustomClassOperation returns a new DeleteCustomClassOperation from a given name. @@ -1748,10 +3993,21 @@ func (c *gRPCClient) DeleteCustomClassOperation(name string) *DeleteCustomClassO } } +// DeleteCustomClassOperation returns a new DeleteCustomClassOperation from a given name. +// The name must be that of a previously created DeleteCustomClassOperation, possibly from a different process. +func (c *restClient) DeleteCustomClassOperation(name string) *DeleteCustomClassOperation { + override := fmt.Sprintf("/v2/%s", name) + return &DeleteCustomClassOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteCustomClassOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*speechpb.CustomClass, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp speechpb.CustomClass if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1769,6 +4025,7 @@ func (op *DeleteCustomClassOperation) Wait(ctx context.Context, opts ...gax.Call // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteCustomClassOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*speechpb.CustomClass, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp speechpb.CustomClass if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1806,7 +4063,8 @@ func (op *DeleteCustomClassOperation) Name() string { // DeletePhraseSetOperation manages a long-running operation from DeletePhraseSet. type DeletePhraseSetOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeletePhraseSetOperation returns a new DeletePhraseSetOperation from a given name. @@ -1817,10 +4075,21 @@ func (c *gRPCClient) DeletePhraseSetOperation(name string) *DeletePhraseSetOpera } } +// DeletePhraseSetOperation returns a new DeletePhraseSetOperation from a given name. +// The name must be that of a previously created DeletePhraseSetOperation, possibly from a different process. +func (c *restClient) DeletePhraseSetOperation(name string) *DeletePhraseSetOperation { + override := fmt.Sprintf("/v2/%s", name) + return &DeletePhraseSetOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeletePhraseSetOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*speechpb.PhraseSet, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp speechpb.PhraseSet if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1838,6 +4107,7 @@ func (op *DeletePhraseSetOperation) Wait(ctx context.Context, opts ...gax.CallOp // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeletePhraseSetOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*speechpb.PhraseSet, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp speechpb.PhraseSet if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1875,7 +4145,8 @@ func (op *DeletePhraseSetOperation) Name() string { // DeleteRecognizerOperation manages a long-running operation from DeleteRecognizer. type DeleteRecognizerOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteRecognizerOperation returns a new DeleteRecognizerOperation from a given name. @@ -1886,10 +4157,21 @@ func (c *gRPCClient) DeleteRecognizerOperation(name string) *DeleteRecognizerOpe } } +// DeleteRecognizerOperation returns a new DeleteRecognizerOperation from a given name. +// The name must be that of a previously created DeleteRecognizerOperation, possibly from a different process. +func (c *restClient) DeleteRecognizerOperation(name string) *DeleteRecognizerOperation { + override := fmt.Sprintf("/v2/%s", name) + return &DeleteRecognizerOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteRecognizerOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*speechpb.Recognizer, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp speechpb.Recognizer if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1907,6 +4189,7 @@ func (op *DeleteRecognizerOperation) Wait(ctx context.Context, opts ...gax.CallO // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteRecognizerOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*speechpb.Recognizer, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp speechpb.Recognizer if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1944,7 +4227,8 @@ func (op *DeleteRecognizerOperation) Name() string { // UndeleteCustomClassOperation manages a long-running operation from UndeleteCustomClass. type UndeleteCustomClassOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UndeleteCustomClassOperation returns a new UndeleteCustomClassOperation from a given name. @@ -1955,10 +4239,21 @@ func (c *gRPCClient) UndeleteCustomClassOperation(name string) *UndeleteCustomCl } } +// UndeleteCustomClassOperation returns a new UndeleteCustomClassOperation from a given name. +// The name must be that of a previously created UndeleteCustomClassOperation, possibly from a different process. +func (c *restClient) UndeleteCustomClassOperation(name string) *UndeleteCustomClassOperation { + override := fmt.Sprintf("/v2/%s", name) + return &UndeleteCustomClassOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UndeleteCustomClassOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*speechpb.CustomClass, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp speechpb.CustomClass if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1976,6 +4271,7 @@ func (op *UndeleteCustomClassOperation) Wait(ctx context.Context, opts ...gax.Ca // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UndeleteCustomClassOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*speechpb.CustomClass, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp speechpb.CustomClass if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2013,7 +4309,8 @@ func (op *UndeleteCustomClassOperation) Name() string { // UndeletePhraseSetOperation manages a long-running operation from UndeletePhraseSet. type UndeletePhraseSetOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UndeletePhraseSetOperation returns a new UndeletePhraseSetOperation from a given name. @@ -2024,10 +4321,21 @@ func (c *gRPCClient) UndeletePhraseSetOperation(name string) *UndeletePhraseSetO } } +// UndeletePhraseSetOperation returns a new UndeletePhraseSetOperation from a given name. +// The name must be that of a previously created UndeletePhraseSetOperation, possibly from a different process. +func (c *restClient) UndeletePhraseSetOperation(name string) *UndeletePhraseSetOperation { + override := fmt.Sprintf("/v2/%s", name) + return &UndeletePhraseSetOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UndeletePhraseSetOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*speechpb.PhraseSet, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp speechpb.PhraseSet if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2045,6 +4353,7 @@ func (op *UndeletePhraseSetOperation) Wait(ctx context.Context, opts ...gax.Call // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UndeletePhraseSetOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*speechpb.PhraseSet, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp speechpb.PhraseSet if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2082,7 +4391,8 @@ func (op *UndeletePhraseSetOperation) Name() string { // UndeleteRecognizerOperation manages a long-running operation from UndeleteRecognizer. type UndeleteRecognizerOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UndeleteRecognizerOperation returns a new UndeleteRecognizerOperation from a given name. @@ -2093,10 +4403,21 @@ func (c *gRPCClient) UndeleteRecognizerOperation(name string) *UndeleteRecognize } } +// UndeleteRecognizerOperation returns a new UndeleteRecognizerOperation from a given name. +// The name must be that of a previously created UndeleteRecognizerOperation, possibly from a different process. +func (c *restClient) UndeleteRecognizerOperation(name string) *UndeleteRecognizerOperation { + override := fmt.Sprintf("/v2/%s", name) + return &UndeleteRecognizerOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UndeleteRecognizerOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*speechpb.Recognizer, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp speechpb.Recognizer if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2114,6 +4435,7 @@ func (op *UndeleteRecognizerOperation) Wait(ctx context.Context, opts ...gax.Cal // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UndeleteRecognizerOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*speechpb.Recognizer, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp speechpb.Recognizer if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2151,7 +4473,8 @@ func (op *UndeleteRecognizerOperation) Name() string { // UpdateCustomClassOperation manages a long-running operation from UpdateCustomClass. type UpdateCustomClassOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateCustomClassOperation returns a new UpdateCustomClassOperation from a given name. @@ -2162,10 +4485,21 @@ func (c *gRPCClient) UpdateCustomClassOperation(name string) *UpdateCustomClassO } } +// UpdateCustomClassOperation returns a new UpdateCustomClassOperation from a given name. +// The name must be that of a previously created UpdateCustomClassOperation, possibly from a different process. +func (c *restClient) UpdateCustomClassOperation(name string) *UpdateCustomClassOperation { + override := fmt.Sprintf("/v2/%s", name) + return &UpdateCustomClassOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateCustomClassOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*speechpb.CustomClass, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp speechpb.CustomClass if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2183,6 +4517,7 @@ func (op *UpdateCustomClassOperation) Wait(ctx context.Context, opts ...gax.Call // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateCustomClassOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*speechpb.CustomClass, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp speechpb.CustomClass if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2220,7 +4555,8 @@ func (op *UpdateCustomClassOperation) Name() string { // UpdatePhraseSetOperation manages a long-running operation from UpdatePhraseSet. type UpdatePhraseSetOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdatePhraseSetOperation returns a new UpdatePhraseSetOperation from a given name. @@ -2231,10 +4567,21 @@ func (c *gRPCClient) UpdatePhraseSetOperation(name string) *UpdatePhraseSetOpera } } +// UpdatePhraseSetOperation returns a new UpdatePhraseSetOperation from a given name. +// The name must be that of a previously created UpdatePhraseSetOperation, possibly from a different process. +func (c *restClient) UpdatePhraseSetOperation(name string) *UpdatePhraseSetOperation { + override := fmt.Sprintf("/v2/%s", name) + return &UpdatePhraseSetOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdatePhraseSetOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*speechpb.PhraseSet, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp speechpb.PhraseSet if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2252,6 +4599,7 @@ func (op *UpdatePhraseSetOperation) Wait(ctx context.Context, opts ...gax.CallOp // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdatePhraseSetOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*speechpb.PhraseSet, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp speechpb.PhraseSet if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2289,7 +4637,8 @@ func (op *UpdatePhraseSetOperation) Name() string { // UpdateRecognizerOperation manages a long-running operation from UpdateRecognizer. type UpdateRecognizerOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateRecognizerOperation returns a new UpdateRecognizerOperation from a given name. @@ -2300,10 +4649,21 @@ func (c *gRPCClient) UpdateRecognizerOperation(name string) *UpdateRecognizerOpe } } +// UpdateRecognizerOperation returns a new UpdateRecognizerOperation from a given name. +// The name must be that of a previously created UpdateRecognizerOperation, possibly from a different process. +func (c *restClient) UpdateRecognizerOperation(name string) *UpdateRecognizerOperation { + override := fmt.Sprintf("/v2/%s", name) + return &UpdateRecognizerOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateRecognizerOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*speechpb.Recognizer, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp speechpb.Recognizer if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2321,6 +4681,7 @@ func (op *UpdateRecognizerOperation) Wait(ctx context.Context, opts ...gax.CallO // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateRecognizerOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*speechpb.Recognizer, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp speechpb.Recognizer if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/speech/apiv2/speech_client_example_test.go b/speech/apiv2/speech_client_example_test.go index 5803af9755f3..b359f52c951d 100644 --- a/speech/apiv2/speech_client_example_test.go +++ b/speech/apiv2/speech_client_example_test.go @@ -43,6 +43,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := speech.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_CreateRecognizer() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/speech/apiv2/speechpb/cloud_speech.pb.go b/speech/apiv2/speechpb/cloud_speech.pb.go index 98eefa49d6a7..70f792c8cd93 100644 --- a/speech/apiv2/speechpb/cloud_speech.pb.go +++ b/speech/apiv2/speechpb/cloud_speech.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/speech/v2/cloud_speech.proto package speechpb @@ -494,7 +494,6 @@ type OperationMetadata struct { // The request that spawned the Operation. // // Types that are assignable to Request: - // // *OperationMetadata_BatchRecognizeRequest // *OperationMetadata_CreateRecognizerRequest // *OperationMetadata_UpdateRecognizerRequest @@ -516,7 +515,6 @@ type OperationMetadata struct { // Specific metadata per RPC // // Types that are assignable to Metadata: - // // *OperationMetadata_BatchRecognizeMetadata Metadata isOperationMetadata_Metadata `protobuf_oneof:"metadata"` } @@ -1282,13 +1280,13 @@ type Recognizer struct { // // - `latest_long` // - // Best for long form content like media or conversation. + // Best for long form content like media or conversation. // // - `latest_short` // - // Best for short form content like commands or single shot directed speech. - // When using this model, the service will stop transcribing audio after the - // first utterance is detected and completed. + // Best for short form content like commands or single shot directed speech. + // When using this model, the service will stop transcribing audio after the + // first utterance is detected and completed. // // When using this model, // [SEPARATE_RECOGNITION_PER_CHANNEL][google.cloud.speech.v2.RecognitionFeatures.MultiChannelMode.SEPARATE_RECOGNITION_PER_CHANNEL] @@ -1906,7 +1904,6 @@ type RecognitionConfig struct { // Decoding parameters for audio being sent for recognition. // // Types that are assignable to DecodingConfig: - // // *RecognitionConfig_AutoDecodingConfig // *RecognitionConfig_ExplicitDecodingConfig DecodingConfig isRecognitionConfig_DecodingConfig `protobuf_oneof:"decoding_config"` @@ -2043,7 +2040,6 @@ type RecognizeRequest struct { // Storage URI. // // Types that are assignable to AudioSource: - // // *RecognizeRequest_Content // *RecognizeRequest_Uri AudioSource isRecognizeRequest_AudioSource `protobuf_oneof:"audio_source"` @@ -2712,7 +2708,6 @@ type StreamingRecognizeRequest struct { // [default_recognition_config][google.cloud.speech.v2.Recognizer.default_recognition_config]. Recognizer string `protobuf:"bytes,3,opt,name=recognizer,proto3" json:"recognizer,omitempty"` // Types that are assignable to StreamingRequest: - // // *StreamingRecognizeRequest_StreamingConfig // *StreamingRecognizeRequest_Audio StreamingRequest isStreamingRecognizeRequest_StreamingRequest `protobuf_oneof:"streaming_request"` @@ -3129,7 +3124,6 @@ type BatchRecognizeFileMetadata struct { // The audio source, which is a Google Cloud Storage URI. // // Types that are assignable to AudioSource: - // // *BatchRecognizeFileMetadata_Uri AudioSource isBatchRecognizeFileMetadata_AudioSource `protobuf_oneof:"audio_source"` // Features and audio metadata to use for the Automatic Speech Recognition. @@ -5068,7 +5062,6 @@ type SpeechAdaptation_AdaptationPhraseSet struct { unknownFields protoimpl.UnknownFields // Types that are assignable to Value: - // // *SpeechAdaptation_AdaptationPhraseSet_PhraseSet // *SpeechAdaptation_AdaptationPhraseSet_InlinePhraseSet Value isSpeechAdaptation_AdaptationPhraseSet_Value `protobuf_oneof:"value"` diff --git a/storage/internal/apiv2/stubs/storage.pb.go b/storage/internal/apiv2/stubs/storage.pb.go index f81e216c575e..4f5bb62e7787 100644 --- a/storage/internal/apiv2/stubs/storage.pb.go +++ b/storage/internal/apiv2/stubs/storage.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/storage/v2/storage.proto package storage @@ -1878,7 +1878,6 @@ type WriteObjectRequest struct { // The first message of each stream should set one of the following. // // Types that are assignable to FirstMessage: - // // *WriteObjectRequest_UploadId // *WriteObjectRequest_WriteObjectSpec FirstMessage isWriteObjectRequest_FirstMessage `protobuf_oneof:"first_message"` @@ -1899,7 +1898,6 @@ type WriteObjectRequest struct { // A portion of the data for the object. // // Types that are assignable to Data: - // // *WriteObjectRequest_ChecksummedData Data isWriteObjectRequest_Data `protobuf_oneof:"data"` // Checksums for the complete object. If the checksums computed by the service @@ -2054,7 +2052,6 @@ type WriteObjectResponse struct { // The response will set one of the following. // // Types that are assignable to WriteStatus: - // // *WriteObjectResponse_PersistedSize // *WriteObjectResponse_Resource WriteStatus isWriteObjectResponse_WriteStatus `protobuf_oneof:"write_status"` @@ -2354,7 +2351,6 @@ type QueryWriteStatusResponse struct { // The response will set one of the following. // // Types that are assignable to WriteStatus: - // // *QueryWriteStatusResponse_PersistedSize // *QueryWriteStatusResponse_Resource WriteStatus isQueryWriteStatusResponse_WriteStatus `protobuf_oneof:"write_status"` diff --git a/storagetransfer/apiv1/doc.go b/storagetransfer/apiv1/doc.go index 691b6a5a108c..f544a6224486 100644 --- a/storagetransfer/apiv1/doc.go +++ b/storagetransfer/apiv1/doc.go @@ -81,6 +81,8 @@ package storagetransfer // import "cloud.google.com/go/storagetransfer/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -169,3 +171,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/storagetransfer/apiv1/gapic_metadata.json b/storagetransfer/apiv1/gapic_metadata.json index 44e3280b4c54..bdb541ac06ae 100644 --- a/storagetransfer/apiv1/gapic_metadata.json +++ b/storagetransfer/apiv1/gapic_metadata.json @@ -96,6 +96,96 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "CreateAgentPool": { + "methods": [ + "CreateAgentPool" + ] + }, + "CreateTransferJob": { + "methods": [ + "CreateTransferJob" + ] + }, + "DeleteAgentPool": { + "methods": [ + "DeleteAgentPool" + ] + }, + "DeleteTransferJob": { + "methods": [ + "DeleteTransferJob" + ] + }, + "GetAgentPool": { + "methods": [ + "GetAgentPool" + ] + }, + "GetGoogleServiceAccount": { + "methods": [ + "GetGoogleServiceAccount" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "GetTransferJob": { + "methods": [ + "GetTransferJob" + ] + }, + "ListAgentPools": { + "methods": [ + "ListAgentPools" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "ListTransferJobs": { + "methods": [ + "ListTransferJobs" + ] + }, + "PauseTransferOperation": { + "methods": [ + "PauseTransferOperation" + ] + }, + "ResumeTransferOperation": { + "methods": [ + "ResumeTransferOperation" + ] + }, + "RunTransferJob": { + "methods": [ + "RunTransferJob" + ] + }, + "UpdateAgentPool": { + "methods": [ + "UpdateAgentPool" + ] + }, + "UpdateTransferJob": { + "methods": [ + "UpdateTransferJob" + ] + } + } } } } diff --git a/storagetransfer/apiv1/storage_transfer_client.go b/storagetransfer/apiv1/storage_transfer_client.go index 66d15e31002c..655cbc164b9c 100644 --- a/storagetransfer/apiv1/storage_transfer_client.go +++ b/storagetransfer/apiv1/storage_transfer_client.go @@ -17,9 +17,12 @@ package storagetransfer import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,14 +30,17 @@ import ( lroauto "cloud.google.com/go/longrunning/autogen" storagetransferpb "cloud.google.com/go/storagetransfer/apiv1/storagetransferpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -255,6 +261,172 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + GetGoogleServiceAccount: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 2.00, + }, + http.StatusServiceUnavailable) + }), + }, + CreateTransferJob: []gax.CallOption{}, + UpdateTransferJob: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 2.00, + }, + http.StatusServiceUnavailable) + }), + }, + GetTransferJob: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 2.00, + }, + http.StatusServiceUnavailable) + }), + }, + ListTransferJobs: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 2.00, + }, + http.StatusServiceUnavailable) + }), + }, + PauseTransferOperation: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 2.00, + }, + http.StatusServiceUnavailable) + }), + }, + ResumeTransferOperation: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 2.00, + }, + http.StatusServiceUnavailable) + }), + }, + RunTransferJob: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 2.00, + }, + http.StatusServiceUnavailable) + }), + }, + DeleteTransferJob: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 2.00, + }, + http.StatusServiceUnavailable) + }), + }, + CreateAgentPool: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 2.00, + }, + http.StatusServiceUnavailable) + }), + }, + UpdateAgentPool: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 2.00, + }, + http.StatusServiceUnavailable) + }), + }, + GetAgentPool: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 2.00, + }, + http.StatusServiceUnavailable) + }), + }, + ListAgentPools: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 2.00, + }, + http.StatusServiceUnavailable) + }), + }, + DeleteAgentPool: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 2.00, + }, + http.StatusServiceUnavailable) + }), + }, + CancelOperation: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 2.00, + }, + http.StatusServiceUnavailable) + }), + }, + GetOperation: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 2.00, + }, + http.StatusServiceUnavailable) + }), + }, + ListOperations: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 2.00, + }, + http.StatusServiceUnavailable) + }), + }, + } +} + // internalClient is an interface that defines the methods available from Storage Transfer API. type internalClient interface { Close() error @@ -553,6 +725,91 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new storage transfer service rest client. +// +// Storage Transfer Service and its protos. +// Transfers data between between Google Cloud Storage buckets or from a data +// source external to Google to a Cloud Storage bucket. +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://storagetransfer.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://storagetransfer.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://storagetransfer.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) GetGoogleServiceAccount(ctx context.Context, req *storagetransferpb.GetGoogleServiceAccountRequest, opts ...gax.CallOption) (*storagetransferpb.GoogleServiceAccount, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) @@ -974,16 +1231,1121 @@ func (c *gRPCClient) ListOperations(ctx context.Context, req *longrunningpb.List return it } -// RunTransferJobOperation manages a long-running operation from RunTransferJob. -type RunTransferJobOperation struct { - lro *longrunning.Operation +// GetGoogleServiceAccount returns the Google service account that is used by Storage Transfer +// Service to access buckets in the project where transfers +// run or in other projects. Each Google service account is associated +// with one Google Cloud project. Users +// should add this service account to the Google Cloud Storage bucket +// ACLs to grant access to Storage Transfer Service. This service +// account is created and owned by Storage Transfer Service and can +// only be used by Storage Transfer Service. +func (c *restClient) GetGoogleServiceAccount(ctx context.Context, req *storagetransferpb.GetGoogleServiceAccountRequest, opts ...gax.CallOption) (*storagetransferpb.GoogleServiceAccount, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/googleServiceAccounts/%v", req.GetProjectId()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "project_id", url.QueryEscape(req.GetProjectId()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetGoogleServiceAccount[0:len((*c.CallOptions).GetGoogleServiceAccount):len((*c.CallOptions).GetGoogleServiceAccount)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &storagetransferpb.GoogleServiceAccount{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil } -// RunTransferJobOperation returns a new RunTransferJobOperation from a given name. -// The name must be that of a previously created RunTransferJobOperation, possibly from a different process. -func (c *gRPCClient) RunTransferJobOperation(name string) *RunTransferJobOperation { - return &RunTransferJobOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), +// CreateTransferJob creates a transfer job that runs periodically. +func (c *restClient) CreateTransferJob(ctx context.Context, req *storagetransferpb.CreateTransferJobRequest, opts ...gax.CallOption) (*storagetransferpb.TransferJob, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetTransferJob() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/transferJobs") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateTransferJob[0:len((*c.CallOptions).CreateTransferJob):len((*c.CallOptions).CreateTransferJob)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &storagetransferpb.TransferJob{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateTransferJob updates a transfer job. Updating a job’s transfer spec does not affect +// transfer operations that are running already. +// +// Note: The job’s status field can be modified +// using this RPC (for example, to set a job’s status to +// DELETED, +// DISABLED, or +// ENABLED). +func (c *restClient) UpdateTransferJob(ctx context.Context, req *storagetransferpb.UpdateTransferJobRequest, opts ...gax.CallOption) (*storagetransferpb.TransferJob, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetJobName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "job_name", url.QueryEscape(req.GetJobName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateTransferJob[0:len((*c.CallOptions).UpdateTransferJob):len((*c.CallOptions).UpdateTransferJob)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &storagetransferpb.TransferJob{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetTransferJob gets a transfer job. +func (c *restClient) GetTransferJob(ctx context.Context, req *storagetransferpb.GetTransferJobRequest, opts ...gax.CallOption) (*storagetransferpb.TransferJob, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetJobName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("projectId", fmt.Sprintf("%v", req.GetProjectId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "job_name", url.QueryEscape(req.GetJobName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetTransferJob[0:len((*c.CallOptions).GetTransferJob):len((*c.CallOptions).GetTransferJob)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &storagetransferpb.TransferJob{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListTransferJobs lists transfer jobs. +func (c *restClient) ListTransferJobs(ctx context.Context, req *storagetransferpb.ListTransferJobsRequest, opts ...gax.CallOption) *TransferJobIterator { + it := &TransferJobIterator{} + req = proto.Clone(req).(*storagetransferpb.ListTransferJobsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*storagetransferpb.TransferJob, string, error) { + resp := &storagetransferpb.ListTransferJobsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/transferJobs") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetTransferJobs(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// PauseTransferOperation pauses a transfer operation. +func (c *restClient) PauseTransferOperation(ctx context.Context, req *storagetransferpb.PauseTransferOperationRequest, opts ...gax.CallOption) error { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:pause", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// ResumeTransferOperation resumes a transfer operation that is paused. +func (c *restClient) ResumeTransferOperation(ctx context.Context, req *storagetransferpb.ResumeTransferOperationRequest, opts ...gax.CallOption) error { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:resume", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// RunTransferJob attempts to start a new TransferOperation for the current TransferJob. A +// TransferJob has a maximum of one active TransferOperation. If this method +// is called while a TransferOperation is active, an error will be returned. +func (c *restClient) RunTransferJob(ctx context.Context, req *storagetransferpb.RunTransferJobRequest, opts ...gax.CallOption) (*RunTransferJobOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:run", req.GetJobName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "job_name", url.QueryEscape(req.GetJobName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &RunTransferJobOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteTransferJob deletes a transfer job. Deleting a transfer job sets its status to +// DELETED. +func (c *restClient) DeleteTransferJob(ctx context.Context, req *storagetransferpb.DeleteTransferJobRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetJobName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("projectId", fmt.Sprintf("%v", req.GetProjectId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "job_name", url.QueryEscape(req.GetJobName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// CreateAgentPool creates an agent pool resource. +func (c *restClient) CreateAgentPool(ctx context.Context, req *storagetransferpb.CreateAgentPoolRequest, opts ...gax.CallOption) (*storagetransferpb.AgentPool, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetAgentPool() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/projects/%v/agentPools", req.GetProjectId()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("agentPoolId", fmt.Sprintf("%v", req.GetAgentPoolId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "project_id", url.QueryEscape(req.GetProjectId()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateAgentPool[0:len((*c.CallOptions).CreateAgentPool):len((*c.CallOptions).CreateAgentPool)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &storagetransferpb.AgentPool{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateAgentPool updates an existing agent pool resource. +func (c *restClient) UpdateAgentPool(ctx context.Context, req *storagetransferpb.UpdateAgentPoolRequest, opts ...gax.CallOption) (*storagetransferpb.AgentPool, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetAgentPool() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetAgentPool().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "agent_pool.name", url.QueryEscape(req.GetAgentPool().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateAgentPool[0:len((*c.CallOptions).UpdateAgentPool):len((*c.CallOptions).UpdateAgentPool)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &storagetransferpb.AgentPool{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetAgentPool gets an agent pool. +func (c *restClient) GetAgentPool(ctx context.Context, req *storagetransferpb.GetAgentPoolRequest, opts ...gax.CallOption) (*storagetransferpb.AgentPool, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetAgentPool[0:len((*c.CallOptions).GetAgentPool):len((*c.CallOptions).GetAgentPool)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &storagetransferpb.AgentPool{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListAgentPools lists agent pools. +func (c *restClient) ListAgentPools(ctx context.Context, req *storagetransferpb.ListAgentPoolsRequest, opts ...gax.CallOption) *AgentPoolIterator { + it := &AgentPoolIterator{} + req = proto.Clone(req).(*storagetransferpb.ListAgentPoolsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*storagetransferpb.AgentPool, string, error) { + resp := &storagetransferpb.ListAgentPoolsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/projects/%v/agentPools", req.GetProjectId()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetAgentPools(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// DeleteAgentPool deletes an agent pool. +func (c *restClient) DeleteAgentPool(ctx context.Context, req *storagetransferpb.DeleteAgentPoolRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// CancelOperation cancels a transfer. Use +// the transferOperations.get +// method to check if the cancellation succeeded or if the operation +// completed despite the cancel request. +// +// When you cancel an operation, the currently running transfer is +// interrupted. For recurring transfer jobs, the next instance of the +// transfer job will still run. For example, if your job is configured +// to run every day at 1pm and you cancel Monday’s operation at 1:05pm, +// Monday’s transfer +// will stop. However, a transfer job will still be attempted on Tuesday. +// +// This applies only to currently running operations. If an operation is +// not currently running, cancel does nothing. +// +// When you cancel a job, the next job computes a delta of files and may +// repair any inconsistent state. For instance, if you run a job every +// day, and today’s job found 10 new files and transferred five files +// before you canceled the job, tomorrow’s transfer operation will +// compute a new delta with the five files that were not copied today +// plus any new files discovered tomorrow. +func (c *restClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *restClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations lists transfer operations. Operations are ordered by their creation +// time in reverse chronological order. +func (c *restClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// RunTransferJobOperation manages a long-running operation from RunTransferJob. +type RunTransferJobOperation struct { + lro *longrunning.Operation + pollPath string +} + +// RunTransferJobOperation returns a new RunTransferJobOperation from a given name. +// The name must be that of a previously created RunTransferJobOperation, possibly from a different process. +func (c *gRPCClient) RunTransferJobOperation(name string) *RunTransferJobOperation { + return &RunTransferJobOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// RunTransferJobOperation returns a new RunTransferJobOperation from a given name. +// The name must be that of a previously created RunTransferJobOperation, possibly from a different process. +func (c *restClient) RunTransferJobOperation(name string) *RunTransferJobOperation { + override := fmt.Sprintf("/v1/%s", name) + return &RunTransferJobOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, } } @@ -991,6 +2353,7 @@ func (c *gRPCClient) RunTransferJobOperation(name string) *RunTransferJobOperati // // See documentation of Poll for error-handling information. func (op *RunTransferJobOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -1004,6 +2367,7 @@ func (op *RunTransferJobOperation) Wait(ctx context.Context, opts ...gax.CallOpt // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *RunTransferJobOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } diff --git a/storagetransfer/apiv1/storage_transfer_client_example_test.go b/storagetransfer/apiv1/storage_transfer_client_example_test.go index 53d4cb94b89a..d301930178af 100644 --- a/storagetransfer/apiv1/storage_transfer_client_example_test.go +++ b/storagetransfer/apiv1/storage_transfer_client_example_test.go @@ -42,6 +42,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := storagetransfer.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_GetGoogleServiceAccount() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/storagetransfer/apiv1/storagetransferpb/transfer.pb.go b/storagetransfer/apiv1/storagetransferpb/transfer.pb.go index 9519b30ac423..a8ca20ad65ac 100644 --- a/storagetransfer/apiv1/storagetransferpb/transfer.pb.go +++ b/storagetransfer/apiv1/storagetransferpb/transfer.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/storagetransfer/v1/transfer.proto package storagetransferpb @@ -364,9 +364,8 @@ type ListTransferJobsRequest struct { // Required. A list of query parameters specified as JSON text in the form of: // `{"projectId":"my_project_id", - // - // "jobNames":["jobid1","jobid2",...], - // "jobStatuses":["status1","status2",...]}` + // "jobNames":["jobid1","jobid2",...], + // "jobStatuses":["status1","status2",...]}` // // Since `jobNames` and `jobStatuses` support multiple values, their values // must be specified with array notation. `projectId` is required. @@ -668,9 +667,9 @@ type CreateAgentPoolRequest struct { // * Length of 128 characters or less. // * Not start with the string `goog`. // * Start with a lowercase ASCII character, followed by: - // - Zero or more: lowercase Latin alphabet characters, numerals, - // hyphens (`-`), periods (`.`), underscores (`_`), or tildes (`~`). - // - One or more numerals or lowercase ASCII characters. + // * Zero or more: lowercase Latin alphabet characters, numerals, + // hyphens (`-`), periods (`.`), underscores (`_`), or tildes (`~`). + // * One or more numerals or lowercase ASCII characters. // // As expressed by the regular expression: // `^(?!goog)[a-z]([a-z0-9-._~]*[a-z0-9])?$`. diff --git a/storagetransfer/apiv1/storagetransferpb/transfer_types.pb.go b/storagetransfer/apiv1/storagetransferpb/transfer_types.pb.go index cc9a6a09888b..8e8cf18590b5 100644 --- a/storagetransfer/apiv1/storagetransferpb/transfer_types.pb.go +++ b/storagetransfer/apiv1/storagetransferpb/transfer_types.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/storagetransfer/v1/transfer_types.proto package storagetransferpb @@ -1452,9 +1452,7 @@ type ObjectConditions struct { // "last modification time" are transferred only if the elapsed time // between the [start_time][google.storagetransfer.v1.TransferOperation.start_time] of the // `TransferOperation`and the "last modification time" of the object - // - // is less than the value of max_time_elapsed_since_last_modification`. - // + // is less than the value of max_time_elapsed_since_last_modification`. // Objects that do not have a "last modification time" are also transferred. MaxTimeElapsedSinceLastModification *durationpb.Duration `protobuf:"bytes,2,opt,name=max_time_elapsed_since_last_modification,json=maxTimeElapsedSinceLastModification,proto3" json:"max_time_elapsed_since_last_modification,omitempty"` // If you specify `include_prefixes`, Storage Transfer Service uses the items @@ -1466,18 +1464,18 @@ type ObjectConditions struct { // // The following are requirements of `include_prefixes`: // - // - Each include-prefix can contain any sequence of Unicode characters, to + // * Each include-prefix can contain any sequence of Unicode characters, to // a max length of 1024 bytes when UTF8-encoded, and must not contain // Carriage Return or Line Feed characters. Wildcard matching and regular // expression matching are not supported. // - // - Each include-prefix must omit the leading slash. For example, to + // * Each include-prefix must omit the leading slash. For example, to // include the object `s3://my-aws-bucket/logs/y=2015/requests.gz`, // specify the include-prefix as `logs/y=2015/requests.gz`. // - // - None of the include-prefix values can be empty, if specified. + // * None of the include-prefix values can be empty, if specified. // - // - Each include-prefix must include a distinct portion of the object + // * Each include-prefix must include a distinct portion of the object // namespace. No include-prefix may be a prefix of another // include-prefix. // @@ -1493,23 +1491,23 @@ type ObjectConditions struct { // // The following are requirements of `exclude_prefixes`: // - // - Each exclude-prefix can contain any sequence of Unicode characters, to + // * Each exclude-prefix can contain any sequence of Unicode characters, to // a max length of 1024 bytes when UTF8-encoded, and must not contain // Carriage Return or Line Feed characters. Wildcard matching and regular // expression matching are not supported. // - // - Each exclude-prefix must omit the leading slash. For example, to + // * Each exclude-prefix must omit the leading slash. For example, to // exclude the object `s3://my-aws-bucket/logs/y=2015/requests.gz`, // specify the exclude-prefix as `logs/y=2015/requests.gz`. // - // - None of the exclude-prefix values can be empty, if specified. + // * None of the exclude-prefix values can be empty, if specified. // - // - Each exclude-prefix must exclude a distinct portion of the object + // * Each exclude-prefix must exclude a distinct portion of the object // namespace. No exclude-prefix may be a prefix of another // exclude-prefix. // - // - If [include_prefixes][google.storagetransfer.v1.ObjectConditions.include_prefixes] is specified, then each exclude-prefix must - // start with the value of a path explicitly included by `include_prefixes`. + // * If [include_prefixes][google.storagetransfer.v1.ObjectConditions.include_prefixes] is specified, then each exclude-prefix must + // start with the value of a path explicitly included by `include_prefixes`. // // The max size of `exclude_prefixes` is 1000. // @@ -2024,7 +2022,6 @@ type AwsS3CompatibleData struct { // providers. When not specified, S3CompatibleMetadata is used by default. // // Types that are assignable to DataProvider: - // // *AwsS3CompatibleData_S3Metadata DataProvider isAwsS3CompatibleData_DataProvider `protobuf_oneof:"data_provider"` } @@ -2382,14 +2379,12 @@ type TransferSpec struct { // The write sink for the data. // // Types that are assignable to DataSink: - // // *TransferSpec_GcsDataSink // *TransferSpec_PosixDataSink DataSink isTransferSpec_DataSink `protobuf_oneof:"data_sink"` // The read source of the data. // // Types that are assignable to DataSource: - // // *TransferSpec_GcsDataSource // *TransferSpec_AwsS3DataSource // *TransferSpec_HttpDataSource @@ -2402,7 +2397,6 @@ type TransferSpec struct { // transfer data through. This is validated on TransferJob creation. // // Types that are assignable to IntermediateDataLocation: - // // *TransferSpec_GcsIntermediateDataLocation IntermediateDataLocation isTransferSpec_IntermediateDataLocation `protobuf_oneof:"intermediate_data_location"` // Only objects that satisfy these object conditions are included in the set @@ -2869,9 +2863,9 @@ type Schedule struct { // The last day a transfer runs. Date boundaries are determined relative to // UTC time. A job runs once per 24 hours within the following guidelines: // - // - If `schedule_end_date` and [schedule_start_date][google.storagetransfer.v1.Schedule.schedule_start_date] are the same and in + // * If `schedule_end_date` and [schedule_start_date][google.storagetransfer.v1.Schedule.schedule_start_date] are the same and in // the future relative to UTC, the transfer is executed only one time. - // - If `schedule_end_date` is later than `schedule_start_date` and + // * If `schedule_end_date` is later than `schedule_start_date` and // `schedule_end_date` is in the future relative to UTC, the job runs each // day at [start_time_of_day][google.storagetransfer.v1.Schedule.start_time_of_day] through `schedule_end_date`. ScheduleEndDate *date.Date `protobuf:"bytes,2,opt,name=schedule_end_date,json=scheduleEndDate,proto3" json:"schedule_end_date,omitempty"` @@ -2880,14 +2874,14 @@ type Schedule struct { // // If `start_time_of_day` is not specified: // - // - One-time transfers run immediately. - // - Recurring transfers run immediately, and each day at midnight UTC, + // * One-time transfers run immediately. + // * Recurring transfers run immediately, and each day at midnight UTC, // through [schedule_end_date][google.storagetransfer.v1.Schedule.schedule_end_date]. // // If `start_time_of_day` is specified: // - // - One-time transfers run at the specified time. - // - Recurring transfers run at the specified time each day, through + // * One-time transfers run at the specified time. + // * Recurring transfers run at the specified time each day, through // `schedule_end_date`. StartTimeOfDay *timeofday.TimeOfDay `protobuf:"bytes,3,opt,name=start_time_of_day,json=startTimeOfDay,proto3" json:"start_time_of_day,omitempty"` // The time in UTC that no further transfer operations are scheduled. Combined @@ -2897,10 +2891,10 @@ type Schedule struct { // [schedule_start_date][google.storagetransfer.v1.Schedule.schedule_start_date] and [start_time_of_day][google.storagetransfer.v1.Schedule.start_time_of_day], and is subject to the // following: // - // - If `end_time_of_day` is not set and `schedule_end_date` is set, then + // * If `end_time_of_day` is not set and `schedule_end_date` is set, then // a default value of `23:59:59` is used for `end_time_of_day`. // - // - If `end_time_of_day` is set and `schedule_end_date` is not set, then + // * If `end_time_of_day` is set and `schedule_end_date` is not set, then // [INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT] is returned. EndTimeOfDay *timeofday.TimeOfDay `protobuf:"bytes,4,opt,name=end_time_of_day,json=endTimeOfDay,proto3" json:"end_time_of_day,omitempty"` // Interval between the start of each scheduled TransferOperation. If @@ -3275,7 +3269,7 @@ func (x *ErrorSummary) GetErrorCode() code.Code { if x != nil { return x.ErrorCode } - return code.Code_OK + return code.Code(0) } func (x *ErrorSummary) GetErrorCount() int64 { diff --git a/talent/apiv4/company_client.go b/talent/apiv4/company_client.go index 885d3fb7196d..6ae9e75486cf 100644 --- a/talent/apiv4/company_client.go +++ b/talent/apiv4/company_client.go @@ -17,22 +17,28 @@ package talent import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" talentpb "cloud.google.com/go/talent/apiv4/talentpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -104,6 +110,47 @@ func defaultCompanyCallOptions() *CompanyCallOptions { } } +func defaultCompanyRESTCallOptions() *CompanyCallOptions { + return &CompanyCallOptions{ + CreateCompany: []gax.CallOption{}, + GetCompany: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + UpdateCompany: []gax.CallOption{}, + DeleteCompany: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + ListCompanies: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + GetOperation: []gax.CallOption{}, + } +} + // internalCompanyClient is an interface that defines the methods available from Cloud Talent Solution API. type internalCompanyClient interface { Close() error @@ -267,6 +314,74 @@ func (c *companyGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type companyRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing CompanyClient + CallOptions **CompanyCallOptions +} + +// NewCompanyRESTClient creates a new company service rest client. +// +// A service that handles company management, including CRUD and enumeration. +func NewCompanyRESTClient(ctx context.Context, opts ...option.ClientOption) (*CompanyClient, error) { + clientOpts := append(defaultCompanyRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultCompanyRESTCallOptions() + c := &companyRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &CompanyClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultCompanyRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://jobs.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://jobs.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://jobs.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *companyRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *companyRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *companyRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *companyGRPCClient) CreateCompany(ctx context.Context, req *talentpb.CreateCompanyRequest, opts ...gax.CallOption) (*talentpb.Company, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) @@ -413,6 +528,391 @@ func (c *companyGRPCClient) GetOperation(ctx context.Context, req *longrunningpb return resp, nil } +// CreateCompany creates a new company entity. +func (c *companyRESTClient) CreateCompany(ctx context.Context, req *talentpb.CreateCompanyRequest, opts ...gax.CallOption) (*talentpb.Company, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetCompany() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v4/%v/companies", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateCompany[0:len((*c.CallOptions).CreateCompany):len((*c.CallOptions).CreateCompany)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &talentpb.Company{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetCompany retrieves specified company. +func (c *companyRESTClient) GetCompany(ctx context.Context, req *talentpb.GetCompanyRequest, opts ...gax.CallOption) (*talentpb.Company, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v4/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetCompany[0:len((*c.CallOptions).GetCompany):len((*c.CallOptions).GetCompany)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &talentpb.Company{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateCompany updates specified company. +func (c *companyRESTClient) UpdateCompany(ctx context.Context, req *talentpb.UpdateCompanyRequest, opts ...gax.CallOption) (*talentpb.Company, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetCompany() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v4/%v", req.GetCompany().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "company.name", url.QueryEscape(req.GetCompany().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateCompany[0:len((*c.CallOptions).UpdateCompany):len((*c.CallOptions).UpdateCompany)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &talentpb.Company{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteCompany deletes specified company. +// Prerequisite: The company has no jobs associated with it. +func (c *companyRESTClient) DeleteCompany(ctx context.Context, req *talentpb.DeleteCompanyRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v4/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// ListCompanies lists all companies associated with the project. +func (c *companyRESTClient) ListCompanies(ctx context.Context, req *talentpb.ListCompaniesRequest, opts ...gax.CallOption) *CompanyIterator { + it := &CompanyIterator{} + req = proto.Clone(req).(*talentpb.ListCompaniesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*talentpb.Company, string, error) { + resp := &talentpb.ListCompaniesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v4/%v/companies", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + if req.GetRequireOpenJobs() { + params.Add("requireOpenJobs", fmt.Sprintf("%v", req.GetRequireOpenJobs())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetCompanies(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *companyRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v4/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + // CompanyIterator manages a stream of *talentpb.Company. type CompanyIterator struct { items []*talentpb.Company diff --git a/talent/apiv4/company_client_example_test.go b/talent/apiv4/company_client_example_test.go index bc40f6758263..bcf04bf60a73 100644 --- a/talent/apiv4/company_client_example_test.go +++ b/talent/apiv4/company_client_example_test.go @@ -42,6 +42,23 @@ func ExampleNewCompanyClient() { _ = c } +func ExampleNewCompanyRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := talent.NewCompanyRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleCompanyClient_CreateCompany() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/talent/apiv4/completion_client.go b/talent/apiv4/completion_client.go index 90da2801a52d..c1f99509ab9f 100644 --- a/talent/apiv4/completion_client.go +++ b/talent/apiv4/completion_client.go @@ -19,19 +19,24 @@ package talent import ( "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" talentpb "cloud.google.com/go/talent/apiv4/talentpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" ) var newCompletionClientHook clientHook @@ -72,6 +77,23 @@ func defaultCompletionCallOptions() *CompletionCallOptions { } } +func defaultCompletionRESTCallOptions() *CompletionCallOptions { + return &CompletionCallOptions{ + CompleteQuery: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + GetOperation: []gax.CallOption{}, + } +} + // internalCompletionClient is an interface that defines the methods available from Cloud Talent Solution API. type internalCompletionClient interface { Close() error @@ -211,6 +233,74 @@ func (c *completionGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type completionRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing CompletionClient + CallOptions **CompletionCallOptions +} + +// NewCompletionRESTClient creates a new completion rest client. +// +// A service handles auto completion. +func NewCompletionRESTClient(ctx context.Context, opts ...option.ClientOption) (*CompletionClient, error) { + clientOpts := append(defaultCompletionRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultCompletionRESTCallOptions() + c := &completionRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &CompletionClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultCompletionRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://jobs.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://jobs.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://jobs.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *completionRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *completionRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *completionRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *completionGRPCClient) CompleteQuery(ctx context.Context, req *talentpb.CompleteQueryRequest, opts ...gax.CallOption) (*talentpb.CompleteQueryResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) @@ -249,3 +339,136 @@ func (c *completionGRPCClient) GetOperation(ctx context.Context, req *longrunnin } return resp, nil } + +// CompleteQuery completes the specified prefix with keyword suggestions. +// Intended for use by a job search auto-complete search box. +func (c *completionRESTClient) CompleteQuery(ctx context.Context, req *talentpb.CompleteQueryRequest, opts ...gax.CallOption) (*talentpb.CompleteQueryResponse, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v4/%v:completeQuery", req.GetTenant()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetCompany() != "" { + params.Add("company", fmt.Sprintf("%v", req.GetCompany())) + } + if items := req.GetLanguageCodes(); len(items) > 0 { + for _, item := range items { + params.Add("languageCodes", fmt.Sprintf("%v", item)) + } + } + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + params.Add("query", fmt.Sprintf("%v", req.GetQuery())) + if req.GetScope() != 0 { + params.Add("scope", fmt.Sprintf("%v", req.GetScope())) + } + if req.GetType() != 0 { + params.Add("type", fmt.Sprintf("%v", req.GetType())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "tenant", url.QueryEscape(req.GetTenant()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CompleteQuery[0:len((*c.CallOptions).CompleteQuery):len((*c.CallOptions).CompleteQuery)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &talentpb.CompleteQueryResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *completionRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v4/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} diff --git a/talent/apiv4/completion_client_example_test.go b/talent/apiv4/completion_client_example_test.go index 4ca642577bf5..5e6a96567792 100644 --- a/talent/apiv4/completion_client_example_test.go +++ b/talent/apiv4/completion_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewCompletionClient() { _ = c } +func ExampleNewCompletionRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := talent.NewCompletionRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleCompletionClient_CompleteQuery() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/talent/apiv4/doc.go b/talent/apiv4/doc.go index 3758a2ab53db..d62e23ec6116 100644 --- a/talent/apiv4/doc.go +++ b/talent/apiv4/doc.go @@ -81,6 +81,8 @@ package talent // import "cloud.google.com/go/talent/apiv4" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -170,3 +172,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/talent/apiv4/event_client.go b/talent/apiv4/event_client.go index f4c6dfad6b05..dde3ed78a8c1 100644 --- a/talent/apiv4/event_client.go +++ b/talent/apiv4/event_client.go @@ -17,20 +17,26 @@ package talent import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" talentpb "cloud.google.com/go/talent/apiv4/talentpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" ) var newEventClientHook clientHook @@ -60,6 +66,13 @@ func defaultEventCallOptions() *EventCallOptions { } } +func defaultEventRESTCallOptions() *EventCallOptions { + return &EventCallOptions{ + CreateClientEvent: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + } +} + // internalEventClient is an interface that defines the methods available from Cloud Talent Solution API. type internalEventClient interface { Close() error @@ -204,6 +217,74 @@ func (c *eventGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type eventRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing EventClient + CallOptions **EventCallOptions +} + +// NewEventRESTClient creates a new event service rest client. +// +// A service handles client event report. +func NewEventRESTClient(ctx context.Context, opts ...option.ClientOption) (*EventClient, error) { + clientOpts := append(defaultEventRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultEventRESTCallOptions() + c := &eventRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &EventClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultEventRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://jobs.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://jobs.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://jobs.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *eventRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *eventRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *eventRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *eventGRPCClient) CreateClientEvent(ctx context.Context, req *talentpb.CreateClientEventRequest, opts ...gax.CallOption) (*talentpb.ClientEvent, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) @@ -242,3 +323,132 @@ func (c *eventGRPCClient) GetOperation(ctx context.Context, req *longrunningpb.G } return resp, nil } + +// CreateClientEvent report events issued when end user interacts with customer’s application +// that uses Cloud Talent Solution. You may inspect the created events in +// self service +// tools (at https://console.cloud.google.com/talent-solution/overview). +// Learn +// more (at https://cloud.google.com/talent-solution/docs/management-tools) +// about self service tools. +func (c *eventRESTClient) CreateClientEvent(ctx context.Context, req *talentpb.CreateClientEventRequest, opts ...gax.CallOption) (*talentpb.ClientEvent, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetClientEvent() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v4/%v/clientEvents", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateClientEvent[0:len((*c.CallOptions).CreateClientEvent):len((*c.CallOptions).CreateClientEvent)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &talentpb.ClientEvent{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *eventRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v4/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} diff --git a/talent/apiv4/event_client_example_test.go b/talent/apiv4/event_client_example_test.go index 77deeb8cb4c6..a7d2080dfb93 100644 --- a/talent/apiv4/event_client_example_test.go +++ b/talent/apiv4/event_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewEventClient() { _ = c } +func ExampleNewEventRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := talent.NewEventRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleEventClient_CreateClientEvent() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/talent/apiv4/gapic_metadata.json b/talent/apiv4/gapic_metadata.json index ca0a51cbd36a..aec1c3b2cc8f 100644 --- a/talent/apiv4/gapic_metadata.json +++ b/talent/apiv4/gapic_metadata.json @@ -41,6 +41,41 @@ ] } } + }, + "rest": { + "libraryClient": "CompanyClient", + "rpcs": { + "CreateCompany": { + "methods": [ + "CreateCompany" + ] + }, + "DeleteCompany": { + "methods": [ + "DeleteCompany" + ] + }, + "GetCompany": { + "methods": [ + "GetCompany" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ListCompanies": { + "methods": [ + "ListCompanies" + ] + }, + "UpdateCompany": { + "methods": [ + "UpdateCompany" + ] + } + } } } }, @@ -60,6 +95,21 @@ ] } } + }, + "rest": { + "libraryClient": "CompletionClient", + "rpcs": { + "CompleteQuery": { + "methods": [ + "CompleteQuery" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + } + } } } }, @@ -79,6 +129,21 @@ ] } } + }, + "rest": { + "libraryClient": "EventClient", + "rpcs": { + "CreateClientEvent": { + "methods": [ + "CreateClientEvent" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + } + } } } }, @@ -143,6 +208,66 @@ ] } } + }, + "rest": { + "libraryClient": "JobClient", + "rpcs": { + "BatchCreateJobs": { + "methods": [ + "BatchCreateJobs" + ] + }, + "BatchDeleteJobs": { + "methods": [ + "BatchDeleteJobs" + ] + }, + "BatchUpdateJobs": { + "methods": [ + "BatchUpdateJobs" + ] + }, + "CreateJob": { + "methods": [ + "CreateJob" + ] + }, + "DeleteJob": { + "methods": [ + "DeleteJob" + ] + }, + "GetJob": { + "methods": [ + "GetJob" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ListJobs": { + "methods": [ + "ListJobs" + ] + }, + "SearchJobs": { + "methods": [ + "SearchJobs" + ] + }, + "SearchJobsForAlert": { + "methods": [ + "SearchJobsForAlert" + ] + }, + "UpdateJob": { + "methods": [ + "UpdateJob" + ] + } + } } } }, @@ -182,6 +307,41 @@ ] } } + }, + "rest": { + "libraryClient": "TenantClient", + "rpcs": { + "CreateTenant": { + "methods": [ + "CreateTenant" + ] + }, + "DeleteTenant": { + "methods": [ + "DeleteTenant" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "GetTenant": { + "methods": [ + "GetTenant" + ] + }, + "ListTenants": { + "methods": [ + "ListTenants" + ] + }, + "UpdateTenant": { + "methods": [ + "UpdateTenant" + ] + } + } } } } diff --git a/talent/apiv4/job_client.go b/talent/apiv4/job_client.go index 4b6cd456dab1..e33dc67a0341 100644 --- a/talent/apiv4/job_client.go +++ b/talent/apiv4/job_client.go @@ -17,9 +17,12 @@ package talent import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,14 +30,17 @@ import ( lroauto "cloud.google.com/go/longrunning/autogen" talentpb "cloud.google.com/go/talent/apiv4/talentpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -116,6 +122,52 @@ func defaultJobCallOptions() *JobCallOptions { } } +func defaultJobRESTCallOptions() *JobCallOptions { + return &JobCallOptions{ + CreateJob: []gax.CallOption{}, + BatchCreateJobs: []gax.CallOption{}, + GetJob: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + UpdateJob: []gax.CallOption{}, + BatchUpdateJobs: []gax.CallOption{}, + DeleteJob: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + BatchDeleteJobs: []gax.CallOption{}, + ListJobs: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + SearchJobs: []gax.CallOption{}, + SearchJobsForAlert: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + } +} + // internalJobClient is an interface that defines the methods available from Cloud Talent Solution API. type internalJobClient interface { Close() error @@ -373,6 +425,89 @@ func (c *jobGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type jobRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing JobClient + CallOptions **JobCallOptions +} + +// NewJobRESTClient creates a new job service rest client. +// +// A service handles job management, including job CRUD, enumeration and search. +func NewJobRESTClient(ctx context.Context, opts ...option.ClientOption) (*JobClient, error) { + clientOpts := append(defaultJobRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultJobRESTCallOptions() + c := &jobRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &JobClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultJobRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://jobs.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://jobs.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://jobs.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *jobRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *jobRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *jobRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *jobGRPCClient) CreateJob(ctx context.Context, req *talentpb.CreateJobRequest, opts ...gax.CallOption) (*talentpb.Job, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) @@ -635,148 +770,915 @@ func (c *jobGRPCClient) GetOperation(ctx context.Context, req *longrunningpb.Get return resp, nil } -// BatchCreateJobsOperation manages a long-running operation from BatchCreateJobs. -type BatchCreateJobsOperation struct { - lro *longrunning.Operation -} - -// BatchCreateJobsOperation returns a new BatchCreateJobsOperation from a given name. -// The name must be that of a previously created BatchCreateJobsOperation, possibly from a different process. -func (c *jobGRPCClient) BatchCreateJobsOperation(name string) *BatchCreateJobsOperation { - return &BatchCreateJobsOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} - -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// CreateJob creates a new job. // -// See documentation of Poll for error-handling information. -func (op *BatchCreateJobsOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*talentpb.BatchCreateJobsResponse, error) { - var resp talentpb.BatchCreateJobsResponse - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { +// Typically, the job becomes searchable within 10 seconds, but it may take +// up to 5 minutes. +func (c *jobRESTClient) CreateJob(ctx context.Context, req *talentpb.CreateJobRequest, opts ...gax.CallOption) (*talentpb.Job, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetJob() + jsonReq, err := m.Marshal(body) + if err != nil { return nil, err } - return &resp, nil -} -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *BatchCreateJobsOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*talentpb.BatchCreateJobsResponse, error) { - var resp talentpb.BatchCreateJobsResponse - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - if !op.Done() { - return nil, nil - } - return &resp, nil -} + baseUrl.Path += fmt.Sprintf("/v4/%v/jobs", req.GetParent()) -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *BatchCreateJobsOperation) Metadata() (*talentpb.BatchOperationMetadata, error) { - var meta talentpb.BatchOperationMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { - return nil, err - } - return &meta, nil -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") -// Done reports whether the long-running operation has completed. -func (op *BatchCreateJobsOperation) Done() bool { - return op.lro.Done() -} + baseUrl.RawQuery = params.Encode() -// 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 *BatchCreateJobsOperation) Name() string { - return op.lro.Name() -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) -// BatchDeleteJobsOperation manages a long-running operation from BatchDeleteJobs. -type BatchDeleteJobsOperation struct { - lro *longrunning.Operation -} + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateJob[0:len((*c.CallOptions).CreateJob):len((*c.CallOptions).CreateJob)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &talentpb.Job{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers -// BatchDeleteJobsOperation returns a new BatchDeleteJobsOperation from a given name. -// The name must be that of a previously created BatchDeleteJobsOperation, possibly from a different process. -func (c *jobGRPCClient) BatchDeleteJobsOperation(name string) *BatchDeleteJobsOperation { - return &BatchDeleteJobsOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e } + return resp, nil } -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *BatchDeleteJobsOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*talentpb.BatchDeleteJobsResponse, error) { - var resp talentpb.BatchDeleteJobsResponse - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { +// BatchCreateJobs begins executing a batch create jobs operation. +func (c *jobRESTClient) BatchCreateJobs(ctx context.Context, req *talentpb.BatchCreateJobsRequest, opts ...gax.CallOption) (*BatchCreateJobsOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { return nil, err } - return &resp, nil -} -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *BatchDeleteJobsOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*talentpb.BatchDeleteJobsResponse, error) { - var resp talentpb.BatchDeleteJobsResponse - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - if !op.Done() { - return nil, nil + baseUrl.Path += fmt.Sprintf("/v4/%v/jobs:batchCreate", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e } - return &resp, nil + + override := fmt.Sprintf("/v4/%s", resp.GetName()) + return &BatchCreateJobsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil } -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *BatchDeleteJobsOperation) Metadata() (*talentpb.BatchOperationMetadata, error) { - var meta talentpb.BatchOperationMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { +// GetJob retrieves the specified job, whose status is OPEN or recently EXPIRED +// within the last 90 days. +func (c *jobRESTClient) GetJob(ctx context.Context, req *talentpb.GetJobRequest, opts ...gax.CallOption) (*talentpb.Job, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - return &meta, nil -} + baseUrl.Path += fmt.Sprintf("/v4/%v", req.GetName()) -// Done reports whether the long-running operation has completed. -func (op *BatchDeleteJobsOperation) Done() bool { - return op.lro.Done() -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") -// 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 *BatchDeleteJobsOperation) Name() string { - return op.lro.Name() -} + baseUrl.RawQuery = params.Encode() -// BatchUpdateJobsOperation manages a long-running operation from BatchUpdateJobs. -type BatchUpdateJobsOperation struct { - lro *longrunning.Operation -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetJob[0:len((*c.CallOptions).GetJob):len((*c.CallOptions).GetJob)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &talentpb.Job{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateJob updates specified job. +// +// Typically, updated contents become visible in search results within 10 +// seconds, but it may take up to 5 minutes. +func (c *jobRESTClient) UpdateJob(ctx context.Context, req *talentpb.UpdateJobRequest, opts ...gax.CallOption) (*talentpb.Job, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetJob() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v4/%v", req.GetJob().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "job.name", url.QueryEscape(req.GetJob().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateJob[0:len((*c.CallOptions).UpdateJob):len((*c.CallOptions).UpdateJob)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &talentpb.Job{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// BatchUpdateJobs begins executing a batch update jobs operation. +func (c *jobRESTClient) BatchUpdateJobs(ctx context.Context, req *talentpb.BatchUpdateJobsRequest, opts ...gax.CallOption) (*BatchUpdateJobsOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v4/%v/jobs:batchUpdate", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v4/%s", resp.GetName()) + return &BatchUpdateJobsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteJob deletes the specified job. +// +// Typically, the job becomes unsearchable within 10 seconds, but it may take +// up to 5 minutes. +func (c *jobRESTClient) DeleteJob(ctx context.Context, req *talentpb.DeleteJobRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v4/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// BatchDeleteJobs begins executing a batch delete jobs operation. +func (c *jobRESTClient) BatchDeleteJobs(ctx context.Context, req *talentpb.BatchDeleteJobsRequest, opts ...gax.CallOption) (*BatchDeleteJobsOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v4/%v/jobs:batchDelete", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v4/%s", resp.GetName()) + return &BatchDeleteJobsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListJobs lists jobs by filter. +func (c *jobRESTClient) ListJobs(ctx context.Context, req *talentpb.ListJobsRequest, opts ...gax.CallOption) *JobIterator { + it := &JobIterator{} + req = proto.Clone(req).(*talentpb.ListJobsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*talentpb.Job, string, error) { + resp := &talentpb.ListJobsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v4/%v/jobs", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + if req.GetJobView() != 0 { + params.Add("jobView", fmt.Sprintf("%v", req.GetJobView())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetJobs(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// SearchJobs searches for jobs using the provided SearchJobsRequest. +// +// This call constrains the visibility of jobs +// present in the database, and only returns jobs that the caller has +// permission to search against. +func (c *jobRESTClient) SearchJobs(ctx context.Context, req *talentpb.SearchJobsRequest, opts ...gax.CallOption) (*talentpb.SearchJobsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v4/%v/jobs:search", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SearchJobs[0:len((*c.CallOptions).SearchJobs):len((*c.CallOptions).SearchJobs)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &talentpb.SearchJobsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SearchJobsForAlert searches for jobs using the provided SearchJobsRequest. +// +// This API call is intended for the use case of targeting passive job +// seekers (for example, job seekers who have signed up to receive email +// alerts about potential job opportunities), it has different algorithmic +// adjustments that are designed to specifically target passive job seekers. +// +// This call constrains the visibility of jobs +// present in the database, and only returns jobs the caller has +// permission to search against. +func (c *jobRESTClient) SearchJobsForAlert(ctx context.Context, req *talentpb.SearchJobsRequest, opts ...gax.CallOption) (*talentpb.SearchJobsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v4/%v/jobs:searchForAlert", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SearchJobsForAlert[0:len((*c.CallOptions).SearchJobsForAlert):len((*c.CallOptions).SearchJobsForAlert)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &talentpb.SearchJobsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *jobRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v4/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// BatchCreateJobsOperation manages a long-running operation from BatchCreateJobs. +type BatchCreateJobsOperation struct { + lro *longrunning.Operation + pollPath string +} + +// BatchCreateJobsOperation returns a new BatchCreateJobsOperation from a given name. +// The name must be that of a previously created BatchCreateJobsOperation, possibly from a different process. +func (c *jobGRPCClient) BatchCreateJobsOperation(name string) *BatchCreateJobsOperation { + return &BatchCreateJobsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// BatchCreateJobsOperation returns a new BatchCreateJobsOperation from a given name. +// The name must be that of a previously created BatchCreateJobsOperation, possibly from a different process. +func (c *jobRESTClient) BatchCreateJobsOperation(name string) *BatchCreateJobsOperation { + override := fmt.Sprintf("/v4/%s", name) + return &BatchCreateJobsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *BatchCreateJobsOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*talentpb.BatchCreateJobsResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp talentpb.BatchCreateJobsResponse + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *BatchCreateJobsOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*talentpb.BatchCreateJobsResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp talentpb.BatchCreateJobsResponse + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *BatchCreateJobsOperation) Metadata() (*talentpb.BatchOperationMetadata, error) { + var meta talentpb.BatchOperationMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *BatchCreateJobsOperation) Done() bool { + return op.lro.Done() +} + +// 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 *BatchCreateJobsOperation) Name() string { + return op.lro.Name() +} + +// BatchDeleteJobsOperation manages a long-running operation from BatchDeleteJobs. +type BatchDeleteJobsOperation struct { + lro *longrunning.Operation + pollPath string +} + +// BatchDeleteJobsOperation returns a new BatchDeleteJobsOperation from a given name. +// The name must be that of a previously created BatchDeleteJobsOperation, possibly from a different process. +func (c *jobGRPCClient) BatchDeleteJobsOperation(name string) *BatchDeleteJobsOperation { + return &BatchDeleteJobsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// BatchDeleteJobsOperation returns a new BatchDeleteJobsOperation from a given name. +// The name must be that of a previously created BatchDeleteJobsOperation, possibly from a different process. +func (c *jobRESTClient) BatchDeleteJobsOperation(name string) *BatchDeleteJobsOperation { + override := fmt.Sprintf("/v4/%s", name) + return &BatchDeleteJobsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *BatchDeleteJobsOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*talentpb.BatchDeleteJobsResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp talentpb.BatchDeleteJobsResponse + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *BatchDeleteJobsOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*talentpb.BatchDeleteJobsResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp talentpb.BatchDeleteJobsResponse + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *BatchDeleteJobsOperation) Metadata() (*talentpb.BatchOperationMetadata, error) { + var meta talentpb.BatchOperationMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *BatchDeleteJobsOperation) Done() bool { + return op.lro.Done() +} + +// 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 *BatchDeleteJobsOperation) Name() string { + return op.lro.Name() +} + +// BatchUpdateJobsOperation manages a long-running operation from BatchUpdateJobs. +type BatchUpdateJobsOperation struct { + lro *longrunning.Operation + pollPath string +} // BatchUpdateJobsOperation returns a new BatchUpdateJobsOperation from a given name. // The name must be that of a previously created BatchUpdateJobsOperation, possibly from a different process. @@ -786,10 +1688,21 @@ func (c *jobGRPCClient) BatchUpdateJobsOperation(name string) *BatchUpdateJobsOp } } +// BatchUpdateJobsOperation returns a new BatchUpdateJobsOperation from a given name. +// The name must be that of a previously created BatchUpdateJobsOperation, possibly from a different process. +func (c *jobRESTClient) BatchUpdateJobsOperation(name string) *BatchUpdateJobsOperation { + override := fmt.Sprintf("/v4/%s", name) + return &BatchUpdateJobsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *BatchUpdateJobsOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*talentpb.BatchUpdateJobsResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp talentpb.BatchUpdateJobsResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -807,6 +1720,7 @@ func (op *BatchUpdateJobsOperation) Wait(ctx context.Context, opts ...gax.CallOp // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *BatchUpdateJobsOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*talentpb.BatchUpdateJobsResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp talentpb.BatchUpdateJobsResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/talent/apiv4/job_client_example_test.go b/talent/apiv4/job_client_example_test.go index 10845ff741db..f7a5aa6a89dc 100644 --- a/talent/apiv4/job_client_example_test.go +++ b/talent/apiv4/job_client_example_test.go @@ -42,6 +42,23 @@ func ExampleNewJobClient() { _ = c } +func ExampleNewJobRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := talent.NewJobRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleJobClient_CreateJob() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/talent/apiv4/talentpb/common.pb.go b/talent/apiv4/talentpb/common.pb.go index f6572e8d3de7..71455cb56ce9 100644 --- a/talent/apiv4/talentpb/common.pb.go +++ b/talent/apiv4/talentpb/common.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/talent/v4/common.proto package talentpb @@ -2078,7 +2078,6 @@ type CompensationInfo_CompensationEntry struct { // Compensation amount. It could be a fixed amount or a floating range. // // Types that are assignable to CompensationAmount: - // // *CompensationInfo_CompensationEntry_Amount // *CompensationInfo_CompensationEntry_Range CompensationAmount isCompensationInfo_CompensationEntry_CompensationAmount `protobuf_oneof:"compensation_amount"` diff --git a/talent/apiv4/talentpb/company.pb.go b/talent/apiv4/talentpb/company.pb.go index e1901aba6343..aca054e81be9 100644 --- a/talent/apiv4/talentpb/company.pb.go +++ b/talent/apiv4/talentpb/company.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/talent/v4/company.proto package talentpb diff --git a/talent/apiv4/talentpb/company_service.pb.go b/talent/apiv4/talentpb/company_service.pb.go index 8d9961bc6f53..c6bcc99ed21a 100644 --- a/talent/apiv4/talentpb/company_service.pb.go +++ b/talent/apiv4/talentpb/company_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/talent/v4/company_service.proto package talentpb diff --git a/talent/apiv4/talentpb/completion_service.pb.go b/talent/apiv4/talentpb/completion_service.pb.go index d612bc3487d4..defb666d25ba 100644 --- a/talent/apiv4/talentpb/completion_service.pb.go +++ b/talent/apiv4/talentpb/completion_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/talent/v4/completion_service.proto package talentpb diff --git a/talent/apiv4/talentpb/event.pb.go b/talent/apiv4/talentpb/event.pb.go index 9c8ed4a97547..e94c73201e81 100644 --- a/talent/apiv4/talentpb/event.pb.go +++ b/talent/apiv4/talentpb/event.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/talent/v4/event.proto package talentpb @@ -209,7 +209,6 @@ type ClientEvent struct { // The detail information of a specific event type. // // Types that are assignable to Event: - // // *ClientEvent_JobEvent Event isClientEvent_Event `protobuf_oneof:"event"` // Notes about the event provided by recruiters or other users, for example, diff --git a/talent/apiv4/talentpb/event_service.pb.go b/talent/apiv4/talentpb/event_service.pb.go index 0c464fa7f6e9..40d5c1fece4b 100644 --- a/talent/apiv4/talentpb/event_service.pb.go +++ b/talent/apiv4/talentpb/event_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/talent/v4/event_service.proto package talentpb diff --git a/talent/apiv4/talentpb/filters.pb.go b/talent/apiv4/talentpb/filters.pb.go index 145edf059e8e..11f904b03a3c 100644 --- a/talent/apiv4/talentpb/filters.pb.go +++ b/talent/apiv4/talentpb/filters.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/talent/v4/filters.proto package talentpb @@ -288,13 +288,12 @@ type JobQuery struct { // categories are searched against. JobCategories []JobCategory `protobuf:"varint,4,rep,packed,name=job_categories,json=jobCategories,proto3,enum=google.cloud.talent.v4.JobCategory" json:"job_categories,omitempty"` // Allows filtering jobs by commute time with different travel methods (for - // - // example, driving or public transit). + // example, driving or public transit). // // Note: This only works when you specify a [CommuteMethod][google.cloud.talent.v4.CommuteMethod]. In this case, // [location_filters][google.cloud.talent.v4.JobQuery.location_filters] is ignored. // - // Currently we don't support sorting by commute time. + // Currently we don't support sorting by commute time. CommuteFilter *CommuteFilter `protobuf:"bytes,5,opt,name=commute_filter,json=commuteFilter,proto3" json:"commute_filter,omitempty"` // This filter specifies the company [Company.display_name][google.cloud.talent.v4.Company.display_name] // of the jobs to search against. The company name must match the value @@ -373,6 +372,7 @@ type JobQuery struct { // If a value isn't specified, the search results can contain jobs in any // locale. // + // // Language codes should be in BCP-47 format, such as "en-US" or "sr-Latn". // For more information, see // [Tags for Identifying Languages](https://tools.ietf.org/html/bcp47). @@ -740,7 +740,6 @@ type CommuteFilter struct { // Traffic factor to take into account while searching by commute. // // Types that are assignable to TrafficOption: - // // *CommuteFilter_RoadTraffic_ // *CommuteFilter_DepartureTime TrafficOption isCommuteFilter_TrafficOption `protobuf_oneof:"traffic_option"` diff --git a/talent/apiv4/talentpb/histogram.pb.go b/talent/apiv4/talentpb/histogram.pb.go index fe89decda7c5..e0f995fe473f 100644 --- a/talent/apiv4/talentpb/histogram.pb.go +++ b/talent/apiv4/talentpb/histogram.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/talent/v4/histogram.proto package talentpb @@ -100,11 +100,11 @@ type HistogramQueryResult struct { // // The key format is: // - // - (for string histogram) string values stored in the field. - // - (for named numeric bucket) name specified in `bucket()` function, like - // for `bucket(0, MAX, "non-negative")`, the key will be `non-negative`. - // - (for anonymous numeric bucket) range formatted as `-`, for - // example, `0-1000`, `MIN-0`, and `0-MAX`. + // * (for string histogram) string values stored in the field. + // * (for named numeric bucket) name specified in `bucket()` function, like + // for `bucket(0, MAX, "non-negative")`, the key will be `non-negative`. + // * (for anonymous numeric bucket) range formatted as `-`, for + // example, `0-1000`, `MIN-0`, and `0-MAX`. Histogram map[string]int64 `protobuf:"bytes,2,rep,name=histogram,proto3" json:"histogram,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"varint,2,opt,name=value,proto3"` } diff --git a/talent/apiv4/talentpb/job.pb.go b/talent/apiv4/talentpb/job.pb.go index 4addf8932202..19b4acbe43a2 100644 --- a/talent/apiv4/talentpb/job.pb.go +++ b/talent/apiv4/talentpb/job.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/talent/v4/job.proto package talentpb diff --git a/talent/apiv4/talentpb/job_service.pb.go b/talent/apiv4/talentpb/job_service.pb.go index 37a0a3c24791..2554cb8fd37c 100644 --- a/talent/apiv4/talentpb/job_service.pb.go +++ b/talent/apiv4/talentpb/job_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/talent/v4/job_service.proto package talentpb @@ -896,69 +896,68 @@ type SearchJobsRequest struct { // // Job histogram facets: // - // - company_display_name: histogram by [Job.company_display_name][google.cloud.talent.v4.Job.company_display_name]. - // - employment_type: histogram by [Job.employment_types][google.cloud.talent.v4.Job.employment_types], for example, - // "FULL_TIME", "PART_TIME". - // - company_size (DEPRECATED): histogram by [CompanySize][google.cloud.talent.v4.CompanySize], for example, - // + // * company_display_name: histogram by [Job.company_display_name][google.cloud.talent.v4.Job.company_display_name]. + // * employment_type: histogram by [Job.employment_types][google.cloud.talent.v4.Job.employment_types], for example, + // "FULL_TIME", "PART_TIME". + // * company_size (DEPRECATED): histogram by [CompanySize][google.cloud.talent.v4.CompanySize], for example, // "SMALL", "MEDIUM", "BIG". - // - publish_time_in_day: histogram by the [Job.posting_publish_time][google.cloud.talent.v4.Job.posting_publish_time] - // in days. - // Must specify list of numeric buckets in spec. - // - publish_time_in_month: histogram by the [Job.posting_publish_time][google.cloud.talent.v4.Job.posting_publish_time] - // in months. - // Must specify list of numeric buckets in spec. - // - publish_time_in_year: histogram by the [Job.posting_publish_time][google.cloud.talent.v4.Job.posting_publish_time] - // in years. - // Must specify list of numeric buckets in spec. - // - degree_types: histogram by the [Job.degree_types][google.cloud.talent.v4.Job.degree_types], for example, - // "Bachelors", "Masters". - // - job_level: histogram by the [Job.job_level][google.cloud.talent.v4.Job.job_level], for example, "Entry - // Level". - // - country: histogram by the country code of jobs, for example, "US", "FR". - // - admin1: histogram by the admin1 code of jobs, which is a global - // placeholder referring to the state, province, or the particular term a - // country uses to define the geographic structure below the country level, - // for example, "CA", "IL". - // - city: histogram by a combination of the "city name, admin1 code". For - // example, "Mountain View, CA", "New York, NY". - // - admin1_country: histogram by a combination of the "admin1 code, country", - // for example, "CA, US", "IL, US". - // - city_coordinate: histogram by the city center's GPS coordinates (latitude - // and longitude), for example, 37.4038522,-122.0987765. Since the - // coordinates of a city center can change, customers may need to refresh - // them periodically. - // - locale: histogram by the [Job.language_code][google.cloud.talent.v4.Job.language_code], for example, "en-US", - // "fr-FR". - // - language: histogram by the language subtag of the [Job.language_code][google.cloud.talent.v4.Job.language_code], - // for example, "en", "fr". - // - category: histogram by the [JobCategory][google.cloud.talent.v4.JobCategory], for example, - // "COMPUTER_AND_IT", "HEALTHCARE". - // - base_compensation_unit: histogram by the - // [CompensationInfo.CompensationUnit][google.cloud.talent.v4.CompensationInfo.CompensationUnit] of base - // salary, for example, "WEEKLY", "MONTHLY". - // - base_compensation: histogram by the base salary. Must specify list of - // numeric buckets to group results by. - // - annualized_base_compensation: histogram by the base annualized salary. - // Must specify list of numeric buckets to group results by. - // - annualized_total_compensation: histogram by the total annualized salary. - // Must specify list of numeric buckets to group results by. - // - string_custom_attribute: histogram by string [Job.custom_attributes][google.cloud.talent.v4.Job.custom_attributes]. - // Values can be accessed via square bracket notations like - // string_custom_attribute["key1"]. - // - numeric_custom_attribute: histogram by numeric [Job.custom_attributes][google.cloud.talent.v4.Job.custom_attributes]. - // Values can be accessed via square bracket notations like - // numeric_custom_attribute["key1"]. Must specify list of numeric buckets to - // group results by. + // * publish_time_in_day: histogram by the [Job.posting_publish_time][google.cloud.talent.v4.Job.posting_publish_time] + // in days. + // Must specify list of numeric buckets in spec. + // * publish_time_in_month: histogram by the [Job.posting_publish_time][google.cloud.talent.v4.Job.posting_publish_time] + // in months. + // Must specify list of numeric buckets in spec. + // * publish_time_in_year: histogram by the [Job.posting_publish_time][google.cloud.talent.v4.Job.posting_publish_time] + // in years. + // Must specify list of numeric buckets in spec. + // * degree_types: histogram by the [Job.degree_types][google.cloud.talent.v4.Job.degree_types], for example, + // "Bachelors", "Masters". + // * job_level: histogram by the [Job.job_level][google.cloud.talent.v4.Job.job_level], for example, "Entry + // Level". + // * country: histogram by the country code of jobs, for example, "US", "FR". + // * admin1: histogram by the admin1 code of jobs, which is a global + // placeholder referring to the state, province, or the particular term a + // country uses to define the geographic structure below the country level, + // for example, "CA", "IL". + // * city: histogram by a combination of the "city name, admin1 code". For + // example, "Mountain View, CA", "New York, NY". + // * admin1_country: histogram by a combination of the "admin1 code, country", + // for example, "CA, US", "IL, US". + // * city_coordinate: histogram by the city center's GPS coordinates (latitude + // and longitude), for example, 37.4038522,-122.0987765. Since the + // coordinates of a city center can change, customers may need to refresh + // them periodically. + // * locale: histogram by the [Job.language_code][google.cloud.talent.v4.Job.language_code], for example, "en-US", + // "fr-FR". + // * language: histogram by the language subtag of the [Job.language_code][google.cloud.talent.v4.Job.language_code], + // for example, "en", "fr". + // * category: histogram by the [JobCategory][google.cloud.talent.v4.JobCategory], for example, + // "COMPUTER_AND_IT", "HEALTHCARE". + // * base_compensation_unit: histogram by the + // [CompensationInfo.CompensationUnit][google.cloud.talent.v4.CompensationInfo.CompensationUnit] of base + // salary, for example, "WEEKLY", "MONTHLY". + // * base_compensation: histogram by the base salary. Must specify list of + // numeric buckets to group results by. + // * annualized_base_compensation: histogram by the base annualized salary. + // Must specify list of numeric buckets to group results by. + // * annualized_total_compensation: histogram by the total annualized salary. + // Must specify list of numeric buckets to group results by. + // * string_custom_attribute: histogram by string [Job.custom_attributes][google.cloud.talent.v4.Job.custom_attributes]. + // Values can be accessed via square bracket notations like + // string_custom_attribute["key1"]. + // * numeric_custom_attribute: histogram by numeric [Job.custom_attributes][google.cloud.talent.v4.Job.custom_attributes]. + // Values can be accessed via square bracket notations like + // numeric_custom_attribute["key1"]. Must specify list of numeric buckets to + // group results by. // // Example expressions: // // * `count(admin1)` // * `count(base_compensation, [bucket(1000, 10000), bucket(10000, 100000), // bucket(100000, MAX)])` - // - `count(string_custom_attribute["some-string-custom-attribute"])` - // - `count(numeric_custom_attribute["some-numeric-custom-attribute"], - // [bucket(MIN, 0, "negative"), bucket(0, MAX, "non-negative")])` + // * `count(string_custom_attribute["some-string-custom-attribute"])` + // * `count(numeric_custom_attribute["some-numeric-custom-attribute"], + // [bucket(MIN, 0, "negative"), bucket(0, MAX, "non-negative")])` HistogramQueries []*HistogramQuery `protobuf:"bytes,7,rep,name=histogram_queries,json=histogramQueries,proto3" json:"histogram_queries,omitempty"` // The desired job attributes returned for jobs in the search response. // Defaults to [JobView.JOB_VIEW_SMALL][google.cloud.talent.v4.JobView.JOB_VIEW_SMALL] if no value is specified. @@ -987,51 +986,51 @@ type SearchJobsRequest struct { // // Supported options are: // - // - `"relevance desc"`: By relevance descending, as determined by the API - // algorithms. Relevance thresholding of query results is only available - // with this ordering. - // - `"posting_publish_time desc"`: By [Job.posting_publish_time][google.cloud.talent.v4.Job.posting_publish_time] - // descending. - // - `"posting_update_time desc"`: By [Job.posting_update_time][google.cloud.talent.v4.Job.posting_update_time] - // descending. - // - `"title"`: By [Job.title][google.cloud.talent.v4.Job.title] ascending. - // - `"title desc"`: By [Job.title][google.cloud.talent.v4.Job.title] descending. - // - `"annualized_base_compensation"`: By job's - // [CompensationInfo.annualized_base_compensation_range][google.cloud.talent.v4.CompensationInfo.annualized_base_compensation_range] ascending. Jobs - // whose annualized base compensation is unspecified are put at the end of - // search results. - // - `"annualized_base_compensation desc"`: By job's - // [CompensationInfo.annualized_base_compensation_range][google.cloud.talent.v4.CompensationInfo.annualized_base_compensation_range] descending. Jobs - // whose annualized base compensation is unspecified are put at the end of - // search results. - // - `"annualized_total_compensation"`: By job's - // [CompensationInfo.annualized_total_compensation_range][google.cloud.talent.v4.CompensationInfo.annualized_total_compensation_range] ascending. Jobs - // whose annualized base compensation is unspecified are put at the end of - // search results. - // - `"annualized_total_compensation desc"`: By job's - // [CompensationInfo.annualized_total_compensation_range][google.cloud.talent.v4.CompensationInfo.annualized_total_compensation_range] descending. Jobs - // whose annualized base compensation is unspecified are put at the end of - // search results. - // - `"custom_ranking desc"`: By the relevance score adjusted to the - // [SearchJobsRequest.CustomRankingInfo.ranking_expression][google.cloud.talent.v4.SearchJobsRequest.CustomRankingInfo.ranking_expression] with weight - // factor assigned by - // [SearchJobsRequest.CustomRankingInfo.importance_level][google.cloud.talent.v4.SearchJobsRequest.CustomRankingInfo.importance_level] in descending - // order. - // - Location sorting: Use the special syntax to order jobs by distance:
- // `"distance_from('Hawaii')"`: Order by distance from Hawaii.
- // `"distance_from(19.89, 155.5)"`: Order by distance from a coordinate.
- // `"distance_from('Hawaii'), distance_from('Puerto Rico')"`: Order by - // multiple locations. See details below.
- // `"distance_from('Hawaii'), distance_from(19.89, 155.5)"`: Order by - // multiple locations. See details below.
- // The string can have a maximum of 256 characters. When multiple distance - // centers are provided, a job that is close to any of the distance centers - // would have a high rank. When a job has multiple locations, the job - // location closest to one of the distance centers will be used. Jobs that - // don't have locations will be ranked at the bottom. Distance is calculated - // with a precision of 11.3 meters (37.4 feet). Diversification strategy is - // still applied unless explicitly disabled in - // [diversification_level][google.cloud.talent.v4.SearchJobsRequest.diversification_level]. + // * `"relevance desc"`: By relevance descending, as determined by the API + // algorithms. Relevance thresholding of query results is only available + // with this ordering. + // * `"posting_publish_time desc"`: By [Job.posting_publish_time][google.cloud.talent.v4.Job.posting_publish_time] + // descending. + // * `"posting_update_time desc"`: By [Job.posting_update_time][google.cloud.talent.v4.Job.posting_update_time] + // descending. + // * `"title"`: By [Job.title][google.cloud.talent.v4.Job.title] ascending. + // * `"title desc"`: By [Job.title][google.cloud.talent.v4.Job.title] descending. + // * `"annualized_base_compensation"`: By job's + // [CompensationInfo.annualized_base_compensation_range][google.cloud.talent.v4.CompensationInfo.annualized_base_compensation_range] ascending. Jobs + // whose annualized base compensation is unspecified are put at the end of + // search results. + // * `"annualized_base_compensation desc"`: By job's + // [CompensationInfo.annualized_base_compensation_range][google.cloud.talent.v4.CompensationInfo.annualized_base_compensation_range] descending. Jobs + // whose annualized base compensation is unspecified are put at the end of + // search results. + // * `"annualized_total_compensation"`: By job's + // [CompensationInfo.annualized_total_compensation_range][google.cloud.talent.v4.CompensationInfo.annualized_total_compensation_range] ascending. Jobs + // whose annualized base compensation is unspecified are put at the end of + // search results. + // * `"annualized_total_compensation desc"`: By job's + // [CompensationInfo.annualized_total_compensation_range][google.cloud.talent.v4.CompensationInfo.annualized_total_compensation_range] descending. Jobs + // whose annualized base compensation is unspecified are put at the end of + // search results. + // * `"custom_ranking desc"`: By the relevance score adjusted to the + // [SearchJobsRequest.CustomRankingInfo.ranking_expression][google.cloud.talent.v4.SearchJobsRequest.CustomRankingInfo.ranking_expression] with weight + // factor assigned by + // [SearchJobsRequest.CustomRankingInfo.importance_level][google.cloud.talent.v4.SearchJobsRequest.CustomRankingInfo.importance_level] in descending + // order. + // * Location sorting: Use the special syntax to order jobs by distance:
+ // `"distance_from('Hawaii')"`: Order by distance from Hawaii.
+ // `"distance_from(19.89, 155.5)"`: Order by distance from a coordinate.
+ // `"distance_from('Hawaii'), distance_from('Puerto Rico')"`: Order by + // multiple locations. See details below.
+ // `"distance_from('Hawaii'), distance_from(19.89, 155.5)"`: Order by + // multiple locations. See details below.
+ // The string can have a maximum of 256 characters. When multiple distance + // centers are provided, a job that is close to any of the distance centers + // would have a high rank. When a job has multiple locations, the job + // location closest to one of the distance centers will be used. Jobs that + // don't have locations will be ranked at the bottom. Distance is calculated + // with a precision of 11.3 meters (37.4 feet). Diversification strategy is + // still applied unless explicitly disabled in + // [diversification_level][google.cloud.talent.v4.SearchJobsRequest.diversification_level]. OrderBy string `protobuf:"bytes,12,opt,name=order_by,json=orderBy,proto3" json:"order_by,omitempty"` // Controls whether highly similar jobs are returned next to each other in // the search results. Jobs are identified as highly similar based on @@ -1879,8 +1878,7 @@ type SearchJobsResponse_MatchingJob struct { // field, and matching query keywords are enclosed in HTML bold tags. SearchTextSnippet string `protobuf:"bytes,4,opt,name=search_text_snippet,json=searchTextSnippet,proto3" json:"search_text_snippet,omitempty"` // Commute information which is generated based on specified - // - // [CommuteFilter][google.cloud.talent.v4.CommuteFilter]. + // [CommuteFilter][google.cloud.talent.v4.CommuteFilter]. CommuteInfo *SearchJobsResponse_CommuteInfo `protobuf:"bytes,5,opt,name=commute_info,json=commuteInfo,proto3" json:"commute_info,omitempty"` } diff --git a/talent/apiv4/talentpb/tenant.pb.go b/talent/apiv4/talentpb/tenant.pb.go index 8a4328b94d2c..4bd4845d4f1c 100644 --- a/talent/apiv4/talentpb/tenant.pb.go +++ b/talent/apiv4/talentpb/tenant.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/talent/v4/tenant.proto package talentpb diff --git a/talent/apiv4/talentpb/tenant_service.pb.go b/talent/apiv4/talentpb/tenant_service.pb.go index c9129d19ce1e..71a26306d3f1 100644 --- a/talent/apiv4/talentpb/tenant_service.pb.go +++ b/talent/apiv4/talentpb/tenant_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/talent/v4/tenant_service.proto package talentpb diff --git a/talent/apiv4/tenant_client.go b/talent/apiv4/tenant_client.go index bafa2e22a145..688d71dd6a5b 100644 --- a/talent/apiv4/tenant_client.go +++ b/talent/apiv4/tenant_client.go @@ -17,22 +17,28 @@ package talent import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" talentpb "cloud.google.com/go/talent/apiv4/talentpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -104,6 +110,47 @@ func defaultTenantCallOptions() *TenantCallOptions { } } +func defaultTenantRESTCallOptions() *TenantCallOptions { + return &TenantCallOptions{ + CreateTenant: []gax.CallOption{}, + GetTenant: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + UpdateTenant: []gax.CallOption{}, + DeleteTenant: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + ListTenants: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + GetOperation: []gax.CallOption{}, + } +} + // internalTenantClient is an interface that defines the methods available from Cloud Talent Solution API. type internalTenantClient interface { Close() error @@ -266,6 +313,74 @@ func (c *tenantGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type tenantRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing TenantClient + CallOptions **TenantCallOptions +} + +// NewTenantRESTClient creates a new tenant service rest client. +// +// A service that handles tenant management, including CRUD and enumeration. +func NewTenantRESTClient(ctx context.Context, opts ...option.ClientOption) (*TenantClient, error) { + clientOpts := append(defaultTenantRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultTenantRESTCallOptions() + c := &tenantRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &TenantClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultTenantRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://jobs.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://jobs.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://jobs.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *tenantRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *tenantRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *tenantRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *tenantGRPCClient) CreateTenant(ctx context.Context, req *talentpb.CreateTenantRequest, opts ...gax.CallOption) (*talentpb.Tenant, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) @@ -412,6 +527,387 @@ func (c *tenantGRPCClient) GetOperation(ctx context.Context, req *longrunningpb. return resp, nil } +// CreateTenant creates a new tenant entity. +func (c *tenantRESTClient) CreateTenant(ctx context.Context, req *talentpb.CreateTenantRequest, opts ...gax.CallOption) (*talentpb.Tenant, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetTenant() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v4/%v/tenants", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateTenant[0:len((*c.CallOptions).CreateTenant):len((*c.CallOptions).CreateTenant)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &talentpb.Tenant{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetTenant retrieves specified tenant. +func (c *tenantRESTClient) GetTenant(ctx context.Context, req *talentpb.GetTenantRequest, opts ...gax.CallOption) (*talentpb.Tenant, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v4/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetTenant[0:len((*c.CallOptions).GetTenant):len((*c.CallOptions).GetTenant)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &talentpb.Tenant{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateTenant updates specified tenant. +func (c *tenantRESTClient) UpdateTenant(ctx context.Context, req *talentpb.UpdateTenantRequest, opts ...gax.CallOption) (*talentpb.Tenant, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetTenant() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v4/%v", req.GetTenant().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "tenant.name", url.QueryEscape(req.GetTenant().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateTenant[0:len((*c.CallOptions).UpdateTenant):len((*c.CallOptions).UpdateTenant)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &talentpb.Tenant{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteTenant deletes specified tenant. +func (c *tenantRESTClient) DeleteTenant(ctx context.Context, req *talentpb.DeleteTenantRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v4/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// ListTenants lists all tenants associated with the project. +func (c *tenantRESTClient) ListTenants(ctx context.Context, req *talentpb.ListTenantsRequest, opts ...gax.CallOption) *TenantIterator { + it := &TenantIterator{} + req = proto.Clone(req).(*talentpb.ListTenantsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*talentpb.Tenant, string, error) { + resp := &talentpb.ListTenantsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v4/%v/tenants", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetTenants(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *tenantRESTClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v4/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + // TenantIterator manages a stream of *talentpb.Tenant. type TenantIterator struct { items []*talentpb.Tenant diff --git a/talent/apiv4/tenant_client_example_test.go b/talent/apiv4/tenant_client_example_test.go index 1b02c988ef86..637e3fbc0b29 100644 --- a/talent/apiv4/tenant_client_example_test.go +++ b/talent/apiv4/tenant_client_example_test.go @@ -42,6 +42,23 @@ func ExampleNewTenantClient() { _ = c } +func ExampleNewTenantRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := talent.NewTenantRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleTenantClient_CreateTenant() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/talent/apiv4beta1/company_client.go b/talent/apiv4beta1/company_client.go index 43e18e950043..324fb58dfa73 100644 --- a/talent/apiv4beta1/company_client.go +++ b/talent/apiv4beta1/company_client.go @@ -542,6 +542,11 @@ func (c *companyRESTClient) CreateCompany(ctx context.Context, req *talentpb.Cre } baseUrl.Path += fmt.Sprintf("/v4beta1/%v/companies", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -595,6 +600,11 @@ func (c *companyRESTClient) GetCompany(ctx context.Context, req *talentpb.GetCom } baseUrl.Path += fmt.Sprintf("/v4beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -654,6 +664,11 @@ func (c *companyRESTClient) UpdateCompany(ctx context.Context, req *talentpb.Upd } baseUrl.Path += fmt.Sprintf("/v4beta1/%v", req.GetCompany().GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "company.name", url.QueryEscape(req.GetCompany().GetName()))) @@ -708,6 +723,11 @@ func (c *companyRESTClient) DeleteCompany(ctx context.Context, req *talentpb.Del } baseUrl.Path += fmt.Sprintf("/v4beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -757,6 +777,7 @@ func (c *companyRESTClient) ListCompanies(ctx context.Context, req *talentpb.Lis baseUrl.Path += fmt.Sprintf("/v4beta1/%v/companies", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -833,6 +854,11 @@ func (c *companyRESTClient) GetOperation(ctx context.Context, req *longrunningpb } baseUrl.Path += fmt.Sprintf("/v4beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) diff --git a/talent/apiv4beta1/completion_client.go b/talent/apiv4beta1/completion_client.go index 439201136742..fa1fdcbcfe83 100644 --- a/talent/apiv4beta1/completion_client.go +++ b/talent/apiv4beta1/completion_client.go @@ -350,11 +350,14 @@ func (c *completionRESTClient) CompleteQuery(ctx context.Context, req *talentpb. baseUrl.Path += fmt.Sprintf("/v4beta1/%v:complete", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetCompany() != "" { params.Add("company", fmt.Sprintf("%v", req.GetCompany())) } - if req.GetLanguageCodes() != nil { - params.Add("languageCodes", fmt.Sprintf("%v", req.GetLanguageCodes())) + if items := req.GetLanguageCodes(); len(items) > 0 { + for _, item := range items { + params.Add("languageCodes", fmt.Sprintf("%v", item)) + } } params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) params.Add("query", fmt.Sprintf("%v", req.GetQuery())) @@ -420,6 +423,11 @@ func (c *completionRESTClient) GetOperation(ctx context.Context, req *longrunnin } baseUrl.Path += fmt.Sprintf("/v4beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) diff --git a/talent/apiv4beta1/event_client.go b/talent/apiv4beta1/event_client.go index b514c2d74144..de777299efed 100644 --- a/talent/apiv4beta1/event_client.go +++ b/talent/apiv4beta1/event_client.go @@ -344,6 +344,11 @@ func (c *eventRESTClient) CreateClientEvent(ctx context.Context, req *talentpb.C } baseUrl.Path += fmt.Sprintf("/v4beta1/%v/clientEvents", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -397,6 +402,11 @@ func (c *eventRESTClient) GetOperation(ctx context.Context, req *longrunningpb.G } baseUrl.Path += fmt.Sprintf("/v4beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) diff --git a/talent/apiv4beta1/job_client.go b/talent/apiv4beta1/job_client.go index 2f6f88cf62ec..d9e32f3843db 100644 --- a/talent/apiv4beta1/job_client.go +++ b/talent/apiv4beta1/job_client.go @@ -797,6 +797,11 @@ func (c *jobRESTClient) CreateJob(ctx context.Context, req *talentpb.CreateJobRe } baseUrl.Path += fmt.Sprintf("/v4beta1/%v/jobs", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -856,6 +861,11 @@ func (c *jobRESTClient) BatchCreateJobs(ctx context.Context, req *talentpb.Batch } baseUrl.Path += fmt.Sprintf("/v4beta1/%v/jobs:batchCreate", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -914,6 +924,11 @@ func (c *jobRESTClient) GetJob(ctx context.Context, req *talentpb.GetJobRequest, } baseUrl.Path += fmt.Sprintf("/v4beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -976,6 +991,11 @@ func (c *jobRESTClient) UpdateJob(ctx context.Context, req *talentpb.UpdateJobRe } baseUrl.Path += fmt.Sprintf("/v4beta1/%v", req.GetJob().GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "job.name", url.QueryEscape(req.GetJob().GetName()))) @@ -1035,6 +1055,11 @@ func (c *jobRESTClient) BatchUpdateJobs(ctx context.Context, req *talentpb.Batch } baseUrl.Path += fmt.Sprintf("/v4beta1/%v/jobs:batchUpdate", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1095,6 +1120,11 @@ func (c *jobRESTClient) DeleteJob(ctx context.Context, req *talentpb.DeleteJobRe } baseUrl.Path += fmt.Sprintf("/v4beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -1136,6 +1166,11 @@ func (c *jobRESTClient) BatchDeleteJobs(ctx context.Context, req *talentpb.Batch } baseUrl.Path += fmt.Sprintf("/v4beta1/%v/jobs:batchDelete", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1185,6 +1220,7 @@ func (c *jobRESTClient) ListJobs(ctx context.Context, req *talentpb.ListJobsRequ baseUrl.Path += fmt.Sprintf("/v4beta1/%v/jobs", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) if req.GetJobView() != 0 { params.Add("jobView", fmt.Sprintf("%v", req.GetJobView())) @@ -1272,6 +1308,11 @@ func (c *jobRESTClient) SearchJobs(ctx context.Context, req *talentpb.SearchJobs } baseUrl.Path += fmt.Sprintf("/v4beta1/%v/jobs:search", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1353,6 +1394,11 @@ func (c *jobRESTClient) SearchJobsForAlert(ctx context.Context, req *talentpb.Se } baseUrl.Path += fmt.Sprintf("/v4beta1/%v/jobs:searchForAlert", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { @@ -1417,6 +1463,11 @@ func (c *jobRESTClient) GetOperation(ctx context.Context, req *longrunningpb.Get } baseUrl.Path += fmt.Sprintf("/v4beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) diff --git a/talent/apiv4beta1/talentpb/batch.pb.go b/talent/apiv4beta1/talentpb/batch.pb.go index 1a993f615c59..7ed179580dcc 100644 --- a/talent/apiv4beta1/talentpb/batch.pb.go +++ b/talent/apiv4beta1/talentpb/batch.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/talent/v4beta1/batch.proto package talentpb diff --git a/talent/apiv4beta1/talentpb/common.pb.go b/talent/apiv4beta1/talentpb/common.pb.go index be0c5228589e..c1dcdb502a1d 100644 --- a/talent/apiv4beta1/talentpb/common.pb.go +++ b/talent/apiv4beta1/talentpb/common.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/talent/v4beta1/common.proto package talentpb @@ -2072,7 +2072,6 @@ type CompensationInfo_CompensationEntry struct { // Compensation amount. It could be a fixed amount or a floating range. // // Types that are assignable to CompensationAmount: - // // *CompensationInfo_CompensationEntry_Amount // *CompensationInfo_CompensationEntry_Range CompensationAmount isCompensationInfo_CompensationEntry_CompensationAmount `protobuf_oneof:"compensation_amount"` diff --git a/talent/apiv4beta1/talentpb/company.pb.go b/talent/apiv4beta1/talentpb/company.pb.go index 6789f95977e5..023ec9505343 100644 --- a/talent/apiv4beta1/talentpb/company.pb.go +++ b/talent/apiv4beta1/talentpb/company.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/talent/v4beta1/company.proto package talentpb diff --git a/talent/apiv4beta1/talentpb/company_service.pb.go b/talent/apiv4beta1/talentpb/company_service.pb.go index 3bbfe64a6e32..e74a81b45224 100644 --- a/talent/apiv4beta1/talentpb/company_service.pb.go +++ b/talent/apiv4beta1/talentpb/company_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/talent/v4beta1/company_service.proto package talentpb diff --git a/talent/apiv4beta1/talentpb/completion_service.pb.go b/talent/apiv4beta1/talentpb/completion_service.pb.go index b3d45bedebb5..9560fea6a7a6 100644 --- a/talent/apiv4beta1/talentpb/completion_service.pb.go +++ b/talent/apiv4beta1/talentpb/completion_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/talent/v4beta1/completion_service.proto package talentpb diff --git a/talent/apiv4beta1/talentpb/event.pb.go b/talent/apiv4beta1/talentpb/event.pb.go index bc46a2aa63a3..832645a79e2c 100644 --- a/talent/apiv4beta1/talentpb/event.pb.go +++ b/talent/apiv4beta1/talentpb/event.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/talent/v4beta1/event.proto package talentpb @@ -209,7 +209,6 @@ type ClientEvent struct { // The detail information of a specific event type. // // Types that are assignable to Event: - // // *ClientEvent_JobEvent Event isClientEvent_Event `protobuf_oneof:"event"` // Notes about the event provided by recruiters or other users, for example, diff --git a/talent/apiv4beta1/talentpb/event_service.pb.go b/talent/apiv4beta1/talentpb/event_service.pb.go index 4d34058ad498..21aace9dc962 100644 --- a/talent/apiv4beta1/talentpb/event_service.pb.go +++ b/talent/apiv4beta1/talentpb/event_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/talent/v4beta1/event_service.proto package talentpb diff --git a/talent/apiv4beta1/talentpb/filters.pb.go b/talent/apiv4beta1/talentpb/filters.pb.go index cdf8f32ba107..36472ce4434f 100644 --- a/talent/apiv4beta1/talentpb/filters.pb.go +++ b/talent/apiv4beta1/talentpb/filters.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/talent/v4beta1/filters.proto package talentpb @@ -291,13 +291,12 @@ type JobQuery struct { // categories are searched against. JobCategories []JobCategory `protobuf:"varint,4,rep,packed,name=job_categories,json=jobCategories,proto3,enum=google.cloud.talent.v4beta1.JobCategory" json:"job_categories,omitempty"` // Allows filtering jobs by commute time with different travel methods (for - // - // example, driving or public transit). + // example, driving or public transit). // // Note: This only works when you specify a [CommuteMethod][google.cloud.talent.v4beta1.CommuteMethod]. In this case, // [location_filters][google.cloud.talent.v4beta1.JobQuery.location_filters] is ignored. // - // Currently we don't support sorting by commute time. + // Currently we don't support sorting by commute time. CommuteFilter *CommuteFilter `protobuf:"bytes,5,opt,name=commute_filter,json=commuteFilter,proto3" json:"commute_filter,omitempty"` // This filter specifies the company [Company.display_name][google.cloud.talent.v4beta1.Company.display_name] // of the jobs to search against. The company name must match the value @@ -376,6 +375,7 @@ type JobQuery struct { // If a value isn't specified, the search results can contain jobs in any // locale. // + // // Language codes should be in BCP-47 format, such as "en-US" or "sr-Latn". // For more information, see // [Tags for Identifying Languages](https://tools.ietf.org/html/bcp47). @@ -753,7 +753,6 @@ type CommuteFilter struct { // Traffic factor to take into account while searching by commute. // // Types that are assignable to TrafficOption: - // // *CommuteFilter_RoadTraffic_ // *CommuteFilter_DepartureTime TrafficOption isCommuteFilter_TrafficOption `protobuf_oneof:"traffic_option"` diff --git a/talent/apiv4beta1/talentpb/histogram.pb.go b/talent/apiv4beta1/talentpb/histogram.pb.go index 930d6d1df5b8..c3c36b8ac1e8 100644 --- a/talent/apiv4beta1/talentpb/histogram.pb.go +++ b/talent/apiv4beta1/talentpb/histogram.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/talent/v4beta1/histogram.proto package talentpb @@ -101,11 +101,11 @@ type HistogramQueryResult struct { // // The key format is: // - // - (for string histogram) string values stored in the field. - // - (for named numeric bucket) name specified in `bucket()` function, like - // for `bucket(0, MAX, "non-negative")`, the key will be `non-negative`. - // - (for anonymous numeric bucket) range formatted as `-`, for - // example, `0-1000`, `MIN-0`, and `0-MAX`. + // * (for string histogram) string values stored in the field. + // * (for named numeric bucket) name specified in `bucket()` function, like + // for `bucket(0, MAX, "non-negative")`, the key will be `non-negative`. + // * (for anonymous numeric bucket) range formatted as `-`, for + // example, `0-1000`, `MIN-0`, and `0-MAX`. Histogram map[string]int64 `protobuf:"bytes,2,rep,name=histogram,proto3" json:"histogram,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"varint,2,opt,name=value,proto3"` } diff --git a/talent/apiv4beta1/talentpb/job.pb.go b/talent/apiv4beta1/talentpb/job.pb.go index c83b4739e0a4..f0d35ccc7338 100644 --- a/talent/apiv4beta1/talentpb/job.pb.go +++ b/talent/apiv4beta1/talentpb/job.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/talent/v4beta1/job.proto package talentpb diff --git a/talent/apiv4beta1/talentpb/job_service.pb.go b/talent/apiv4beta1/talentpb/job_service.pb.go index 8cdc90094192..af9465e9a7db 100644 --- a/talent/apiv4beta1/talentpb/job_service.pb.go +++ b/talent/apiv4beta1/talentpb/job_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/talent/v4beta1/job_service.proto package talentpb @@ -961,69 +961,68 @@ type SearchJobsRequest struct { // // Job histogram facets: // - // - company_display_name: histogram by [Job.company_display_name][google.cloud.talent.v4beta1.Job.company_display_name]. - // - employment_type: histogram by [Job.employment_types][google.cloud.talent.v4beta1.Job.employment_types], for example, - // "FULL_TIME", "PART_TIME". - // - company_size (DEPRECATED): histogram by [CompanySize][google.cloud.talent.v4beta1.CompanySize], for example, - // + // * company_display_name: histogram by [Job.company_display_name][google.cloud.talent.v4beta1.Job.company_display_name]. + // * employment_type: histogram by [Job.employment_types][google.cloud.talent.v4beta1.Job.employment_types], for example, + // "FULL_TIME", "PART_TIME". + // * company_size (DEPRECATED): histogram by [CompanySize][google.cloud.talent.v4beta1.CompanySize], for example, // "SMALL", "MEDIUM", "BIG". - // - publish_time_in_day: histogram by the [Job.posting_publish_time][google.cloud.talent.v4beta1.Job.posting_publish_time] - // in days. - // Must specify list of numeric buckets in spec. - // - publish_time_in_month: histogram by the [Job.posting_publish_time][google.cloud.talent.v4beta1.Job.posting_publish_time] - // in months. - // Must specify list of numeric buckets in spec. - // - publish_time_in_year: histogram by the [Job.posting_publish_time][google.cloud.talent.v4beta1.Job.posting_publish_time] - // in years. - // Must specify list of numeric buckets in spec. - // - degree_types: histogram by the [Job.degree_types][google.cloud.talent.v4beta1.Job.degree_types], for example, - // "Bachelors", "Masters". - // - job_level: histogram by the [Job.job_level][google.cloud.talent.v4beta1.Job.job_level], for example, "Entry - // Level". - // - country: histogram by the country code of jobs, for example, "US", "FR". - // - admin1: histogram by the admin1 code of jobs, which is a global - // placeholder referring to the state, province, or the particular term a - // country uses to define the geographic structure below the country level, - // for example, "CA", "IL". - // - city: histogram by a combination of the "city name, admin1 code". For - // example, "Mountain View, CA", "New York, NY". - // - admin1_country: histogram by a combination of the "admin1 code, country", - // for example, "CA, US", "IL, US". - // - city_coordinate: histogram by the city center's GPS coordinates (latitude - // and longitude), for example, 37.4038522,-122.0987765. Since the - // coordinates of a city center can change, customers may need to refresh - // them periodically. - // - locale: histogram by the [Job.language_code][google.cloud.talent.v4beta1.Job.language_code], for example, "en-US", - // "fr-FR". - // - language: histogram by the language subtag of the [Job.language_code][google.cloud.talent.v4beta1.Job.language_code], - // for example, "en", "fr". - // - category: histogram by the [JobCategory][google.cloud.talent.v4beta1.JobCategory], for example, - // "COMPUTER_AND_IT", "HEALTHCARE". - // - base_compensation_unit: histogram by the - // [CompensationInfo.CompensationUnit][google.cloud.talent.v4beta1.CompensationInfo.CompensationUnit] of base - // salary, for example, "WEEKLY", "MONTHLY". - // - base_compensation: histogram by the base salary. Must specify list of - // numeric buckets to group results by. - // - annualized_base_compensation: histogram by the base annualized salary. - // Must specify list of numeric buckets to group results by. - // - annualized_total_compensation: histogram by the total annualized salary. - // Must specify list of numeric buckets to group results by. - // - string_custom_attribute: histogram by string [Job.custom_attributes][google.cloud.talent.v4beta1.Job.custom_attributes]. - // Values can be accessed via square bracket notations like - // string_custom_attribute["key1"]. - // - numeric_custom_attribute: histogram by numeric [Job.custom_attributes][google.cloud.talent.v4beta1.Job.custom_attributes]. - // Values can be accessed via square bracket notations like - // numeric_custom_attribute["key1"]. Must specify list of numeric buckets to - // group results by. + // * publish_time_in_day: histogram by the [Job.posting_publish_time][google.cloud.talent.v4beta1.Job.posting_publish_time] + // in days. + // Must specify list of numeric buckets in spec. + // * publish_time_in_month: histogram by the [Job.posting_publish_time][google.cloud.talent.v4beta1.Job.posting_publish_time] + // in months. + // Must specify list of numeric buckets in spec. + // * publish_time_in_year: histogram by the [Job.posting_publish_time][google.cloud.talent.v4beta1.Job.posting_publish_time] + // in years. + // Must specify list of numeric buckets in spec. + // * degree_types: histogram by the [Job.degree_types][google.cloud.talent.v4beta1.Job.degree_types], for example, + // "Bachelors", "Masters". + // * job_level: histogram by the [Job.job_level][google.cloud.talent.v4beta1.Job.job_level], for example, "Entry + // Level". + // * country: histogram by the country code of jobs, for example, "US", "FR". + // * admin1: histogram by the admin1 code of jobs, which is a global + // placeholder referring to the state, province, or the particular term a + // country uses to define the geographic structure below the country level, + // for example, "CA", "IL". + // * city: histogram by a combination of the "city name, admin1 code". For + // example, "Mountain View, CA", "New York, NY". + // * admin1_country: histogram by a combination of the "admin1 code, country", + // for example, "CA, US", "IL, US". + // * city_coordinate: histogram by the city center's GPS coordinates (latitude + // and longitude), for example, 37.4038522,-122.0987765. Since the + // coordinates of a city center can change, customers may need to refresh + // them periodically. + // * locale: histogram by the [Job.language_code][google.cloud.talent.v4beta1.Job.language_code], for example, "en-US", + // "fr-FR". + // * language: histogram by the language subtag of the [Job.language_code][google.cloud.talent.v4beta1.Job.language_code], + // for example, "en", "fr". + // * category: histogram by the [JobCategory][google.cloud.talent.v4beta1.JobCategory], for example, + // "COMPUTER_AND_IT", "HEALTHCARE". + // * base_compensation_unit: histogram by the + // [CompensationInfo.CompensationUnit][google.cloud.talent.v4beta1.CompensationInfo.CompensationUnit] of base + // salary, for example, "WEEKLY", "MONTHLY". + // * base_compensation: histogram by the base salary. Must specify list of + // numeric buckets to group results by. + // * annualized_base_compensation: histogram by the base annualized salary. + // Must specify list of numeric buckets to group results by. + // * annualized_total_compensation: histogram by the total annualized salary. + // Must specify list of numeric buckets to group results by. + // * string_custom_attribute: histogram by string [Job.custom_attributes][google.cloud.talent.v4beta1.Job.custom_attributes]. + // Values can be accessed via square bracket notations like + // string_custom_attribute["key1"]. + // * numeric_custom_attribute: histogram by numeric [Job.custom_attributes][google.cloud.talent.v4beta1.Job.custom_attributes]. + // Values can be accessed via square bracket notations like + // numeric_custom_attribute["key1"]. Must specify list of numeric buckets to + // group results by. // // Example expressions: // // * `count(admin1)` // * `count(base_compensation, [bucket(1000, 10000), bucket(10000, 100000), // bucket(100000, MAX)])` - // - `count(string_custom_attribute["some-string-custom-attribute"])` - // - `count(numeric_custom_attribute["some-numeric-custom-attribute"], - // [bucket(MIN, 0, "negative"), bucket(0, MAX, "non-negative")])` + // * `count(string_custom_attribute["some-string-custom-attribute"])` + // * `count(numeric_custom_attribute["some-numeric-custom-attribute"], + // [bucket(MIN, 0, "negative"), bucket(0, MAX, "non-negative")])` HistogramQueries []*HistogramQuery `protobuf:"bytes,7,rep,name=histogram_queries,json=histogramQueries,proto3" json:"histogram_queries,omitempty"` // The desired job attributes returned for jobs in the search response. // Defaults to [JobView.JOB_VIEW_SMALL][google.cloud.talent.v4beta1.JobView.JOB_VIEW_SMALL] if no value is specified. @@ -1052,51 +1051,51 @@ type SearchJobsRequest struct { // // Supported options are: // - // - `"relevance desc"`: By relevance descending, as determined by the API - // algorithms. Relevance thresholding of query results is only available - // with this ordering. - // - `"posting_publish_time desc"`: By [Job.posting_publish_time][google.cloud.talent.v4beta1.Job.posting_publish_time] - // descending. - // - `"posting_update_time desc"`: By [Job.posting_update_time][google.cloud.talent.v4beta1.Job.posting_update_time] - // descending. - // - `"title"`: By [Job.title][google.cloud.talent.v4beta1.Job.title] ascending. - // - `"title desc"`: By [Job.title][google.cloud.talent.v4beta1.Job.title] descending. - // - `"annualized_base_compensation"`: By job's - // [CompensationInfo.annualized_base_compensation_range][google.cloud.talent.v4beta1.CompensationInfo.annualized_base_compensation_range] ascending. Jobs - // whose annualized base compensation is unspecified are put at the end of - // search results. - // - `"annualized_base_compensation desc"`: By job's - // [CompensationInfo.annualized_base_compensation_range][google.cloud.talent.v4beta1.CompensationInfo.annualized_base_compensation_range] descending. Jobs - // whose annualized base compensation is unspecified are put at the end of - // search results. - // - `"annualized_total_compensation"`: By job's - // [CompensationInfo.annualized_total_compensation_range][google.cloud.talent.v4beta1.CompensationInfo.annualized_total_compensation_range] ascending. Jobs - // whose annualized base compensation is unspecified are put at the end of - // search results. - // - `"annualized_total_compensation desc"`: By job's - // [CompensationInfo.annualized_total_compensation_range][google.cloud.talent.v4beta1.CompensationInfo.annualized_total_compensation_range] descending. Jobs - // whose annualized base compensation is unspecified are put at the end of - // search results. - // - `"custom_ranking desc"`: By the relevance score adjusted to the - // [SearchJobsRequest.CustomRankingInfo.ranking_expression][google.cloud.talent.v4beta1.SearchJobsRequest.CustomRankingInfo.ranking_expression] with weight - // factor assigned by - // [SearchJobsRequest.CustomRankingInfo.importance_level][google.cloud.talent.v4beta1.SearchJobsRequest.CustomRankingInfo.importance_level] in descending - // order. - // - Location sorting: Use the special syntax to order jobs by distance:
- // `"distance_from('Hawaii')"`: Order by distance from Hawaii.
- // `"distance_from(19.89, 155.5)"`: Order by distance from a coordinate.
- // `"distance_from('Hawaii'), distance_from('Puerto Rico')"`: Order by - // multiple locations. See details below.
- // `"distance_from('Hawaii'), distance_from(19.89, 155.5)"`: Order by - // multiple locations. See details below.
- // The string can have a maximum of 256 characters. When multiple distance - // centers are provided, a job that is close to any of the distance centers - // would have a high rank. When a job has multiple locations, the job - // location closest to one of the distance centers will be used. Jobs that - // don't have locations will be ranked at the bottom. Distance is calculated - // with a precision of 11.3 meters (37.4 feet). Diversification strategy is - // still applied unless explicitly disabled in - // [diversification_level][google.cloud.talent.v4beta1.SearchJobsRequest.diversification_level]. + // * `"relevance desc"`: By relevance descending, as determined by the API + // algorithms. Relevance thresholding of query results is only available + // with this ordering. + // * `"posting_publish_time desc"`: By [Job.posting_publish_time][google.cloud.talent.v4beta1.Job.posting_publish_time] + // descending. + // * `"posting_update_time desc"`: By [Job.posting_update_time][google.cloud.talent.v4beta1.Job.posting_update_time] + // descending. + // * `"title"`: By [Job.title][google.cloud.talent.v4beta1.Job.title] ascending. + // * `"title desc"`: By [Job.title][google.cloud.talent.v4beta1.Job.title] descending. + // * `"annualized_base_compensation"`: By job's + // [CompensationInfo.annualized_base_compensation_range][google.cloud.talent.v4beta1.CompensationInfo.annualized_base_compensation_range] ascending. Jobs + // whose annualized base compensation is unspecified are put at the end of + // search results. + // * `"annualized_base_compensation desc"`: By job's + // [CompensationInfo.annualized_base_compensation_range][google.cloud.talent.v4beta1.CompensationInfo.annualized_base_compensation_range] descending. Jobs + // whose annualized base compensation is unspecified are put at the end of + // search results. + // * `"annualized_total_compensation"`: By job's + // [CompensationInfo.annualized_total_compensation_range][google.cloud.talent.v4beta1.CompensationInfo.annualized_total_compensation_range] ascending. Jobs + // whose annualized base compensation is unspecified are put at the end of + // search results. + // * `"annualized_total_compensation desc"`: By job's + // [CompensationInfo.annualized_total_compensation_range][google.cloud.talent.v4beta1.CompensationInfo.annualized_total_compensation_range] descending. Jobs + // whose annualized base compensation is unspecified are put at the end of + // search results. + // * `"custom_ranking desc"`: By the relevance score adjusted to the + // [SearchJobsRequest.CustomRankingInfo.ranking_expression][google.cloud.talent.v4beta1.SearchJobsRequest.CustomRankingInfo.ranking_expression] with weight + // factor assigned by + // [SearchJobsRequest.CustomRankingInfo.importance_level][google.cloud.talent.v4beta1.SearchJobsRequest.CustomRankingInfo.importance_level] in descending + // order. + // * Location sorting: Use the special syntax to order jobs by distance:
+ // `"distance_from('Hawaii')"`: Order by distance from Hawaii.
+ // `"distance_from(19.89, 155.5)"`: Order by distance from a coordinate.
+ // `"distance_from('Hawaii'), distance_from('Puerto Rico')"`: Order by + // multiple locations. See details below.
+ // `"distance_from('Hawaii'), distance_from(19.89, 155.5)"`: Order by + // multiple locations. See details below.
+ // The string can have a maximum of 256 characters. When multiple distance + // centers are provided, a job that is close to any of the distance centers + // would have a high rank. When a job has multiple locations, the job + // location closest to one of the distance centers will be used. Jobs that + // don't have locations will be ranked at the bottom. Distance is calculated + // with a precision of 11.3 meters (37.4 feet). Diversification strategy is + // still applied unless explicitly disabled in + // [diversification_level][google.cloud.talent.v4beta1.SearchJobsRequest.diversification_level]. OrderBy string `protobuf:"bytes,12,opt,name=order_by,json=orderBy,proto3" json:"order_by,omitempty"` // Controls whether highly similar jobs are returned next to each other in // the search results. Jobs are identified as highly similar based on @@ -1727,8 +1726,7 @@ type SearchJobsResponse_MatchingJob struct { // field, and matching query keywords are enclosed in HTML bold tags. SearchTextSnippet string `protobuf:"bytes,4,opt,name=search_text_snippet,json=searchTextSnippet,proto3" json:"search_text_snippet,omitempty"` // Commute information which is generated based on specified - // - // [CommuteFilter][google.cloud.talent.v4beta1.CommuteFilter]. + // [CommuteFilter][google.cloud.talent.v4beta1.CommuteFilter]. CommuteInfo *SearchJobsResponse_CommuteInfo `protobuf:"bytes,5,opt,name=commute_info,json=commuteInfo,proto3" json:"commute_info,omitempty"` } diff --git a/talent/apiv4beta1/talentpb/tenant.pb.go b/talent/apiv4beta1/talentpb/tenant.pb.go index 3d2151ecb5f5..61f7fa2167cc 100644 --- a/talent/apiv4beta1/talentpb/tenant.pb.go +++ b/talent/apiv4beta1/talentpb/tenant.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/talent/v4beta1/tenant.proto package talentpb diff --git a/talent/apiv4beta1/talentpb/tenant_service.pb.go b/talent/apiv4beta1/talentpb/tenant_service.pb.go index 9cd60333c139..f2cef6d69b77 100644 --- a/talent/apiv4beta1/talentpb/tenant_service.pb.go +++ b/talent/apiv4beta1/talentpb/tenant_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/talent/v4beta1/tenant_service.proto package talentpb diff --git a/talent/apiv4beta1/tenant_client.go b/talent/apiv4beta1/tenant_client.go index c24029d5f698..08f62e6279f1 100644 --- a/talent/apiv4beta1/tenant_client.go +++ b/talent/apiv4beta1/tenant_client.go @@ -541,6 +541,11 @@ func (c *tenantRESTClient) CreateTenant(ctx context.Context, req *talentpb.Creat } baseUrl.Path += fmt.Sprintf("/v4beta1/%v/tenants", req.GetParent()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -594,6 +599,11 @@ func (c *tenantRESTClient) GetTenant(ctx context.Context, req *talentpb.GetTenan } baseUrl.Path += fmt.Sprintf("/v4beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -653,6 +663,11 @@ func (c *tenantRESTClient) UpdateTenant(ctx context.Context, req *talentpb.Updat } baseUrl.Path += fmt.Sprintf("/v4beta1/%v", req.GetTenant().GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "tenant.name", url.QueryEscape(req.GetTenant().GetName()))) @@ -706,6 +721,11 @@ func (c *tenantRESTClient) DeleteTenant(ctx context.Context, req *talentpb.Delet } baseUrl.Path += fmt.Sprintf("/v4beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -755,6 +775,7 @@ func (c *tenantRESTClient) ListTenants(ctx context.Context, req *talentpb.ListTe baseUrl.Path += fmt.Sprintf("/v4beta1/%v/tenants", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetPageSize() != 0 { params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) } @@ -828,6 +849,11 @@ func (c *tenantRESTClient) GetOperation(ctx context.Context, req *longrunningpb. } baseUrl.Path += fmt.Sprintf("/v4beta1/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) diff --git a/texttospeech/apiv1/doc.go b/texttospeech/apiv1/doc.go index 9b0dd0f69aca..0905ab7c3865 100644 --- a/texttospeech/apiv1/doc.go +++ b/texttospeech/apiv1/doc.go @@ -81,6 +81,8 @@ package texttospeech // import "cloud.google.com/go/texttospeech/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -169,3 +171,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/texttospeech/apiv1/gapic_metadata.json b/texttospeech/apiv1/gapic_metadata.json index 111b0361dca8..0ce4247e05ba 100644 --- a/texttospeech/apiv1/gapic_metadata.json +++ b/texttospeech/apiv1/gapic_metadata.json @@ -21,6 +21,21 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "ListVoices": { + "methods": [ + "ListVoices" + ] + }, + "SynthesizeSpeech": { + "methods": [ + "SynthesizeSpeech" + ] + } + } } } } diff --git a/texttospeech/apiv1/text_to_speech_client.go b/texttospeech/apiv1/text_to_speech_client.go index c203cc570f5a..4591d1006b34 100644 --- a/texttospeech/apiv1/text_to_speech_client.go +++ b/texttospeech/apiv1/text_to_speech_client.go @@ -17,18 +17,26 @@ package texttospeech import ( + "bytes" "context" + "fmt" + "io/ioutil" "math" + "net/http" + "net/url" "time" texttospeechpb "cloud.google.com/go/texttospeech/apiv1/texttospeechpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" ) var newClientHook clientHook @@ -80,6 +88,33 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + ListVoices: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + SynthesizeSpeech: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + } +} + // internalClient is an interface that defines the methods available from Cloud Text-to-Speech API. type internalClient interface { Close() error @@ -216,6 +251,74 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new text to speech rest client. +// +// Service that implements Google Cloud Text-to-Speech API. +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://texttospeech.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://texttospeech.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://texttospeech.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) ListVoices(ctx context.Context, req *texttospeechpb.ListVoicesRequest, opts ...gax.CallOption) (*texttospeechpb.ListVoicesResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 300000*time.Millisecond) @@ -255,3 +358,125 @@ func (c *gRPCClient) SynthesizeSpeech(ctx context.Context, req *texttospeechpb.S } return resp, nil } + +// ListVoices returns a list of Voice supported for synthesis. +func (c *restClient) ListVoices(ctx context.Context, req *texttospeechpb.ListVoicesRequest, opts ...gax.CallOption) (*texttospeechpb.ListVoicesResponse, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/voices") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetLanguageCode() != "" { + params.Add("languageCode", fmt.Sprintf("%v", req.GetLanguageCode())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).ListVoices[0:len((*c.CallOptions).ListVoices):len((*c.CallOptions).ListVoices)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &texttospeechpb.ListVoicesResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SynthesizeSpeech synthesizes speech synchronously: receive results after all text input +// has been processed. +func (c *restClient) SynthesizeSpeech(ctx context.Context, req *texttospeechpb.SynthesizeSpeechRequest, opts ...gax.CallOption) (*texttospeechpb.SynthesizeSpeechResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/text:synthesize") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SynthesizeSpeech[0:len((*c.CallOptions).SynthesizeSpeech):len((*c.CallOptions).SynthesizeSpeech)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &texttospeechpb.SynthesizeSpeechResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} diff --git a/texttospeech/apiv1/text_to_speech_client_example_test.go b/texttospeech/apiv1/text_to_speech_client_example_test.go index 0a95844eb0cc..1f10e529859b 100644 --- a/texttospeech/apiv1/text_to_speech_client_example_test.go +++ b/texttospeech/apiv1/text_to_speech_client_example_test.go @@ -40,6 +40,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := texttospeech.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_ListVoices() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/texttospeech/apiv1/texttospeechpb/cloud_tts.pb.go b/texttospeech/apiv1/texttospeechpb/cloud_tts.pb.go index 59c0c1f65390..c32814d36169 100644 --- a/texttospeech/apiv1/texttospeechpb/cloud_tts.pb.go +++ b/texttospeech/apiv1/texttospeechpb/cloud_tts.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/texttospeech/v1/cloud_tts.proto package texttospeechpb @@ -494,7 +494,6 @@ type SynthesisInput struct { // The input source, which is either plain text or SSML. // // Types that are assignable to InputSource: - // // *SynthesisInput_Text // *SynthesisInput_Ssml InputSource isSynthesisInput_InputSource `protobuf_oneof:"input_source"` diff --git a/tpu/apiv1/doc.go b/tpu/apiv1/doc.go index 6e3f9785e48b..870ace88836e 100644 --- a/tpu/apiv1/doc.go +++ b/tpu/apiv1/doc.go @@ -86,6 +86,8 @@ package tpu // import "cloud.google.com/go/tpu/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -174,3 +176,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/tpu/apiv1/gapic_metadata.json b/tpu/apiv1/gapic_metadata.json index 8d0064ef8b4f..60d7c2d4c3cf 100644 --- a/tpu/apiv1/gapic_metadata.json +++ b/tpu/apiv1/gapic_metadata.json @@ -96,6 +96,96 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "CancelOperation": { + "methods": [ + "CancelOperation" + ] + }, + "CreateNode": { + "methods": [ + "CreateNode" + ] + }, + "DeleteNode": { + "methods": [ + "DeleteNode" + ] + }, + "DeleteOperation": { + "methods": [ + "DeleteOperation" + ] + }, + "GetAcceleratorType": { + "methods": [ + "GetAcceleratorType" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "GetNode": { + "methods": [ + "GetNode" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "GetTensorFlowVersion": { + "methods": [ + "GetTensorFlowVersion" + ] + }, + "ListAcceleratorTypes": { + "methods": [ + "ListAcceleratorTypes" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListNodes": { + "methods": [ + "ListNodes" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "ListTensorFlowVersions": { + "methods": [ + "ListTensorFlowVersions" + ] + }, + "ReimageNode": { + "methods": [ + "ReimageNode" + ] + }, + "StartNode": { + "methods": [ + "StartNode" + ] + }, + "StopNode": { + "methods": [ + "StopNode" + ] + } + } } } } diff --git a/tpu/apiv1/tpu_client.go b/tpu/apiv1/tpu_client.go index 36ea84138eb8..c4fb5d3be9aa 100644 --- a/tpu/apiv1/tpu_client.go +++ b/tpu/apiv1/tpu_client.go @@ -17,9 +17,12 @@ package tpu import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,14 +30,17 @@ import ( lroauto "cloud.google.com/go/longrunning/autogen" tpupb "cloud.google.com/go/tpu/apiv1/tpupb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -95,6 +101,28 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + ListNodes: []gax.CallOption{}, + GetNode: []gax.CallOption{}, + CreateNode: []gax.CallOption{}, + DeleteNode: []gax.CallOption{}, + ReimageNode: []gax.CallOption{}, + StopNode: []gax.CallOption{}, + StartNode: []gax.CallOption{}, + ListTensorFlowVersions: []gax.CallOption{}, + GetTensorFlowVersion: []gax.CallOption{}, + ListAcceleratorTypes: []gax.CallOption{}, + GetAcceleratorType: []gax.CallOption{}, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + CancelOperation: []gax.CallOption{}, + DeleteOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalClient is an interface that defines the methods available from Cloud TPU API. type internalClient interface { Close() error @@ -386,6 +414,91 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new tpu rest client. +// +// # Manages TPU nodes and other resources +// +// TPU API v1 +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://tpu.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://tpu.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://tpu.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) ListNodes(ctx context.Context, req *tpupb.ListNodesRequest, opts ...gax.CallOption) *NodeIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -857,161 +970,1365 @@ func (c *gRPCClient) ListOperations(ctx context.Context, req *longrunningpb.List return it } -// CreateNodeOperation manages a long-running operation from CreateNode. -type CreateNodeOperation struct { - lro *longrunning.Operation -} +// ListNodes lists nodes. +func (c *restClient) ListNodes(ctx context.Context, req *tpupb.ListNodesRequest, opts ...gax.CallOption) *NodeIterator { + it := &NodeIterator{} + req = proto.Clone(req).(*tpupb.ListNodesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*tpupb.Node, string, error) { + resp := &tpupb.ListNodesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/nodes", req.GetParent()) -// CreateNodeOperation returns a new CreateNodeOperation from a given name. -// The name must be that of a previously created CreateNodeOperation, possibly from a different process. -func (c *gRPCClient) CreateNodeOperation(name string) *CreateNodeOperation { - return &CreateNodeOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *CreateNodeOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*tpupb.Node, error) { - var resp tpupb.Node - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { - return nil, err + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetNodes(), resp.GetNextPageToken(), nil } - return &resp, nil -} -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *CreateNodeOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*tpupb.Node, error) { - var resp tpupb.Node - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { - return nil, err - } - if !op.Done() { - return nil, 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 } - return &resp, nil + + it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it } -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *CreateNodeOperation) Metadata() (*tpupb.OperationMetadata, error) { - var meta tpupb.OperationMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { +// GetNode gets the details of a node. +func (c *restClient) GetNode(ctx context.Context, req *tpupb.GetNodeRequest, opts ...gax.CallOption) (*tpupb.Node, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - return &meta, nil -} + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) -// Done reports whether the long-running operation has completed. -func (op *CreateNodeOperation) Done() bool { - return op.lro.Done() -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") -// 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 *CreateNodeOperation) Name() string { - return op.lro.Name() -} + baseUrl.RawQuery = params.Encode() -// DeleteNodeOperation manages a long-running operation from DeleteNode. -type DeleteNodeOperation struct { - lro *longrunning.Operation -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) -// DeleteNodeOperation returns a new DeleteNodeOperation from a given name. -// The name must be that of a previously created DeleteNodeOperation, possibly from a different process. -func (c *gRPCClient) DeleteNodeOperation(name string) *DeleteNodeOperation { - return &DeleteNodeOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetNode[0:len((*c.CallOptions).GetNode):len((*c.CallOptions).GetNode)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &tpupb.Node{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e } + return resp, nil } -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *DeleteNodeOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*tpupb.Node, error) { - var resp tpupb.Node - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { +// CreateNode creates a node. +func (c *restClient) CreateNode(ctx context.Context, req *tpupb.CreateNodeRequest, opts ...gax.CallOption) (*CreateNodeOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetNode() + jsonReq, err := m.Marshal(body) + if err != nil { return nil, err } - return &resp, nil -} -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *DeleteNodeOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*tpupb.Node, error) { - var resp tpupb.Node - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - if !op.Done() { - return nil, nil - } - return &resp, nil -} + baseUrl.Path += fmt.Sprintf("/v1/%v/nodes", req.GetParent()) -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *DeleteNodeOperation) Metadata() (*tpupb.OperationMetadata, error) { - var meta tpupb.OperationMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { - return nil, err + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetNodeId() != "" { + params.Add("nodeId", fmt.Sprintf("%v", req.GetNodeId())) } - return &meta, nil -} -// Done reports whether the long-running operation has completed. -func (op *DeleteNodeOperation) Done() bool { - return op.lro.Done() -} + baseUrl.RawQuery = params.Encode() -// 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 *DeleteNodeOperation) Name() string { - return op.lro.Name() -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) -// ReimageNodeOperation manages a long-running operation from ReimageNode. -type ReimageNodeOperation struct { - lro *longrunning.Operation -} + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers -// ReimageNodeOperation returns a new ReimageNodeOperation from a given name. -// The name must be that of a previously created ReimageNodeOperation, possibly from a different process. + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateNodeOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteNode deletes a node. +func (c *restClient) DeleteNode(ctx context.Context, req *tpupb.DeleteNodeRequest, opts ...gax.CallOption) (*DeleteNodeOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteNodeOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ReimageNode reimages a node’s OS. +func (c *restClient) ReimageNode(ctx context.Context, req *tpupb.ReimageNodeRequest, opts ...gax.CallOption) (*ReimageNodeOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:reimage", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &ReimageNodeOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// StopNode stops a node, this operation is only available with single TPU nodes. +func (c *restClient) StopNode(ctx context.Context, req *tpupb.StopNodeRequest, opts ...gax.CallOption) (*StopNodeOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:stop", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &StopNodeOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// StartNode starts a node. +func (c *restClient) StartNode(ctx context.Context, req *tpupb.StartNodeRequest, opts ...gax.CallOption) (*StartNodeOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:start", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &StartNodeOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListTensorFlowVersions list TensorFlow versions supported by this API. +func (c *restClient) ListTensorFlowVersions(ctx context.Context, req *tpupb.ListTensorFlowVersionsRequest, opts ...gax.CallOption) *TensorFlowVersionIterator { + it := &TensorFlowVersionIterator{} + req = proto.Clone(req).(*tpupb.ListTensorFlowVersionsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*tpupb.TensorFlowVersion, string, error) { + resp := &tpupb.ListTensorFlowVersionsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/tensorflowVersions", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetTensorflowVersions(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetTensorFlowVersion gets TensorFlow Version. +func (c *restClient) GetTensorFlowVersion(ctx context.Context, req *tpupb.GetTensorFlowVersionRequest, opts ...gax.CallOption) (*tpupb.TensorFlowVersion, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetTensorFlowVersion[0:len((*c.CallOptions).GetTensorFlowVersion):len((*c.CallOptions).GetTensorFlowVersion)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &tpupb.TensorFlowVersion{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListAcceleratorTypes lists accelerator types supported by this API. +func (c *restClient) ListAcceleratorTypes(ctx context.Context, req *tpupb.ListAcceleratorTypesRequest, opts ...gax.CallOption) *AcceleratorTypeIterator { + it := &AcceleratorTypeIterator{} + req = proto.Clone(req).(*tpupb.ListAcceleratorTypesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*tpupb.AcceleratorType, string, error) { + resp := &tpupb.ListAcceleratorTypesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/acceleratorTypes", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetAcceleratorTypes(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetAcceleratorType gets AcceleratorType. +func (c *restClient) GetAcceleratorType(ctx context.Context, req *tpupb.GetAcceleratorTypeRequest, opts ...gax.CallOption) (*tpupb.AcceleratorType, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetAcceleratorType[0:len((*c.CallOptions).GetAcceleratorType):len((*c.CallOptions).GetAcceleratorType)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &tpupb.AcceleratorType{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetLocation gets information about a location. +func (c *restClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *restClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CancelOperation is a utility method from google.longrunning.Operations. +func (c *restClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// DeleteOperation is a utility method from google.longrunning.Operations. +func (c *restClient) DeleteOperation(ctx context.Context, req *longrunningpb.DeleteOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *restClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *restClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CreateNodeOperation manages a long-running operation from CreateNode. +type CreateNodeOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateNodeOperation returns a new CreateNodeOperation from a given name. +// The name must be that of a previously created CreateNodeOperation, possibly from a different process. +func (c *gRPCClient) CreateNodeOperation(name string) *CreateNodeOperation { + return &CreateNodeOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateNodeOperation returns a new CreateNodeOperation from a given name. +// The name must be that of a previously created CreateNodeOperation, possibly from a different process. +func (c *restClient) CreateNodeOperation(name string) *CreateNodeOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateNodeOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CreateNodeOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*tpupb.Node, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp tpupb.Node + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *CreateNodeOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*tpupb.Node, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp tpupb.Node + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *CreateNodeOperation) Metadata() (*tpupb.OperationMetadata, error) { + var meta tpupb.OperationMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *CreateNodeOperation) Done() bool { + return op.lro.Done() +} + +// 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 *CreateNodeOperation) Name() string { + return op.lro.Name() +} + +// DeleteNodeOperation manages a long-running operation from DeleteNode. +type DeleteNodeOperation struct { + lro *longrunning.Operation + pollPath string +} + +// DeleteNodeOperation returns a new DeleteNodeOperation from a given name. +// The name must be that of a previously created DeleteNodeOperation, possibly from a different process. +func (c *gRPCClient) DeleteNodeOperation(name string) *DeleteNodeOperation { + return &DeleteNodeOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// DeleteNodeOperation returns a new DeleteNodeOperation from a given name. +// The name must be that of a previously created DeleteNodeOperation, possibly from a different process. +func (c *restClient) DeleteNodeOperation(name string) *DeleteNodeOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteNodeOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *DeleteNodeOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*tpupb.Node, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp tpupb.Node + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *DeleteNodeOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*tpupb.Node, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp tpupb.Node + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *DeleteNodeOperation) Metadata() (*tpupb.OperationMetadata, error) { + var meta tpupb.OperationMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *DeleteNodeOperation) Done() bool { + return op.lro.Done() +} + +// 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 *DeleteNodeOperation) Name() string { + return op.lro.Name() +} + +// ReimageNodeOperation manages a long-running operation from ReimageNode. +type ReimageNodeOperation struct { + lro *longrunning.Operation + pollPath string +} + +// ReimageNodeOperation returns a new ReimageNodeOperation from a given name. +// The name must be that of a previously created ReimageNodeOperation, possibly from a different process. func (c *gRPCClient) ReimageNodeOperation(name string) *ReimageNodeOperation { return &ReimageNodeOperation{ lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } +// ReimageNodeOperation returns a new ReimageNodeOperation from a given name. +// The name must be that of a previously created ReimageNodeOperation, possibly from a different process. +func (c *restClient) ReimageNodeOperation(name string) *ReimageNodeOperation { + override := fmt.Sprintf("/v1/%s", name) + return &ReimageNodeOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *ReimageNodeOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*tpupb.Node, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp tpupb.Node if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1029,6 +2346,7 @@ func (op *ReimageNodeOperation) Wait(ctx context.Context, opts ...gax.CallOption // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *ReimageNodeOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*tpupb.Node, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp tpupb.Node if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1066,7 +2384,8 @@ func (op *ReimageNodeOperation) Name() string { // StartNodeOperation manages a long-running operation from StartNode. type StartNodeOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // StartNodeOperation returns a new StartNodeOperation from a given name. @@ -1077,10 +2396,21 @@ func (c *gRPCClient) StartNodeOperation(name string) *StartNodeOperation { } } +// StartNodeOperation returns a new StartNodeOperation from a given name. +// The name must be that of a previously created StartNodeOperation, possibly from a different process. +func (c *restClient) StartNodeOperation(name string) *StartNodeOperation { + override := fmt.Sprintf("/v1/%s", name) + return &StartNodeOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *StartNodeOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*tpupb.Node, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp tpupb.Node if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1098,6 +2428,7 @@ func (op *StartNodeOperation) Wait(ctx context.Context, opts ...gax.CallOption) // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *StartNodeOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*tpupb.Node, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp tpupb.Node if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1135,7 +2466,8 @@ func (op *StartNodeOperation) Name() string { // StopNodeOperation manages a long-running operation from StopNode. type StopNodeOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // StopNodeOperation returns a new StopNodeOperation from a given name. @@ -1146,10 +2478,21 @@ func (c *gRPCClient) StopNodeOperation(name string) *StopNodeOperation { } } +// StopNodeOperation returns a new StopNodeOperation from a given name. +// The name must be that of a previously created StopNodeOperation, possibly from a different process. +func (c *restClient) StopNodeOperation(name string) *StopNodeOperation { + override := fmt.Sprintf("/v1/%s", name) + return &StopNodeOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *StopNodeOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*tpupb.Node, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp tpupb.Node if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1167,6 +2510,7 @@ func (op *StopNodeOperation) Wait(ctx context.Context, opts ...gax.CallOption) ( // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *StopNodeOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*tpupb.Node, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp tpupb.Node if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/tpu/apiv1/tpu_client_example_test.go b/tpu/apiv1/tpu_client_example_test.go index e8119ec62ed2..67e51c821cdf 100644 --- a/tpu/apiv1/tpu_client_example_test.go +++ b/tpu/apiv1/tpu_client_example_test.go @@ -43,6 +43,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := tpu.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_ListNodes() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/tpu/apiv1/tpupb/cloud_tpu.pb.go b/tpu/apiv1/tpupb/cloud_tpu.pb.go index aa404bcd2ae6..38a8cb94bd7e 100644 --- a/tpu/apiv1/tpupb/cloud_tpu.pb.go +++ b/tpu/apiv1/tpupb/cloud_tpu.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/tpu/v1/cloud_tpu.proto package tpupb diff --git a/trace/apiv1/doc.go b/trace/apiv1/doc.go index e696eb0b3475..6504aa43ae98 100644 --- a/trace/apiv1/doc.go +++ b/trace/apiv1/doc.go @@ -90,6 +90,8 @@ package trace // import "cloud.google.com/go/trace/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -180,3 +182,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/trace/apiv1/gapic_metadata.json b/trace/apiv1/gapic_metadata.json index 173594929e90..72374c39364a 100644 --- a/trace/apiv1/gapic_metadata.json +++ b/trace/apiv1/gapic_metadata.json @@ -26,6 +26,26 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "GetTrace": { + "methods": [ + "GetTrace" + ] + }, + "ListTraces": { + "methods": [ + "ListTraces" + ] + }, + "PatchTraces": { + "methods": [ + "PatchTraces" + ] + } + } } } } diff --git a/trace/apiv1/trace_client.go b/trace/apiv1/trace_client.go index cf1a8f453770..f61e70897e7d 100644 --- a/trace/apiv1/trace_client.go +++ b/trace/apiv1/trace_client.go @@ -17,21 +17,27 @@ package trace import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" tracepb "cloud.google.com/go/trace/apiv1/tracepb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -97,6 +103,44 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + ListTraces: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 1000 * time.Millisecond, + Multiplier: 1.20, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + GetTrace: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 1000 * time.Millisecond, + Multiplier: 1.20, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + PatchTraces: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 1000 * time.Millisecond, + Multiplier: 1.20, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + } +} + // internalClient is an interface that defines the methods available from Stackdriver Trace API. type internalClient interface { Close() error @@ -250,6 +294,78 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new trace service rest client. +// +// This file describes an API for collecting and viewing traces and spans +// within a trace. A Trace is a collection of spans corresponding to a single +// operation or set of operations for an application. A span is an individual +// timed event which forms a node of the trace tree. Spans for a single trace +// may span multiple services. +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://cloudtrace.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://cloudtrace.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://cloudtrace.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) ListTraces(ctx context.Context, req *tracepb.ListTracesRequest, opts ...gax.CallOption) *TraceIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "project_id", url.QueryEscape(req.GetProjectId()))) @@ -335,6 +451,226 @@ func (c *gRPCClient) PatchTraces(ctx context.Context, req *tracepb.PatchTracesRe return err } +// ListTraces returns of a list of traces that match the specified filter conditions. +func (c *restClient) ListTraces(ctx context.Context, req *tracepb.ListTracesRequest, opts ...gax.CallOption) *TraceIterator { + it := &TraceIterator{} + req = proto.Clone(req).(*tracepb.ListTracesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*tracepb.Trace, string, error) { + resp := &tracepb.ListTracesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/projects/%v/traces", req.GetProjectId()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetEndTime() != nil { + endTime, err := protojson.Marshal(req.GetEndTime()) + if err != nil { + return nil, "", err + } + params.Add("endTime", string(endTime)) + } + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + if req.GetStartTime() != nil { + startTime, err := protojson.Marshal(req.GetStartTime()) + if err != nil { + return nil, "", err + } + params.Add("startTime", string(startTime)) + } + if req.GetView() != 0 { + params.Add("view", fmt.Sprintf("%v", req.GetView())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetTraces(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetTrace gets a single trace by its ID. +func (c *restClient) GetTrace(ctx context.Context, req *tracepb.GetTraceRequest, opts ...gax.CallOption) (*tracepb.Trace, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/projects/%v/traces/%v", req.GetProjectId(), req.GetTraceId()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "trace_id", url.QueryEscape(req.GetTraceId()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetTrace[0:len((*c.CallOptions).GetTrace):len((*c.CallOptions).GetTrace)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &tracepb.Trace{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// PatchTraces sends new traces to Stackdriver Trace or updates existing traces. If the ID +// of a trace that you send matches that of an existing trace, any fields +// in the existing trace and its spans are overwritten by the provided values, +// and any new fields provided are merged with the existing trace data. If the +// ID does not match, a new trace is created. +func (c *restClient) PatchTraces(ctx context.Context, req *tracepb.PatchTracesRequest, opts ...gax.CallOption) error { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetTraces() + jsonReq, err := m.Marshal(body) + if err != nil { + return err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/projects/%v/traces", req.GetProjectId()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "project_id", url.QueryEscape(req.GetProjectId()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + // TraceIterator manages a stream of *tracepb.Trace. type TraceIterator struct { items []*tracepb.Trace diff --git a/trace/apiv1/trace_client_example_test.go b/trace/apiv1/trace_client_example_test.go index fa292d8f8ddb..f340a7069071 100644 --- a/trace/apiv1/trace_client_example_test.go +++ b/trace/apiv1/trace_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := trace.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_ListTraces() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/trace/apiv1/tracepb/trace.pb.go b/trace/apiv1/tracepb/trace.pb.go index bfc600c32ef7..01e364eb0469 100644 --- a/trace/apiv1/tracepb/trace.pb.go +++ b/trace/apiv1/tracepb/trace.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/devtools/cloudtrace/v1/trace.proto package tracepb @@ -317,10 +317,10 @@ type TraceSpan struct { // Some predefined label keys exist, or you may create your own. When creating // your own, we recommend the following formats: // - // - `/category/product/key` for agents of well-known products (e.g. - // `/db/mongodb/read_size`). - // - `short_host/path/key` for domain-specific keys (e.g. - // `foo.com/myproduct/bar`) + // * `/category/product/key` for agents of well-known products (e.g. + // `/db/mongodb/read_size`). + // * `short_host/path/key` for domain-specific keys (e.g. + // `foo.com/myproduct/bar`) // // Predefined labels include: // @@ -460,39 +460,39 @@ type ListTracesRequest struct { // a plus symbol (`+`) to the search term. // Multiple terms are ANDed. Syntax: // - // - `root:NAME_PREFIX` or `NAME_PREFIX`: Return traces where any root + // * `root:NAME_PREFIX` or `NAME_PREFIX`: Return traces where any root // span starts with `NAME_PREFIX`. - // - `+root:NAME` or `+NAME`: Return traces where any root span's name is + // * `+root:NAME` or `+NAME`: Return traces where any root span's name is // exactly `NAME`. - // - `span:NAME_PREFIX`: Return traces where any span starts with + // * `span:NAME_PREFIX`: Return traces where any span starts with // `NAME_PREFIX`. - // - `+span:NAME`: Return traces where any span's name is exactly + // * `+span:NAME`: Return traces where any span's name is exactly // `NAME`. - // - `latency:DURATION`: Return traces whose overall latency is + // * `latency:DURATION`: Return traces whose overall latency is // greater or equal to than `DURATION`. Accepted units are nanoseconds // (`ns`), milliseconds (`ms`), and seconds (`s`). Default is `ms`. For // example, `latency:24ms` returns traces whose overall latency // is greater than or equal to 24 milliseconds. - // - `label:LABEL_KEY`: Return all traces containing the specified + // * `label:LABEL_KEY`: Return all traces containing the specified // label key (exact match, case-sensitive) regardless of the key:value // pair's value (including empty values). - // - `LABEL_KEY:VALUE_PREFIX`: Return all traces containing the specified + // * `LABEL_KEY:VALUE_PREFIX`: Return all traces containing the specified // label key (exact match, case-sensitive) whose value starts with // `VALUE_PREFIX`. Both a key and a value must be specified. - // - `+LABEL_KEY:VALUE`: Return all traces containing a key:value pair + // * `+LABEL_KEY:VALUE`: Return all traces containing a key:value pair // exactly matching the specified text. Both a key and a value must be // specified. - // - `method:VALUE`: Equivalent to `/http/method:VALUE`. - // - `url:VALUE`: Equivalent to `/http/url:VALUE`. + // * `method:VALUE`: Equivalent to `/http/method:VALUE`. + // * `url:VALUE`: Equivalent to `/http/url:VALUE`. Filter string `protobuf:"bytes,7,opt,name=filter,proto3" json:"filter,omitempty"` // Optional. Field used to sort the returned traces. // Can be one of the following: // - // - `trace_id` - // - `name` (`name` field of root span in the trace) - // - `duration` (difference between `end_time` and `start_time` fields of - // the root span) - // - `start` (`start_time` field of the root span) + // * `trace_id` + // * `name` (`name` field of root span in the trace) + // * `duration` (difference between `end_time` and `start_time` fields of + // the root span) + // * `start` (`start_time` field of the root span) // // Descending order can be specified by appending `desc` to the sort field // (for example, `name desc`). diff --git a/trace/apiv2/doc.go b/trace/apiv2/doc.go index b36528c9be0c..0fc7a91b9cc2 100644 --- a/trace/apiv2/doc.go +++ b/trace/apiv2/doc.go @@ -82,6 +82,8 @@ package trace // import "cloud.google.com/go/trace/apiv2" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -171,3 +173,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/trace/apiv2/gapic_metadata.json b/trace/apiv2/gapic_metadata.json index ef3c8d6d0456..566e48c5cb87 100644 --- a/trace/apiv2/gapic_metadata.json +++ b/trace/apiv2/gapic_metadata.json @@ -21,6 +21,21 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "BatchWriteSpans": { + "methods": [ + "BatchWriteSpans" + ] + }, + "CreateSpan": { + "methods": [ + "CreateSpan" + ] + } + } } } } diff --git a/trace/apiv2/trace_client.go b/trace/apiv2/trace_client.go index 6b803f9d0c49..e65c95b1b1e8 100644 --- a/trace/apiv2/trace_client.go +++ b/trace/apiv2/trace_client.go @@ -17,20 +17,26 @@ package trace import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" tracepb "cloud.google.com/go/trace/apiv2/tracepb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" ) var newClientHook clientHook @@ -71,6 +77,23 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + BatchWriteSpans: []gax.CallOption{}, + CreateSpan: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 1000 * time.Millisecond, + Multiplier: 1.20, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + } +} + // internalClient is an interface that defines the methods available from Stackdriver Trace API. type internalClient interface { Close() error @@ -215,6 +238,78 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new trace service rest client. +// +// This file describes an API for collecting and viewing traces and spans +// within a trace. A Trace is a collection of spans corresponding to a single +// operation or set of operations for an application. A span is an individual +// timed event which forms a node of the trace tree. A single trace may +// contain span(s) from multiple services. +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://cloudtrace.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://cloudtrace.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://cloudtrace.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) BatchWriteSpans(ctx context.Context, req *tracepb.BatchWriteSpansRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 120000*time.Millisecond) @@ -254,3 +349,114 @@ func (c *gRPCClient) CreateSpan(ctx context.Context, req *tracepb.Span, opts ... } return resp, nil } + +// BatchWriteSpans sends new spans to new or existing traces. You cannot update +// existing spans. +func (c *restClient) BatchWriteSpans(ctx context.Context, req *tracepb.BatchWriteSpansRequest, opts ...gax.CallOption) error { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v2/%v/traces:batchWrite", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// CreateSpan creates a new span. +func (c *restClient) CreateSpan(ctx context.Context, req *tracepb.Span, opts ...gax.CallOption) (*tracepb.Span, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v2/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateSpan[0:len((*c.CallOptions).CreateSpan):len((*c.CallOptions).CreateSpan)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &tracepb.Span{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} diff --git a/trace/apiv2/trace_client_example_test.go b/trace/apiv2/trace_client_example_test.go index 50b50eef4e18..eec66398cde7 100644 --- a/trace/apiv2/trace_client_example_test.go +++ b/trace/apiv2/trace_client_example_test.go @@ -40,6 +40,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := trace.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_BatchWriteSpans() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/trace/apiv2/tracepb/trace.pb.go b/trace/apiv2/tracepb/trace.pb.go index d855a6f6dd25..9538bc844a1d 100644 --- a/trace/apiv2/tracepb/trace.pb.go +++ b/trace/apiv2/tracepb/trace.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/devtools/cloudtrace/v2/trace.proto package tracepb @@ -234,7 +234,7 @@ type Span struct { // Required. The resource name of the span in the following format: // - // projects/[PROJECT_ID]/traces/[TRACE_ID]/spans/[SPAN_ID] + // projects/[PROJECT_ID]/traces/[TRACE_ID]/spans/[SPAN_ID] // // [TRACE_ID] is a unique identifier for a trace within a project; // it is a 32-character hexadecimal encoding of a 16-byte array. @@ -428,7 +428,6 @@ type AttributeValue struct { // The type of the value. // // Types that are assignable to Value: - // // *AttributeValue_StringValue // *AttributeValue_IntValue // *AttributeValue_BoolValue @@ -721,9 +720,9 @@ type Span_Attributes struct { // long. The value can be a string up to 256 bytes, a signed 64-bit integer, // or the Boolean values `true` and `false`. For example: // - // "/instance_id": { "string_value": { "value": "my-instance" } } - // "/http/request_bytes": { "int_value": 300 } - // "abc.com/myattribute": { "bool_value": false } + // "/instance_id": { "string_value": { "value": "my-instance" } } + // "/http/request_bytes": { "int_value": 300 } + // "abc.com/myattribute": { "bool_value": false } AttributeMap map[string]*AttributeValue `protobuf:"bytes,1,rep,name=attribute_map,json=attributeMap,proto3" json:"attribute_map,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` // The number of attributes that were discarded. Attributes can be discarded // because their keys are too long or because there are too many attributes. @@ -789,7 +788,6 @@ type Span_TimeEvent struct { // `MessageEvent` object, but not both. // // Types that are assignable to Value: - // // *Span_TimeEvent_Annotation_ // *Span_TimeEvent_MessageEvent_ Value isSpan_TimeEvent_Value `protobuf_oneof:"value"` diff --git a/trace/apiv2/tracepb/tracing.pb.go b/trace/apiv2/tracepb/tracing.pb.go index 47b8d0fc0c80..970b2efe9daf 100644 --- a/trace/apiv2/tracepb/tracing.pb.go +++ b/trace/apiv2/tracepb/tracing.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/devtools/cloudtrace/v2/tracing.proto package tracepb diff --git a/translate/apiv3/doc.go b/translate/apiv3/doc.go index 6c8bf1c30c5b..bfe4a4c1ec75 100644 --- a/translate/apiv3/doc.go +++ b/translate/apiv3/doc.go @@ -80,6 +80,8 @@ package translate // import "cloud.google.com/go/translate/apiv3" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -169,3 +171,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/translate/apiv3/gapic_metadata.json b/translate/apiv3/gapic_metadata.json index 4608562e63e1..844b3c6680a0 100644 --- a/translate/apiv3/gapic_metadata.json +++ b/translate/apiv3/gapic_metadata.json @@ -61,6 +61,61 @@ ] } } + }, + "rest": { + "libraryClient": "TranslationClient", + "rpcs": { + "BatchTranslateDocument": { + "methods": [ + "BatchTranslateDocument" + ] + }, + "BatchTranslateText": { + "methods": [ + "BatchTranslateText" + ] + }, + "CreateGlossary": { + "methods": [ + "CreateGlossary" + ] + }, + "DeleteGlossary": { + "methods": [ + "DeleteGlossary" + ] + }, + "DetectLanguage": { + "methods": [ + "DetectLanguage" + ] + }, + "GetGlossary": { + "methods": [ + "GetGlossary" + ] + }, + "GetSupportedLanguages": { + "methods": [ + "GetSupportedLanguages" + ] + }, + "ListGlossaries": { + "methods": [ + "ListGlossaries" + ] + }, + "TranslateDocument": { + "methods": [ + "TranslateDocument" + ] + }, + "TranslateText": { + "methods": [ + "TranslateText" + ] + } + } } } } diff --git a/translate/apiv3/translatepb/translation_service.pb.go b/translate/apiv3/translatepb/translation_service.pb.go index c1b65740a439..6e4c5d638bf5 100644 --- a/translate/apiv3/translatepb/translation_service.pb.go +++ b/translate/apiv3/translatepb/translation_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/translate/v3/translation_service.proto package translatepb @@ -322,8 +322,8 @@ type TranslateTextGlossaryConfig struct { // // The format depends on glossary: // - // - User provided custom glossary: - // `projects/{project-number-or-id}/locations/{location-id}/glossaries/{glossary-id}` + // - User provided custom glossary: + // `projects/{project-number-or-id}/locations/{location-id}/glossaries/{glossary-id}` Glossary string `protobuf:"bytes,1,opt,name=glossary,proto3" json:"glossary,omitempty"` // Optional. Indicates match is case-insensitive. // Default value is false if missing. @@ -388,8 +388,7 @@ type TranslateTextRequest struct { // Use BatchTranslateText for larger text. Contents []string `protobuf:"bytes,1,rep,name=contents,proto3" json:"contents,omitempty"` // Optional. The format of the source text, for example, "text/html", - // - // "text/plain". If left blank, the MIME type defaults to "text/html". + // "text/plain". If left blank, the MIME type defaults to "text/html". MimeType string `protobuf:"bytes,3,opt,name=mime_type,json=mimeType,proto3" json:"mime_type,omitempty"` // Optional. The BCP-47 language code of the input text if // known, for example, "en-US" or "sr-Latn". Supported language codes are @@ -419,11 +418,12 @@ type TranslateTextRequest struct { // // The format depends on model type: // - // - AutoML Translation models: - // `projects/{project-number-or-id}/locations/{location-id}/models/{model-id}` + // - AutoML Translation models: + // `projects/{project-number-or-id}/locations/{location-id}/models/{model-id}` + // + // - General (built-in) models: + // `projects/{project-number-or-id}/locations/{location-id}/models/general/nmt`, // - // - General (built-in) models: - // `projects/{project-number-or-id}/locations/{location-id}/models/general/nmt`, // // For global (non-regionalized) requests, use `location-id` `global`. // For example, @@ -717,7 +717,6 @@ type DetectLanguageRequest struct { // Required. The source of the document from which to detect the language. // // Types that are assignable to Source: - // // *DetectLanguageRequest_Content Source isDetectLanguageRequest_Source `protobuf_oneof:"source"` // Optional. The format of the source text, for example, "text/html", @@ -957,11 +956,12 @@ type GetSupportedLanguagesRequest struct { // // The format depends on model type: // - // - AutoML Translation models: - // `projects/{project-number-or-id}/locations/{location-id}/models/{model-id}` + // - AutoML Translation models: + // `projects/{project-number-or-id}/locations/{location-id}/models/{model-id}` + // + // - General (built-in) models: + // `projects/{project-number-or-id}/locations/{location-id}/models/general/nmt`, // - // - General (built-in) models: - // `projects/{project-number-or-id}/locations/{location-id}/models/general/nmt`, // // Returns languages supported by the specified model. // If missing, we get supported languages of Google general NMT model. @@ -1215,7 +1215,6 @@ type InputConfig struct { // Required. Specify the input. // // Types that are assignable to Source: - // // *InputConfig_GcsSource Source isInputConfig_Source `protobuf_oneof:"source"` } @@ -1286,9 +1285,7 @@ type InputConfig_GcsSource struct { // of the text request. If the first column is missing, we use the row // number (0-based) from the input file as the ID in the output file. The // second column is the actual text to be - // - // translated. We recommend each row be <= 10K Unicode codepoints, - // + // translated. We recommend each row be <= 10K Unicode codepoints, // otherwise an error might be returned. // Note that the input tsv must be RFC 4180 compliant. // @@ -1365,7 +1362,6 @@ type OutputConfig struct { // Required. The destination of output. // // Types that are assignable to Destination: - // // *OutputConfig_GcsDestination Destination isOutputConfig_Destination `protobuf_oneof:"destination"` } @@ -1512,7 +1508,6 @@ type DocumentInputConfig struct { // - application/pdf // // Types that are assignable to Source: - // // *DocumentInputConfig_Content // *DocumentInputConfig_GcsSource Source isDocumentInputConfig_Source `protobuf_oneof:"source"` @@ -1622,7 +1617,6 @@ type DocumentOutputConfig struct { // TranslateDocumentResponse.glossary_document_translation. // // Types that are assignable to Destination: - // // *DocumentOutputConfig_GcsDestination Destination isDocumentOutputConfig_Destination `protobuf_oneof:"destination"` // Optional. Specifies the translated document's mime_type. @@ -1708,6 +1702,7 @@ type DocumentOutputConfig_GcsDestination struct { // - [ext] corresponds to the translated file's extension according to its // mime type. // + // // For a DocumentInputConfig.gcs_uri provided document, the output file will // have a name according to its URI. For example: an input file with URI: // "gs://a/b/c.[extension]" stored in a gcs_destination bucket with name @@ -1717,6 +1712,7 @@ type DocumentOutputConfig_GcsDestination struct { // - [ext] corresponds to the translated file's extension according to its // mime type. // + // // If the document was directly provided through the request, then the // output document will have the format: // "gs://my_bucket/translated_document_[trg]_translations.[ext], where @@ -1782,11 +1778,12 @@ type TranslateDocumentRequest struct { // // The format depends on model type: // - // - AutoML Translation models: - // `projects/{project-number-or-id}/locations/{location-id}/models/{model-id}` + // - AutoML Translation models: + // `projects/{project-number-or-id}/locations/{location-id}/models/{model-id}` + // + // - General (built-in) models: + // `projects/{project-number-or-id}/locations/{location-id}/models/general/nmt`, // - // - General (built-in) models: - // `projects/{project-number-or-id}/locations/{location-id}/models/general/nmt`, // // If not provided, the default Google model (NMT) will be used for // translation. @@ -2079,11 +2076,12 @@ type BatchTranslateTextRequest struct { // // The value format depends on model type: // - // - AutoML Translation models: - // `projects/{project-number-or-id}/locations/{location-id}/models/{model-id}` + // - AutoML Translation models: + // `projects/{project-number-or-id}/locations/{location-id}/models/{model-id}` + // + // - General (built-in) models: + // `projects/{project-number-or-id}/locations/{location-id}/models/general/nmt`, // - // - General (built-in) models: - // `projects/{project-number-or-id}/locations/{location-id}/models/general/nmt`, // // If the map is empty or a specific model is // not requested for a language pair, then default google model (nmt) is used. @@ -2387,7 +2385,6 @@ type GlossaryInputConfig struct { // Required. Specify the input. // // Types that are assignable to Source: - // // *GlossaryInputConfig_GcsSource Source isGlossaryInputConfig_Source `protobuf_oneof:"source"` } @@ -2451,19 +2448,19 @@ type GlossaryInputConfig_GcsSource struct { // // For unidirectional glossaries: // - // - TSV/CSV (`.tsv`/`.csv`): 2 column file, tab- or comma-separated. - // The first column is source text. The second column is target text. - // The file must not contain headers. That is, the first row is data, not - // column names. + // - TSV/CSV (`.tsv`/`.csv`): 2 column file, tab- or comma-separated. + // The first column is source text. The second column is target text. + // The file must not contain headers. That is, the first row is data, not + // column names. // // - TMX (`.tmx`): TMX file with parallel data defining source/target term // pairs. // // For equivalent term sets glossaries: // - // - CSV (`.csv`): Multi-column CSV file defining equivalent glossary terms - // in multiple languages. See documentation for more information - - // [glossaries](https://cloud.google.com/translate/docs/advanced/glossary). + // - CSV (`.csv`): Multi-column CSV file defining equivalent glossary terms + // in multiple languages. See documentation for more information - + // [glossaries](https://cloud.google.com/translate/docs/advanced/glossary). GcsSource *GcsSource `protobuf:"bytes,1,opt,name=gcs_source,json=gcsSource,proto3,oneof"` } @@ -2481,7 +2478,6 @@ type Glossary struct { // Languages supported by the glossary. // // Types that are assignable to Languages: - // // *Glossary_LanguagePair // *Glossary_LanguageCodesSet_ Languages isGlossary_Languages `protobuf_oneof:"languages"` @@ -3160,11 +3156,12 @@ type BatchTranslateDocumentRequest struct { // // The value format depends on model type: // - // - AutoML Translation models: - // `projects/{project-number-or-id}/locations/{location-id}/models/{model-id}` + // - AutoML Translation models: + // `projects/{project-number-or-id}/locations/{location-id}/models/{model-id}` + // + // - General (built-in) models: + // `projects/{project-number-or-id}/locations/{location-id}/models/general/nmt`, // - // - General (built-in) models: - // `projects/{project-number-or-id}/locations/{location-id}/models/general/nmt`, // // If the map is empty or a specific model is // not requested for a language pair, then default google model (nmt) is used. @@ -3176,8 +3173,8 @@ type BatchTranslateDocumentRequest struct { // translated documents. // // Supported file format conversion includes: - // - `application/pdf` to - // `application/vnd.openxmlformats-officedocument.wordprocessingml.document` + // - `application/pdf` to + // `application/vnd.openxmlformats-officedocument.wordprocessingml.document` // // If nothing specified, output files will be in the same format as the // original file. @@ -3281,7 +3278,6 @@ type BatchDocumentInputConfig struct { // Specify the input. // // Types that are assignable to Source: - // // *BatchDocumentInputConfig_GcsSource Source isBatchDocumentInputConfig_Source `protobuf_oneof:"source"` } @@ -3371,7 +3367,6 @@ type BatchDocumentOutputConfig struct { // and be empty. // // Types that are assignable to Destination: - // // *BatchDocumentOutputConfig_GcsDestination Destination isBatchDocumentOutputConfig_Destination `protobuf_oneof:"destination"` } diff --git a/translate/apiv3/translation_client.go b/translate/apiv3/translation_client.go index c4cff11715bd..1ac423acb48e 100644 --- a/translate/apiv3/translation_client.go +++ b/translate/apiv3/translation_client.go @@ -17,9 +17,12 @@ package translate import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,14 +30,17 @@ import ( lroauto "cloud.google.com/go/longrunning/autogen" translatepb "cloud.google.com/go/translate/apiv3/translatepb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -125,6 +131,61 @@ func defaultTranslationCallOptions() *TranslationCallOptions { } } +func defaultTranslationRESTCallOptions() *TranslationCallOptions { + return &TranslationCallOptions{ + TranslateText: []gax.CallOption{}, + DetectLanguage: []gax.CallOption{}, + GetSupportedLanguages: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + TranslateDocument: []gax.CallOption{}, + BatchTranslateText: []gax.CallOption{}, + BatchTranslateDocument: []gax.CallOption{}, + CreateGlossary: []gax.CallOption{}, + ListGlossaries: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + GetGlossary: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + DeleteGlossary: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + } +} + // internalTranslationClient is an interface that defines the methods available from Cloud Translation API. type internalTranslationClient interface { Close() error @@ -374,6 +435,89 @@ func (c *translationGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type translationRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing TranslationClient + CallOptions **TranslationCallOptions +} + +// NewTranslationRESTClient creates a new translation service rest client. +// +// Provides natural language translation operations. +func NewTranslationRESTClient(ctx context.Context, opts ...option.ClientOption) (*TranslationClient, error) { + clientOpts := append(defaultTranslationRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultTranslationRESTCallOptions() + c := &translationRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &TranslationClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultTranslationRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://translate.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://translate.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://translate.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *translationRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *translationRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *translationRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *translationGRPCClient) TranslateText(ctx context.Context, req *translatepb.TranslateTextRequest, opts ...gax.CallOption) (*translatepb.TranslateTextResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) @@ -625,9 +769,699 @@ func (c *translationGRPCClient) DeleteGlossary(ctx context.Context, req *transla }, nil } +// TranslateText translates input text and returns translated text. +func (c *translationRESTClient) TranslateText(ctx context.Context, req *translatepb.TranslateTextRequest, opts ...gax.CallOption) (*translatepb.TranslateTextResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v:translateText", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).TranslateText[0:len((*c.CallOptions).TranslateText):len((*c.CallOptions).TranslateText)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &translatepb.TranslateTextResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DetectLanguage detects the language of text within a request. +func (c *translationRESTClient) DetectLanguage(ctx context.Context, req *translatepb.DetectLanguageRequest, opts ...gax.CallOption) (*translatepb.DetectLanguageResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v:detectLanguage", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).DetectLanguage[0:len((*c.CallOptions).DetectLanguage):len((*c.CallOptions).DetectLanguage)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &translatepb.DetectLanguageResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetSupportedLanguages returns a list of supported languages for translation. +func (c *translationRESTClient) GetSupportedLanguages(ctx context.Context, req *translatepb.GetSupportedLanguagesRequest, opts ...gax.CallOption) (*translatepb.SupportedLanguages, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/supportedLanguages", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetDisplayLanguageCode() != "" { + params.Add("displayLanguageCode", fmt.Sprintf("%v", req.GetDisplayLanguageCode())) + } + if req.GetModel() != "" { + params.Add("model", fmt.Sprintf("%v", req.GetModel())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetSupportedLanguages[0:len((*c.CallOptions).GetSupportedLanguages):len((*c.CallOptions).GetSupportedLanguages)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &translatepb.SupportedLanguages{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// TranslateDocument translates documents in synchronous mode. +func (c *translationRESTClient) TranslateDocument(ctx context.Context, req *translatepb.TranslateDocumentRequest, opts ...gax.CallOption) (*translatepb.TranslateDocumentResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v:translateDocument", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).TranslateDocument[0:len((*c.CallOptions).TranslateDocument):len((*c.CallOptions).TranslateDocument)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &translatepb.TranslateDocumentResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// BatchTranslateText translates a large volume of text in asynchronous batch mode. +// This function provides real-time output as the inputs are being processed. +// If caller cancels a request, the partial results (for an input file, it’s +// all or nothing) may still be available on the specified output location. +// +// This call returns immediately and you can +// use google.longrunning.Operation.name (at http://google.longrunning.Operation.name) to poll the status of the call. +func (c *translationRESTClient) BatchTranslateText(ctx context.Context, req *translatepb.BatchTranslateTextRequest, opts ...gax.CallOption) (*BatchTranslateTextOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v:batchTranslateText", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v3/%s", resp.GetName()) + return &BatchTranslateTextOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// BatchTranslateDocument translates a large volume of document in asynchronous batch mode. +// This function provides real-time output as the inputs are being processed. +// If caller cancels a request, the partial results (for an input file, it’s +// all or nothing) may still be available on the specified output location. +// +// This call returns immediately and you can use +// google.longrunning.Operation.name (at http://google.longrunning.Operation.name) to poll the status of the call. +func (c *translationRESTClient) BatchTranslateDocument(ctx context.Context, req *translatepb.BatchTranslateDocumentRequest, opts ...gax.CallOption) (*BatchTranslateDocumentOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v:batchTranslateDocument", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v3/%s", resp.GetName()) + return &BatchTranslateDocumentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// CreateGlossary creates a glossary and returns the long-running operation. Returns +// NOT_FOUND, if the project doesn’t exist. +func (c *translationRESTClient) CreateGlossary(ctx context.Context, req *translatepb.CreateGlossaryRequest, opts ...gax.CallOption) (*CreateGlossaryOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetGlossary() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/glossaries", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v3/%s", resp.GetName()) + return &CreateGlossaryOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListGlossaries lists glossaries in a project. Returns NOT_FOUND, if the project doesn’t +// exist. +func (c *translationRESTClient) ListGlossaries(ctx context.Context, req *translatepb.ListGlossariesRequest, opts ...gax.CallOption) *GlossaryIterator { + it := &GlossaryIterator{} + req = proto.Clone(req).(*translatepb.ListGlossariesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*translatepb.Glossary, string, error) { + resp := &translatepb.ListGlossariesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v3/%v/glossaries", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetGlossaries(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetGlossary gets a glossary. Returns NOT_FOUND, if the glossary doesn’t +// exist. +func (c *translationRESTClient) GetGlossary(ctx context.Context, req *translatepb.GetGlossaryRequest, opts ...gax.CallOption) (*translatepb.Glossary, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetGlossary[0:len((*c.CallOptions).GetGlossary):len((*c.CallOptions).GetGlossary)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &translatepb.Glossary{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteGlossary deletes a glossary, or cancels glossary construction +// if the glossary isn’t created yet. +// Returns NOT_FOUND, if the glossary doesn’t exist. +func (c *translationRESTClient) DeleteGlossary(ctx context.Context, req *translatepb.DeleteGlossaryRequest, opts ...gax.CallOption) (*DeleteGlossaryOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v3/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v3/%s", resp.GetName()) + return &DeleteGlossaryOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + // BatchTranslateDocumentOperation manages a long-running operation from BatchTranslateDocument. type BatchTranslateDocumentOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // BatchTranslateDocumentOperation returns a new BatchTranslateDocumentOperation from a given name. @@ -638,10 +1472,21 @@ func (c *translationGRPCClient) BatchTranslateDocumentOperation(name string) *Ba } } +// BatchTranslateDocumentOperation returns a new BatchTranslateDocumentOperation from a given name. +// The name must be that of a previously created BatchTranslateDocumentOperation, possibly from a different process. +func (c *translationRESTClient) BatchTranslateDocumentOperation(name string) *BatchTranslateDocumentOperation { + override := fmt.Sprintf("/v3/%s", name) + return &BatchTranslateDocumentOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *BatchTranslateDocumentOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*translatepb.BatchTranslateDocumentResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp translatepb.BatchTranslateDocumentResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -659,6 +1504,7 @@ func (op *BatchTranslateDocumentOperation) Wait(ctx context.Context, opts ...gax // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *BatchTranslateDocumentOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*translatepb.BatchTranslateDocumentResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp translatepb.BatchTranslateDocumentResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -696,7 +1542,8 @@ func (op *BatchTranslateDocumentOperation) Name() string { // BatchTranslateTextOperation manages a long-running operation from BatchTranslateText. type BatchTranslateTextOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // BatchTranslateTextOperation returns a new BatchTranslateTextOperation from a given name. @@ -707,10 +1554,21 @@ func (c *translationGRPCClient) BatchTranslateTextOperation(name string) *BatchT } } +// BatchTranslateTextOperation returns a new BatchTranslateTextOperation from a given name. +// The name must be that of a previously created BatchTranslateTextOperation, possibly from a different process. +func (c *translationRESTClient) BatchTranslateTextOperation(name string) *BatchTranslateTextOperation { + override := fmt.Sprintf("/v3/%s", name) + return &BatchTranslateTextOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *BatchTranslateTextOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*translatepb.BatchTranslateResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp translatepb.BatchTranslateResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -728,6 +1586,7 @@ func (op *BatchTranslateTextOperation) Wait(ctx context.Context, opts ...gax.Cal // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *BatchTranslateTextOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*translatepb.BatchTranslateResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp translatepb.BatchTranslateResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -765,7 +1624,8 @@ func (op *BatchTranslateTextOperation) Name() string { // CreateGlossaryOperation manages a long-running operation from CreateGlossary. type CreateGlossaryOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateGlossaryOperation returns a new CreateGlossaryOperation from a given name. @@ -776,10 +1636,21 @@ func (c *translationGRPCClient) CreateGlossaryOperation(name string) *CreateGlos } } +// CreateGlossaryOperation returns a new CreateGlossaryOperation from a given name. +// The name must be that of a previously created CreateGlossaryOperation, possibly from a different process. +func (c *translationRESTClient) CreateGlossaryOperation(name string) *CreateGlossaryOperation { + override := fmt.Sprintf("/v3/%s", name) + return &CreateGlossaryOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateGlossaryOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*translatepb.Glossary, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp translatepb.Glossary if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -797,6 +1668,7 @@ func (op *CreateGlossaryOperation) Wait(ctx context.Context, opts ...gax.CallOpt // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateGlossaryOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*translatepb.Glossary, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp translatepb.Glossary if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -834,7 +1706,8 @@ func (op *CreateGlossaryOperation) Name() string { // DeleteGlossaryOperation manages a long-running operation from DeleteGlossary. type DeleteGlossaryOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteGlossaryOperation returns a new DeleteGlossaryOperation from a given name. @@ -845,10 +1718,21 @@ func (c *translationGRPCClient) DeleteGlossaryOperation(name string) *DeleteGlos } } +// DeleteGlossaryOperation returns a new DeleteGlossaryOperation from a given name. +// The name must be that of a previously created DeleteGlossaryOperation, possibly from a different process. +func (c *translationRESTClient) DeleteGlossaryOperation(name string) *DeleteGlossaryOperation { + override := fmt.Sprintf("/v3/%s", name) + return &DeleteGlossaryOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteGlossaryOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*translatepb.DeleteGlossaryResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp translatepb.DeleteGlossaryResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -866,6 +1750,7 @@ func (op *DeleteGlossaryOperation) Wait(ctx context.Context, opts ...gax.CallOpt // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteGlossaryOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*translatepb.DeleteGlossaryResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp translatepb.DeleteGlossaryResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/translate/apiv3/translation_client_example_test.go b/translate/apiv3/translation_client_example_test.go index 5ca793342ca0..2027efd58237 100644 --- a/translate/apiv3/translation_client_example_test.go +++ b/translate/apiv3/translation_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewTranslationClient() { _ = c } +func ExampleNewTranslationRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := translate.NewTranslationRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleTranslationClient_TranslateText() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/video/livestream/apiv1/doc.go b/video/livestream/apiv1/doc.go index b2b0b8b9b5a9..391e96c178b8 100644 --- a/video/livestream/apiv1/doc.go +++ b/video/livestream/apiv1/doc.go @@ -83,6 +83,8 @@ package livestream // import "cloud.google.com/go/video/livestream/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -171,3 +173,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/video/livestream/apiv1/gapic_metadata.json b/video/livestream/apiv1/gapic_metadata.json index 8fcbc832eb35..b7a10c1be224 100644 --- a/video/livestream/apiv1/gapic_metadata.json +++ b/video/livestream/apiv1/gapic_metadata.json @@ -91,6 +91,91 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "CreateChannel": { + "methods": [ + "CreateChannel" + ] + }, + "CreateEvent": { + "methods": [ + "CreateEvent" + ] + }, + "CreateInput": { + "methods": [ + "CreateInput" + ] + }, + "DeleteChannel": { + "methods": [ + "DeleteChannel" + ] + }, + "DeleteEvent": { + "methods": [ + "DeleteEvent" + ] + }, + "DeleteInput": { + "methods": [ + "DeleteInput" + ] + }, + "GetChannel": { + "methods": [ + "GetChannel" + ] + }, + "GetEvent": { + "methods": [ + "GetEvent" + ] + }, + "GetInput": { + "methods": [ + "GetInput" + ] + }, + "ListChannels": { + "methods": [ + "ListChannels" + ] + }, + "ListEvents": { + "methods": [ + "ListEvents" + ] + }, + "ListInputs": { + "methods": [ + "ListInputs" + ] + }, + "StartChannel": { + "methods": [ + "StartChannel" + ] + }, + "StopChannel": { + "methods": [ + "StopChannel" + ] + }, + "UpdateChannel": { + "methods": [ + "UpdateChannel" + ] + }, + "UpdateInput": { + "methods": [ + "UpdateInput" + ] + } + } } } } diff --git a/video/livestream/apiv1/livestream_client.go b/video/livestream/apiv1/livestream_client.go index fff97e5e6334..df1c3b502aa6 100644 --- a/video/livestream/apiv1/livestream_client.go +++ b/video/livestream/apiv1/livestream_client.go @@ -17,9 +17,12 @@ package livestream import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,14 +30,17 @@ import ( lroauto "cloud.google.com/go/longrunning/autogen" livestreampb "cloud.google.com/go/video/livestream/apiv1/livestreampb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -153,6 +159,81 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + CreateChannel: []gax.CallOption{}, + ListChannels: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetChannel: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeleteChannel: []gax.CallOption{}, + UpdateChannel: []gax.CallOption{}, + StartChannel: []gax.CallOption{}, + StopChannel: []gax.CallOption{}, + CreateInput: []gax.CallOption{}, + ListInputs: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetInput: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeleteInput: []gax.CallOption{}, + UpdateInput: []gax.CallOption{}, + CreateEvent: []gax.CallOption{}, + ListEvents: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetEvent: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + DeleteEvent: []gax.CallOption{}, + } +} + // internalClient is an interface that defines the methods available from Live Stream API. type internalClient interface { Close() error @@ -460,6 +541,93 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new livestream service rest client. +// +// Using Live Stream API, you can generate live streams in the various +// renditions and streaming formats. The streaming format include HTTP Live +// Streaming (HLS) and Dynamic Adaptive Streaming over HTTP (DASH). You can send +// a source stream in the various ways, including Real-Time Messaging +// Protocol (RTMP) and Secure Reliable Transport (SRT). +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://livestream.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://livestream.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://livestream.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) CreateChannel(ctx context.Context, req *livestreampb.CreateChannelRequest, opts ...gax.CallOption) (*CreateChannelOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) @@ -893,102 +1061,1271 @@ func (c *gRPCClient) DeleteEvent(ctx context.Context, req *livestreampb.DeleteEv return err } -// CreateChannelOperation manages a long-running operation from CreateChannel. -type CreateChannelOperation struct { - lro *longrunning.Operation -} - -// CreateChannelOperation returns a new CreateChannelOperation from a given name. -// The name must be that of a previously created CreateChannelOperation, possibly from a different process. -func (c *gRPCClient) CreateChannelOperation(name string) *CreateChannelOperation { - return &CreateChannelOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} - -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *CreateChannelOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*livestreampb.Channel, error) { - var resp livestreampb.Channel - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { +// CreateChannel creates a channel with the provided unique ID in the specified +// region. +func (c *restClient) CreateChannel(ctx context.Context, req *livestreampb.CreateChannelRequest, opts ...gax.CallOption) (*CreateChannelOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetChannel() + jsonReq, err := m.Marshal(body) + if err != nil { return nil, err } - return &resp, nil -} -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *CreateChannelOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*livestreampb.Channel, error) { - var resp livestreampb.Channel - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - if !op.Done() { - return nil, nil + baseUrl.Path += fmt.Sprintf("/v1/%v/channels", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("channelId", fmt.Sprintf("%v", req.GetChannelId())) + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } - return &resp, nil -} -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *CreateChannelOperation) Metadata() (*livestreampb.OperationMetadata, error) { - var meta livestreampb.OperationMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { - return nil, err + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e } - return &meta, nil -} -// Done reports whether the long-running operation has completed. -func (op *CreateChannelOperation) Done() bool { - return op.lro.Done() + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateChannelOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil } -// 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 *CreateChannelOperation) Name() string { - return op.lro.Name() -} +// ListChannels returns a list of all channels in the specified region. +func (c *restClient) ListChannels(ctx context.Context, req *livestreampb.ListChannelsRequest, opts ...gax.CallOption) *ChannelIterator { + it := &ChannelIterator{} + req = proto.Clone(req).(*livestreampb.ListChannelsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*livestreampb.Channel, string, error) { + resp := &livestreampb.ListChannelsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/channels", req.GetParent()) -// CreateInputOperation manages a long-running operation from CreateInput. -type CreateInputOperation struct { - lro *longrunning.Operation -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } -// CreateInputOperation returns a new CreateInputOperation from a given name. -// The name must be that of a previously created CreateInputOperation, possibly from a different process. -func (c *gRPCClient) CreateInputOperation(name string) *CreateInputOperation { - return &CreateInputOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetChannels(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it } -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *CreateInputOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*livestreampb.Input, error) { - var resp livestreampb.Input - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { +// GetChannel returns the specified channel. +func (c *restClient) GetChannel(ctx context.Context, req *livestreampb.GetChannelRequest, opts ...gax.CallOption) (*livestreampb.Channel, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - return &resp, nil -} + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetChannel[0:len((*c.CallOptions).GetChannel):len((*c.CallOptions).GetChannel)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &livestreampb.Channel{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteChannel deletes the specified channel. +func (c *restClient) DeleteChannel(ctx context.Context, req *livestreampb.DeleteChannelRequest, opts ...gax.CallOption) (*DeleteChannelOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetForce() { + params.Add("force", fmt.Sprintf("%v", req.GetForce())) + } + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteChannelOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateChannel updates the specified channel. +func (c *restClient) UpdateChannel(ctx context.Context, req *livestreampb.UpdateChannelRequest, opts ...gax.CallOption) (*UpdateChannelOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetChannel() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetChannel().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "channel.name", url.QueryEscape(req.GetChannel().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateChannelOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// StartChannel starts the specified channel. Part of the video pipeline will be created +// only when the StartChannel request is received by the server. +func (c *restClient) StartChannel(ctx context.Context, req *livestreampb.StartChannelRequest, opts ...gax.CallOption) (*StartChannelOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:start", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &StartChannelOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// StopChannel stops the specified channel. Part of the video pipeline will be released +// when the StopChannel request is received by the server. +func (c *restClient) StopChannel(ctx context.Context, req *livestreampb.StopChannelRequest, opts ...gax.CallOption) (*StopChannelOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:stop", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &StopChannelOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// CreateInput creates an input with the provided unique ID in the specified region. +func (c *restClient) CreateInput(ctx context.Context, req *livestreampb.CreateInputRequest, opts ...gax.CallOption) (*CreateInputOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetInput() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/inputs", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("inputId", fmt.Sprintf("%v", req.GetInputId())) + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateInputOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListInputs returns a list of all inputs in the specified region. +func (c *restClient) ListInputs(ctx context.Context, req *livestreampb.ListInputsRequest, opts ...gax.CallOption) *InputIterator { + it := &InputIterator{} + req = proto.Clone(req).(*livestreampb.ListInputsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*livestreampb.Input, string, error) { + resp := &livestreampb.ListInputsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/inputs", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetInputs(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetInput returns the specified input. +func (c *restClient) GetInput(ctx context.Context, req *livestreampb.GetInputRequest, opts ...gax.CallOption) (*livestreampb.Input, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetInput[0:len((*c.CallOptions).GetInput):len((*c.CallOptions).GetInput)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &livestreampb.Input{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteInput deletes the specified input. +func (c *restClient) DeleteInput(ctx context.Context, req *livestreampb.DeleteInputRequest, opts ...gax.CallOption) (*DeleteInputOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteInputOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateInput updates the specified input. +func (c *restClient) UpdateInput(ctx context.Context, req *livestreampb.UpdateInputRequest, opts ...gax.CallOption) (*UpdateInputOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetInput() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetInput().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "input.name", url.QueryEscape(req.GetInput().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateInputOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// CreateEvent creates an event with the provided unique ID in the specified channel. +func (c *restClient) CreateEvent(ctx context.Context, req *livestreampb.CreateEventRequest, opts ...gax.CallOption) (*livestreampb.Event, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetEvent() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/events", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("eventId", fmt.Sprintf("%v", req.GetEventId())) + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateEvent[0:len((*c.CallOptions).CreateEvent):len((*c.CallOptions).CreateEvent)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &livestreampb.Event{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListEvents returns a list of all events in the specified channel. +func (c *restClient) ListEvents(ctx context.Context, req *livestreampb.ListEventsRequest, opts ...gax.CallOption) *EventIterator { + it := &EventIterator{} + req = proto.Clone(req).(*livestreampb.ListEventsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*livestreampb.Event, string, error) { + resp := &livestreampb.ListEventsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/events", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetEvents(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetEvent returns the specified event. +func (c *restClient) GetEvent(ctx context.Context, req *livestreampb.GetEventRequest, opts ...gax.CallOption) (*livestreampb.Event, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetEvent[0:len((*c.CallOptions).GetEvent):len((*c.CallOptions).GetEvent)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &livestreampb.Event{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteEvent deletes the specified event. +func (c *restClient) DeleteEvent(ctx context.Context, req *livestreampb.DeleteEventRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// CreateChannelOperation manages a long-running operation from CreateChannel. +type CreateChannelOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateChannelOperation returns a new CreateChannelOperation from a given name. +// The name must be that of a previously created CreateChannelOperation, possibly from a different process. +func (c *gRPCClient) CreateChannelOperation(name string) *CreateChannelOperation { + return &CreateChannelOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateChannelOperation returns a new CreateChannelOperation from a given name. +// The name must be that of a previously created CreateChannelOperation, possibly from a different process. +func (c *restClient) CreateChannelOperation(name string) *CreateChannelOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateChannelOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CreateChannelOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*livestreampb.Channel, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp livestreampb.Channel + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *CreateChannelOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*livestreampb.Channel, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp livestreampb.Channel + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *CreateChannelOperation) Metadata() (*livestreampb.OperationMetadata, error) { + var meta livestreampb.OperationMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *CreateChannelOperation) Done() bool { + return op.lro.Done() +} + +// 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 *CreateChannelOperation) Name() string { + return op.lro.Name() +} + +// CreateInputOperation manages a long-running operation from CreateInput. +type CreateInputOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateInputOperation returns a new CreateInputOperation from a given name. +// The name must be that of a previously created CreateInputOperation, possibly from a different process. +func (c *gRPCClient) CreateInputOperation(name string) *CreateInputOperation { + return &CreateInputOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateInputOperation returns a new CreateInputOperation from a given name. +// The name must be that of a previously created CreateInputOperation, possibly from a different process. +func (c *restClient) CreateInputOperation(name string) *CreateInputOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateInputOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CreateInputOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*livestreampb.Input, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp livestreampb.Input + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. // // 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. @@ -996,6 +2333,7 @@ func (op *CreateInputOperation) Wait(ctx context.Context, opts ...gax.CallOption // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateInputOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*livestreampb.Input, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp livestreampb.Input if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1033,7 +2371,8 @@ func (op *CreateInputOperation) Name() string { // DeleteChannelOperation manages a long-running operation from DeleteChannel. type DeleteChannelOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteChannelOperation returns a new DeleteChannelOperation from a given name. @@ -1044,10 +2383,21 @@ func (c *gRPCClient) DeleteChannelOperation(name string) *DeleteChannelOperation } } +// DeleteChannelOperation returns a new DeleteChannelOperation from a given name. +// The name must be that of a previously created DeleteChannelOperation, possibly from a different process. +func (c *restClient) DeleteChannelOperation(name string) *DeleteChannelOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteChannelOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteChannelOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -1061,6 +2411,7 @@ func (op *DeleteChannelOperation) Wait(ctx context.Context, opts ...gax.CallOpti // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteChannelOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -1091,7 +2442,8 @@ func (op *DeleteChannelOperation) Name() string { // DeleteInputOperation manages a long-running operation from DeleteInput. type DeleteInputOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteInputOperation returns a new DeleteInputOperation from a given name. @@ -1102,10 +2454,21 @@ func (c *gRPCClient) DeleteInputOperation(name string) *DeleteInputOperation { } } +// DeleteInputOperation returns a new DeleteInputOperation from a given name. +// The name must be that of a previously created DeleteInputOperation, possibly from a different process. +func (c *restClient) DeleteInputOperation(name string) *DeleteInputOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteInputOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteInputOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -1119,6 +2482,7 @@ func (op *DeleteInputOperation) Wait(ctx context.Context, opts ...gax.CallOption // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteInputOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -1149,7 +2513,8 @@ func (op *DeleteInputOperation) Name() string { // StartChannelOperation manages a long-running operation from StartChannel. type StartChannelOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // StartChannelOperation returns a new StartChannelOperation from a given name. @@ -1160,10 +2525,21 @@ func (c *gRPCClient) StartChannelOperation(name string) *StartChannelOperation { } } +// StartChannelOperation returns a new StartChannelOperation from a given name. +// The name must be that of a previously created StartChannelOperation, possibly from a different process. +func (c *restClient) StartChannelOperation(name string) *StartChannelOperation { + override := fmt.Sprintf("/v1/%s", name) + return &StartChannelOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *StartChannelOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*livestreampb.ChannelOperationResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp livestreampb.ChannelOperationResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1181,6 +2557,7 @@ func (op *StartChannelOperation) Wait(ctx context.Context, opts ...gax.CallOptio // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *StartChannelOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*livestreampb.ChannelOperationResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp livestreampb.ChannelOperationResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1218,7 +2595,8 @@ func (op *StartChannelOperation) Name() string { // StopChannelOperation manages a long-running operation from StopChannel. type StopChannelOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // StopChannelOperation returns a new StopChannelOperation from a given name. @@ -1229,10 +2607,21 @@ func (c *gRPCClient) StopChannelOperation(name string) *StopChannelOperation { } } +// StopChannelOperation returns a new StopChannelOperation from a given name. +// The name must be that of a previously created StopChannelOperation, possibly from a different process. +func (c *restClient) StopChannelOperation(name string) *StopChannelOperation { + override := fmt.Sprintf("/v1/%s", name) + return &StopChannelOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *StopChannelOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*livestreampb.ChannelOperationResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp livestreampb.ChannelOperationResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1250,6 +2639,7 @@ func (op *StopChannelOperation) Wait(ctx context.Context, opts ...gax.CallOption // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *StopChannelOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*livestreampb.ChannelOperationResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp livestreampb.ChannelOperationResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1287,7 +2677,8 @@ func (op *StopChannelOperation) Name() string { // UpdateChannelOperation manages a long-running operation from UpdateChannel. type UpdateChannelOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateChannelOperation returns a new UpdateChannelOperation from a given name. @@ -1298,10 +2689,21 @@ func (c *gRPCClient) UpdateChannelOperation(name string) *UpdateChannelOperation } } +// UpdateChannelOperation returns a new UpdateChannelOperation from a given name. +// The name must be that of a previously created UpdateChannelOperation, possibly from a different process. +func (c *restClient) UpdateChannelOperation(name string) *UpdateChannelOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateChannelOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateChannelOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*livestreampb.Channel, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp livestreampb.Channel if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1319,6 +2721,7 @@ func (op *UpdateChannelOperation) Wait(ctx context.Context, opts ...gax.CallOpti // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateChannelOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*livestreampb.Channel, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp livestreampb.Channel if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -1356,7 +2759,8 @@ func (op *UpdateChannelOperation) Name() string { // UpdateInputOperation manages a long-running operation from UpdateInput. type UpdateInputOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateInputOperation returns a new UpdateInputOperation from a given name. @@ -1367,10 +2771,21 @@ func (c *gRPCClient) UpdateInputOperation(name string) *UpdateInputOperation { } } +// UpdateInputOperation returns a new UpdateInputOperation from a given name. +// The name must be that of a previously created UpdateInputOperation, possibly from a different process. +func (c *restClient) UpdateInputOperation(name string) *UpdateInputOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateInputOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateInputOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*livestreampb.Input, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp livestreampb.Input if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -1388,6 +2803,7 @@ func (op *UpdateInputOperation) Wait(ctx context.Context, opts ...gax.CallOption // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateInputOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*livestreampb.Input, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp livestreampb.Input if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/video/livestream/apiv1/livestream_client_example_test.go b/video/livestream/apiv1/livestream_client_example_test.go index 459970a2b810..41da941fb353 100644 --- a/video/livestream/apiv1/livestream_client_example_test.go +++ b/video/livestream/apiv1/livestream_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := livestream.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_CreateChannel() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/video/livestream/apiv1/livestreampb/outputs.pb.go b/video/livestream/apiv1/livestreampb/outputs.pb.go index fc374ebb3eac..4e1edf80a62e 100644 --- a/video/livestream/apiv1/livestreampb/outputs.pb.go +++ b/video/livestream/apiv1/livestreampb/outputs.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/video/livestream/v1/outputs.proto package livestreampb @@ -103,7 +103,6 @@ type ElementaryStream struct { // Required. Encoding of an audio, video, or text track. // // Types that are assignable to ElementaryStream: - // // *ElementaryStream_VideoStream // *ElementaryStream_AudioStream // *ElementaryStream_TextStream @@ -582,7 +581,6 @@ type VideoStream struct { // Codec settings. // // Types that are assignable to CodecSettings: - // // *VideoStream_H264 CodecSettings isVideoStream_CodecSettings `protobuf_oneof:"codec_settings"` } @@ -1060,7 +1058,6 @@ type VideoStream_H264CodecSettings struct { // GOP mode can be either by frame count or duration. // // Types that are assignable to GopMode: - // // *VideoStream_H264CodecSettings_GopFrameCount // *VideoStream_H264CodecSettings_GopDuration GopMode isVideoStream_H264CodecSettings_GopMode `protobuf_oneof:"gop_mode"` diff --git a/video/livestream/apiv1/livestreampb/resources.pb.go b/video/livestream/apiv1/livestreampb/resources.pb.go index 804e204ff69e..12f2b5331179 100644 --- a/video/livestream/apiv1/livestreampb/resources.pb.go +++ b/video/livestream/apiv1/livestreampb/resources.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/video/livestream/v1/resources.proto package livestreampb @@ -1151,7 +1151,6 @@ type Event struct { // Required. Operation to be executed by this event. // // Types that are assignable to Task: - // // *Event_AdBreak Task isEvent_Task `protobuf_oneof:"task"` // When this field is set to true, the event will be executed at the earliest diff --git a/video/livestream/apiv1/livestreampb/service.pb.go b/video/livestream/apiv1/livestreampb/service.pb.go index 7fe2f01d5ea2..adb9866d304c 100644 --- a/video/livestream/apiv1/livestreampb/service.pb.go +++ b/video/livestream/apiv1/livestreampb/service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/video/livestream/v1/service.proto package livestreampb diff --git a/video/stitcher/apiv1/doc.go b/video/stitcher/apiv1/doc.go index d179323ff56d..66c88da32dbf 100644 --- a/video/stitcher/apiv1/doc.go +++ b/video/stitcher/apiv1/doc.go @@ -78,6 +78,8 @@ package stitcher // import "cloud.google.com/go/video/stitcher/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -166,3 +168,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/video/stitcher/apiv1/gapic_metadata.json b/video/stitcher/apiv1/gapic_metadata.json index 7d2ab3b62f86..0c342d274e2a 100644 --- a/video/stitcher/apiv1/gapic_metadata.json +++ b/video/stitcher/apiv1/gapic_metadata.json @@ -111,6 +111,111 @@ ] } } + }, + "rest": { + "libraryClient": "VideoStitcherClient", + "rpcs": { + "CreateCdnKey": { + "methods": [ + "CreateCdnKey" + ] + }, + "CreateLiveSession": { + "methods": [ + "CreateLiveSession" + ] + }, + "CreateSlate": { + "methods": [ + "CreateSlate" + ] + }, + "CreateVodSession": { + "methods": [ + "CreateVodSession" + ] + }, + "DeleteCdnKey": { + "methods": [ + "DeleteCdnKey" + ] + }, + "DeleteSlate": { + "methods": [ + "DeleteSlate" + ] + }, + "GetCdnKey": { + "methods": [ + "GetCdnKey" + ] + }, + "GetLiveAdTagDetail": { + "methods": [ + "GetLiveAdTagDetail" + ] + }, + "GetLiveSession": { + "methods": [ + "GetLiveSession" + ] + }, + "GetSlate": { + "methods": [ + "GetSlate" + ] + }, + "GetVodAdTagDetail": { + "methods": [ + "GetVodAdTagDetail" + ] + }, + "GetVodSession": { + "methods": [ + "GetVodSession" + ] + }, + "GetVodStitchDetail": { + "methods": [ + "GetVodStitchDetail" + ] + }, + "ListCdnKeys": { + "methods": [ + "ListCdnKeys" + ] + }, + "ListLiveAdTagDetails": { + "methods": [ + "ListLiveAdTagDetails" + ] + }, + "ListSlates": { + "methods": [ + "ListSlates" + ] + }, + "ListVodAdTagDetails": { + "methods": [ + "ListVodAdTagDetails" + ] + }, + "ListVodStitchDetails": { + "methods": [ + "ListVodStitchDetails" + ] + }, + "UpdateCdnKey": { + "methods": [ + "UpdateCdnKey" + ] + }, + "UpdateSlate": { + "methods": [ + "UpdateSlate" + ] + } + } } } } diff --git a/video/stitcher/apiv1/stitcherpb/ad_tag_details.pb.go b/video/stitcher/apiv1/stitcherpb/ad_tag_details.pb.go index e3f3a50e62b7..619d0b321a81 100644 --- a/video/stitcher/apiv1/stitcherpb/ad_tag_details.pb.go +++ b/video/stitcher/apiv1/stitcherpb/ad_tag_details.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/video/stitcher/v1/ad_tag_details.proto package stitcherpb diff --git a/video/stitcher/apiv1/stitcherpb/cdn_keys.pb.go b/video/stitcher/apiv1/stitcherpb/cdn_keys.pb.go index c7b269820348..ff0c5124441f 100644 --- a/video/stitcher/apiv1/stitcherpb/cdn_keys.pb.go +++ b/video/stitcher/apiv1/stitcherpb/cdn_keys.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/video/stitcher/v1/cdn_keys.proto package stitcherpb @@ -47,7 +47,6 @@ type CdnKey struct { // Configuration associated with the CDN key. // // Types that are assignable to CdnKeyConfig: - // // *CdnKey_GoogleCdnKey // *CdnKey_AkamaiCdnKey // *CdnKey_MediaCdnKey diff --git a/video/stitcher/apiv1/stitcherpb/companions.pb.go b/video/stitcher/apiv1/stitcherpb/companions.pb.go index de8d67eb6c6f..76106a861512 100644 --- a/video/stitcher/apiv1/stitcherpb/companions.pb.go +++ b/video/stitcher/apiv1/stitcherpb/companions.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/video/stitcher/v1/companions.proto package stitcherpb @@ -159,7 +159,6 @@ type Companion struct { // Ad resource associated with the companion ad. // // Types that are assignable to AdResource: - // // *Companion_IframeAdResource // *Companion_StaticAdResource // *Companion_HtmlAdResource diff --git a/video/stitcher/apiv1/stitcherpb/events.pb.go b/video/stitcher/apiv1/stitcherpb/events.pb.go index 64f052e62fab..46363c1c1855 100644 --- a/video/stitcher/apiv1/stitcherpb/events.pb.go +++ b/video/stitcher/apiv1/stitcherpb/events.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/video/stitcher/v1/events.proto package stitcherpb diff --git a/video/stitcher/apiv1/stitcherpb/sessions.pb.go b/video/stitcher/apiv1/stitcherpb/sessions.pb.go index d32b0f1b2a23..dd579ab27b94 100644 --- a/video/stitcher/apiv1/stitcherpb/sessions.pb.go +++ b/video/stitcher/apiv1/stitcherpb/sessions.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/video/stitcher/v1/sessions.proto package stitcherpb @@ -167,12 +167,12 @@ type VodSession struct { // Macros are designated by square brackets. // For example: // - // Ad tag URI: `"https://doubleclick.google.com/ad/1?geo_id=[geoId]"` + // Ad tag URI: `"https://doubleclick.google.com/ad/1?geo_id=[geoId]"` // - // Ad tag macro map: `{"geoId": "123"}` + // Ad tag macro map: `{"geoId": "123"}` // - // Fully qualified ad tag: - // `"`https://doubleclick.google.com/ad/1?geo_id=123"` + // Fully qualified ad tag: + // `"`https://doubleclick.google.com/ad/1?geo_id=123"` AdTagMacroMap map[string]string `protobuf:"bytes,7,rep,name=ad_tag_macro_map,json=adTagMacroMap,proto3" json:"ad_tag_macro_map,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` // Indicates whether client side ad tracking is enabled. If client // side ad tracking is enabled, then the client player is expected @@ -566,12 +566,12 @@ type LiveSession struct { // // For example: // - // Ad tag URI: "https://doubleclick.google.com/ad/1?geo_id=[geoId]" + // Ad tag URI: "https://doubleclick.google.com/ad/1?geo_id=[geoId]" // - // Ad tag macros: `{"geoId": "123"}` + // Ad tag macros: `{"geoId": "123"}` // - // Fully qualified ad tag: - // `"https://doubleclick.google.com/ad/1?geo_id=123"` + // Fully qualified ad tag: + // `"https://doubleclick.google.com/ad/1?geo_id=123"` AdTagMacros map[string]string `protobuf:"bytes,6,rep,name=ad_tag_macros,json=adTagMacros,proto3" json:"ad_tag_macros,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` // Whether client side ad tracking is enabled. If enabled, the client player // is expected to trigger playback and activity events itself. Otherwise, diff --git a/video/stitcher/apiv1/stitcherpb/slates.pb.go b/video/stitcher/apiv1/stitcherpb/slates.pb.go index 9365d919ee8e..ec8be3d01fae 100644 --- a/video/stitcher/apiv1/stitcherpb/slates.pb.go +++ b/video/stitcher/apiv1/stitcherpb/slates.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/video/stitcher/v1/slates.proto package stitcherpb diff --git a/video/stitcher/apiv1/stitcherpb/stitch_details.pb.go b/video/stitcher/apiv1/stitcherpb/stitch_details.pb.go index bcb20eb23f31..2c06a0e5992d 100644 --- a/video/stitcher/apiv1/stitcherpb/stitch_details.pb.go +++ b/video/stitcher/apiv1/stitcherpb/stitch_details.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/video/stitcher/v1/stitch_details.proto package stitcherpb diff --git a/video/stitcher/apiv1/stitcherpb/video_stitcher_service.pb.go b/video/stitcher/apiv1/stitcherpb/video_stitcher_service.pb.go index f4ffbab190cb..33029dcbb8be 100644 --- a/video/stitcher/apiv1/stitcherpb/video_stitcher_service.pb.go +++ b/video/stitcher/apiv1/stitcherpb/video_stitcher_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/video/stitcher/v1/video_stitcher_service.proto package stitcherpb diff --git a/video/stitcher/apiv1/video_stitcher_client.go b/video/stitcher/apiv1/video_stitcher_client.go index 3fa69371a2b5..3dd03f8416a2 100644 --- a/video/stitcher/apiv1/video_stitcher_client.go +++ b/video/stitcher/apiv1/video_stitcher_client.go @@ -17,20 +17,26 @@ package stitcher import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" stitcherpb "cloud.google.com/go/video/stitcher/apiv1/stitcherpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -97,6 +103,31 @@ func defaultVideoStitcherCallOptions() *VideoStitcherCallOptions { } } +func defaultVideoStitcherRESTCallOptions() *VideoStitcherCallOptions { + return &VideoStitcherCallOptions{ + CreateCdnKey: []gax.CallOption{}, + ListCdnKeys: []gax.CallOption{}, + GetCdnKey: []gax.CallOption{}, + DeleteCdnKey: []gax.CallOption{}, + UpdateCdnKey: []gax.CallOption{}, + CreateVodSession: []gax.CallOption{}, + GetVodSession: []gax.CallOption{}, + ListVodStitchDetails: []gax.CallOption{}, + GetVodStitchDetail: []gax.CallOption{}, + ListVodAdTagDetails: []gax.CallOption{}, + GetVodAdTagDetail: []gax.CallOption{}, + ListLiveAdTagDetails: []gax.CallOption{}, + GetLiveAdTagDetail: []gax.CallOption{}, + CreateSlate: []gax.CallOption{}, + ListSlates: []gax.CallOption{}, + GetSlate: []gax.CallOption{}, + UpdateSlate: []gax.CallOption{}, + DeleteSlate: []gax.CallOption{}, + CreateLiveSession: []gax.CallOption{}, + GetLiveSession: []gax.CallOption{}, + } +} + // internalVideoStitcherClient is an interface that defines the methods available from Video Stitcher API. type internalVideoStitcherClient interface { Close() error @@ -352,6 +383,78 @@ func (c *videoStitcherGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type videoStitcherRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing VideoStitcherClient + CallOptions **VideoStitcherCallOptions +} + +// NewVideoStitcherRESTClient creates a new video stitcher service rest client. +// +// Video-On-Demand content stitching API allows you to insert ads +// into (VoD) video on demand files. You will be able to render custom +// scrubber bars with highlighted ads, enforce ad policies, allow +// seamless playback and tracking on native players and monetize +// content with any standard VMAP compliant ad server. +func NewVideoStitcherRESTClient(ctx context.Context, opts ...option.ClientOption) (*VideoStitcherClient, error) { + clientOpts := append(defaultVideoStitcherRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultVideoStitcherRESTCallOptions() + c := &videoStitcherRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &VideoStitcherClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultVideoStitcherRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://videostitcher.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://videostitcher.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://videostitcher.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *videoStitcherRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *videoStitcherRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *videoStitcherRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *videoStitcherGRPCClient) CreateCdnKey(ctx context.Context, req *stitcherpb.CreateCdnKeyRequest, opts ...gax.CallOption) (*stitcherpb.CdnKey, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) @@ -899,6 +1002,1354 @@ func (c *videoStitcherGRPCClient) GetLiveSession(ctx context.Context, req *stitc return resp, nil } +// CreateCdnKey creates a new CDN key. +func (c *videoStitcherRESTClient) CreateCdnKey(ctx context.Context, req *stitcherpb.CreateCdnKeyRequest, opts ...gax.CallOption) (*stitcherpb.CdnKey, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetCdnKey() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/cdnKeys", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("cdnKeyId", fmt.Sprintf("%v", req.GetCdnKeyId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateCdnKey[0:len((*c.CallOptions).CreateCdnKey):len((*c.CallOptions).CreateCdnKey)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &stitcherpb.CdnKey{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListCdnKeys lists all CDN keys in the specified project and location. +func (c *videoStitcherRESTClient) ListCdnKeys(ctx context.Context, req *stitcherpb.ListCdnKeysRequest, opts ...gax.CallOption) *CdnKeyIterator { + it := &CdnKeyIterator{} + req = proto.Clone(req).(*stitcherpb.ListCdnKeysRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*stitcherpb.CdnKey, string, error) { + resp := &stitcherpb.ListCdnKeysResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/cdnKeys", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetCdnKeys(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetCdnKey returns the specified CDN key. +func (c *videoStitcherRESTClient) GetCdnKey(ctx context.Context, req *stitcherpb.GetCdnKeyRequest, opts ...gax.CallOption) (*stitcherpb.CdnKey, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetCdnKey[0:len((*c.CallOptions).GetCdnKey):len((*c.CallOptions).GetCdnKey)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &stitcherpb.CdnKey{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteCdnKey deletes the specified CDN key. +func (c *videoStitcherRESTClient) DeleteCdnKey(ctx context.Context, req *stitcherpb.DeleteCdnKeyRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// UpdateCdnKey updates the specified CDN key. Only update fields specified +// in the call method body. +func (c *videoStitcherRESTClient) UpdateCdnKey(ctx context.Context, req *stitcherpb.UpdateCdnKeyRequest, opts ...gax.CallOption) (*stitcherpb.CdnKey, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetCdnKey() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetCdnKey().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "cdn_key.name", url.QueryEscape(req.GetCdnKey().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateCdnKey[0:len((*c.CallOptions).UpdateCdnKey):len((*c.CallOptions).UpdateCdnKey)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &stitcherpb.CdnKey{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateVodSession creates a client side playback VOD session and returns the full +// tracking and playback metadata of the session. +func (c *videoStitcherRESTClient) CreateVodSession(ctx context.Context, req *stitcherpb.CreateVodSessionRequest, opts ...gax.CallOption) (*stitcherpb.VodSession, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetVodSession() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/vodSessions", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateVodSession[0:len((*c.CallOptions).CreateVodSession):len((*c.CallOptions).CreateVodSession)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &stitcherpb.VodSession{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetVodSession returns the full tracking, playback metadata, and relevant ad-ops +// logs for the specified VOD session. +func (c *videoStitcherRESTClient) GetVodSession(ctx context.Context, req *stitcherpb.GetVodSessionRequest, opts ...gax.CallOption) (*stitcherpb.VodSession, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetVodSession[0:len((*c.CallOptions).GetVodSession):len((*c.CallOptions).GetVodSession)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &stitcherpb.VodSession{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListVodStitchDetails returns a list of detailed stitching information of the specified VOD +// session. +func (c *videoStitcherRESTClient) ListVodStitchDetails(ctx context.Context, req *stitcherpb.ListVodStitchDetailsRequest, opts ...gax.CallOption) *VodStitchDetailIterator { + it := &VodStitchDetailIterator{} + req = proto.Clone(req).(*stitcherpb.ListVodStitchDetailsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*stitcherpb.VodStitchDetail, string, error) { + resp := &stitcherpb.ListVodStitchDetailsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/vodStitchDetails", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetVodStitchDetails(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetVodStitchDetail returns the specified stitching information for the specified VOD session. +func (c *videoStitcherRESTClient) GetVodStitchDetail(ctx context.Context, req *stitcherpb.GetVodStitchDetailRequest, opts ...gax.CallOption) (*stitcherpb.VodStitchDetail, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetVodStitchDetail[0:len((*c.CallOptions).GetVodStitchDetail):len((*c.CallOptions).GetVodStitchDetail)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &stitcherpb.VodStitchDetail{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListVodAdTagDetails return the list of ad tag details for the specified VOD session. +func (c *videoStitcherRESTClient) ListVodAdTagDetails(ctx context.Context, req *stitcherpb.ListVodAdTagDetailsRequest, opts ...gax.CallOption) *VodAdTagDetailIterator { + it := &VodAdTagDetailIterator{} + req = proto.Clone(req).(*stitcherpb.ListVodAdTagDetailsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*stitcherpb.VodAdTagDetail, string, error) { + resp := &stitcherpb.ListVodAdTagDetailsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/vodAdTagDetails", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetVodAdTagDetails(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetVodAdTagDetail returns the specified ad tag detail for the specified VOD session. +func (c *videoStitcherRESTClient) GetVodAdTagDetail(ctx context.Context, req *stitcherpb.GetVodAdTagDetailRequest, opts ...gax.CallOption) (*stitcherpb.VodAdTagDetail, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetVodAdTagDetail[0:len((*c.CallOptions).GetVodAdTagDetail):len((*c.CallOptions).GetVodAdTagDetail)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &stitcherpb.VodAdTagDetail{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLiveAdTagDetails return the list of ad tag details for the specified live session. +func (c *videoStitcherRESTClient) ListLiveAdTagDetails(ctx context.Context, req *stitcherpb.ListLiveAdTagDetailsRequest, opts ...gax.CallOption) *LiveAdTagDetailIterator { + it := &LiveAdTagDetailIterator{} + req = proto.Clone(req).(*stitcherpb.ListLiveAdTagDetailsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*stitcherpb.LiveAdTagDetail, string, error) { + resp := &stitcherpb.ListLiveAdTagDetailsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/liveAdTagDetails", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLiveAdTagDetails(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetLiveAdTagDetail returns the specified ad tag detail for the specified live session. +func (c *videoStitcherRESTClient) GetLiveAdTagDetail(ctx context.Context, req *stitcherpb.GetLiveAdTagDetailRequest, opts ...gax.CallOption) (*stitcherpb.LiveAdTagDetail, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLiveAdTagDetail[0:len((*c.CallOptions).GetLiveAdTagDetail):len((*c.CallOptions).GetLiveAdTagDetail)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &stitcherpb.LiveAdTagDetail{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateSlate creates a slate. +func (c *videoStitcherRESTClient) CreateSlate(ctx context.Context, req *stitcherpb.CreateSlateRequest, opts ...gax.CallOption) (*stitcherpb.Slate, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetSlate() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/slates", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("slateId", fmt.Sprintf("%v", req.GetSlateId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateSlate[0:len((*c.CallOptions).CreateSlate):len((*c.CallOptions).CreateSlate)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &stitcherpb.Slate{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListSlates lists all slates in the specified project and location. +func (c *videoStitcherRESTClient) ListSlates(ctx context.Context, req *stitcherpb.ListSlatesRequest, opts ...gax.CallOption) *SlateIterator { + it := &SlateIterator{} + req = proto.Clone(req).(*stitcherpb.ListSlatesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*stitcherpb.Slate, string, error) { + resp := &stitcherpb.ListSlatesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/slates", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetSlates(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetSlate returns the specified slate. +func (c *videoStitcherRESTClient) GetSlate(ctx context.Context, req *stitcherpb.GetSlateRequest, opts ...gax.CallOption) (*stitcherpb.Slate, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetSlate[0:len((*c.CallOptions).GetSlate):len((*c.CallOptions).GetSlate)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &stitcherpb.Slate{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateSlate updates the specified slate. +func (c *videoStitcherRESTClient) UpdateSlate(ctx context.Context, req *stitcherpb.UpdateSlateRequest, opts ...gax.CallOption) (*stitcherpb.Slate, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetSlate() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetSlate().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "slate.name", url.QueryEscape(req.GetSlate().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateSlate[0:len((*c.CallOptions).UpdateSlate):len((*c.CallOptions).UpdateSlate)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &stitcherpb.Slate{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteSlate deletes the specified slate. +func (c *videoStitcherRESTClient) DeleteSlate(ctx context.Context, req *stitcherpb.DeleteSlateRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// CreateLiveSession creates a new live session. +func (c *videoStitcherRESTClient) CreateLiveSession(ctx context.Context, req *stitcherpb.CreateLiveSessionRequest, opts ...gax.CallOption) (*stitcherpb.LiveSession, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetLiveSession() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/liveSessions", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateLiveSession[0:len((*c.CallOptions).CreateLiveSession):len((*c.CallOptions).CreateLiveSession)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &stitcherpb.LiveSession{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetLiveSession returns the details for the specified live session. +func (c *videoStitcherRESTClient) GetLiveSession(ctx context.Context, req *stitcherpb.GetLiveSessionRequest, opts ...gax.CallOption) (*stitcherpb.LiveSession, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLiveSession[0:len((*c.CallOptions).GetLiveSession):len((*c.CallOptions).GetLiveSession)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &stitcherpb.LiveSession{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + // CdnKeyIterator manages a stream of *stitcherpb.CdnKey. type CdnKeyIterator struct { items []*stitcherpb.CdnKey diff --git a/video/stitcher/apiv1/video_stitcher_client_example_test.go b/video/stitcher/apiv1/video_stitcher_client_example_test.go index fabda9d5580e..fa87710e8618 100644 --- a/video/stitcher/apiv1/video_stitcher_client_example_test.go +++ b/video/stitcher/apiv1/video_stitcher_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewVideoStitcherClient() { _ = c } +func ExampleNewVideoStitcherRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := stitcher.NewVideoStitcherRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleVideoStitcherClient_CreateCdnKey() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/video/transcoder/apiv1/doc.go b/video/transcoder/apiv1/doc.go index 3a9faf6bf1a6..fdf7706775f0 100644 --- a/video/transcoder/apiv1/doc.go +++ b/video/transcoder/apiv1/doc.go @@ -82,6 +82,8 @@ package transcoder // import "cloud.google.com/go/video/transcoder/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -170,3 +172,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/video/transcoder/apiv1/gapic_metadata.json b/video/transcoder/apiv1/gapic_metadata.json index cdf2d1c1be02..f5d79dcae51d 100644 --- a/video/transcoder/apiv1/gapic_metadata.json +++ b/video/transcoder/apiv1/gapic_metadata.json @@ -51,6 +51,51 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "CreateJob": { + "methods": [ + "CreateJob" + ] + }, + "CreateJobTemplate": { + "methods": [ + "CreateJobTemplate" + ] + }, + "DeleteJob": { + "methods": [ + "DeleteJob" + ] + }, + "DeleteJobTemplate": { + "methods": [ + "DeleteJobTemplate" + ] + }, + "GetJob": { + "methods": [ + "GetJob" + ] + }, + "GetJobTemplate": { + "methods": [ + "GetJobTemplate" + ] + }, + "ListJobTemplates": { + "methods": [ + "ListJobTemplates" + ] + }, + "ListJobs": { + "methods": [ + "ListJobs" + ] + } + } } } } diff --git a/video/transcoder/apiv1/transcoder_client.go b/video/transcoder/apiv1/transcoder_client.go index b13b4137da19..14b7cd74867a 100644 --- a/video/transcoder/apiv1/transcoder_client.go +++ b/video/transcoder/apiv1/transcoder_client.go @@ -17,20 +17,26 @@ package transcoder import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" transcoderpb "cloud.google.com/go/video/transcoder/apiv1/transcoderpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -73,6 +79,19 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + CreateJob: []gax.CallOption{}, + ListJobs: []gax.CallOption{}, + GetJob: []gax.CallOption{}, + DeleteJob: []gax.CallOption{}, + CreateJobTemplate: []gax.CallOption{}, + ListJobTemplates: []gax.CallOption{}, + GetJobTemplate: []gax.CallOption{}, + DeleteJobTemplate: []gax.CallOption{}, + } +} + // internalClient is an interface that defines the methods available from Transcoder API. type internalClient interface { Close() error @@ -254,6 +273,79 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new transcoder service rest client. +// +// Using the Transcoder API, you can queue asynchronous jobs for transcoding +// media into various output formats. Output formats may include different +// streaming standards such as HTTP Live Streaming (HLS) and Dynamic Adaptive +// Streaming over HTTP (DASH). You can also customize jobs using advanced +// features such as Digital Rights Management (DRM), audio equalization, content +// concatenation, and digital ad-stitch ready content generation. +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://transcoder.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://transcoder.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://transcoder.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) CreateJob(ctx context.Context, req *transcoderpb.CreateJobRequest, opts ...gax.CallOption) (*transcoderpb.Job, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) @@ -468,6 +560,527 @@ func (c *gRPCClient) DeleteJobTemplate(ctx context.Context, req *transcoderpb.De return err } +// CreateJob creates a job in the specified region. +func (c *restClient) CreateJob(ctx context.Context, req *transcoderpb.CreateJobRequest, opts ...gax.CallOption) (*transcoderpb.Job, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetJob() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/jobs", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateJob[0:len((*c.CallOptions).CreateJob):len((*c.CallOptions).CreateJob)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &transcoderpb.Job{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListJobs lists jobs in the specified region. +func (c *restClient) ListJobs(ctx context.Context, req *transcoderpb.ListJobsRequest, opts ...gax.CallOption) *JobIterator { + it := &JobIterator{} + req = proto.Clone(req).(*transcoderpb.ListJobsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*transcoderpb.Job, string, error) { + resp := &transcoderpb.ListJobsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/jobs", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetJobs(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetJob returns the job data. +func (c *restClient) GetJob(ctx context.Context, req *transcoderpb.GetJobRequest, opts ...gax.CallOption) (*transcoderpb.Job, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetJob[0:len((*c.CallOptions).GetJob):len((*c.CallOptions).GetJob)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &transcoderpb.Job{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteJob deletes a job. +func (c *restClient) DeleteJob(ctx context.Context, req *transcoderpb.DeleteJobRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetAllowMissing() { + params.Add("allowMissing", fmt.Sprintf("%v", req.GetAllowMissing())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// CreateJobTemplate creates a job template in the specified region. +func (c *restClient) CreateJobTemplate(ctx context.Context, req *transcoderpb.CreateJobTemplateRequest, opts ...gax.CallOption) (*transcoderpb.JobTemplate, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetJobTemplate() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/jobTemplates", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("jobTemplateId", fmt.Sprintf("%v", req.GetJobTemplateId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateJobTemplate[0:len((*c.CallOptions).CreateJobTemplate):len((*c.CallOptions).CreateJobTemplate)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &transcoderpb.JobTemplate{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListJobTemplates lists job templates in the specified region. +func (c *restClient) ListJobTemplates(ctx context.Context, req *transcoderpb.ListJobTemplatesRequest, opts ...gax.CallOption) *JobTemplateIterator { + it := &JobTemplateIterator{} + req = proto.Clone(req).(*transcoderpb.ListJobTemplatesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*transcoderpb.JobTemplate, string, error) { + resp := &transcoderpb.ListJobTemplatesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/jobTemplates", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetJobTemplates(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetJobTemplate returns the job template data. +func (c *restClient) GetJobTemplate(ctx context.Context, req *transcoderpb.GetJobTemplateRequest, opts ...gax.CallOption) (*transcoderpb.JobTemplate, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetJobTemplate[0:len((*c.CallOptions).GetJobTemplate):len((*c.CallOptions).GetJobTemplate)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &transcoderpb.JobTemplate{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteJobTemplate deletes a job template. +func (c *restClient) DeleteJobTemplate(ctx context.Context, req *transcoderpb.DeleteJobTemplateRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetAllowMissing() { + params.Add("allowMissing", fmt.Sprintf("%v", req.GetAllowMissing())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + // JobIterator manages a stream of *transcoderpb.Job. type JobIterator struct { items []*transcoderpb.Job diff --git a/video/transcoder/apiv1/transcoder_client_example_test.go b/video/transcoder/apiv1/transcoder_client_example_test.go index 9267e12811d2..8f022c6eac32 100644 --- a/video/transcoder/apiv1/transcoder_client_example_test.go +++ b/video/transcoder/apiv1/transcoder_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := transcoder.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_CreateJob() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/video/transcoder/apiv1/transcoderpb/resources.pb.go b/video/transcoder/apiv1/transcoderpb/resources.pb.go index 9b2b4f9489b5..c1a1110febee 100644 --- a/video/transcoder/apiv1/transcoderpb/resources.pb.go +++ b/video/transcoder/apiv1/transcoderpb/resources.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/video/transcoder/v1/resources.proto package transcoderpb @@ -235,7 +235,6 @@ type Job struct { // the `Job.config` is populated by the `JobTemplate.config`.
// // Types that are assignable to JobConfig: - // // *Job_TemplateId // *Job_Config JobConfig isJob_JobConfig `protobuf_oneof:"job_config"` @@ -393,8 +392,8 @@ type Job_TemplateId struct { // Preset Transcoder templates: // - `preset/{preset_id}` // - // - User defined JobTemplate: - // `{job_template_id}` + // - User defined JobTemplate: + // `{job_template_id}` TemplateId string `protobuf:"bytes,4,opt,name=template_id,json=templateId,proto3,oneof"` } @@ -878,7 +877,6 @@ type ElementaryStream struct { // Encoding of an audio, video, or text track. // // Types that are assignable to ElementaryStream: - // // *ElementaryStream_VideoStream // *ElementaryStream_AudioStream // *ElementaryStream_TextStream @@ -1254,7 +1252,6 @@ type SpriteSheet struct { // Specify either total number of sprites or interval to create sprites. // // Types that are assignable to ExtractionStrategy: - // // *SpriteSheet_TotalCount // *SpriteSheet_Interval ExtractionStrategy isSpriteSheet_ExtractionStrategy `protobuf_oneof:"extraction_strategy"` @@ -1573,7 +1570,6 @@ type VideoStream struct { // Codec settings can be h264, h265, or vp9. // // Types that are assignable to CodecSettings: - // // *VideoStream_H264 // *VideoStream_H265 // *VideoStream_Vp9 @@ -2239,7 +2235,6 @@ type Overlay_Animation struct { // Animations can be static or fade, or they can end the previous animation. // // Types that are assignable to AnimationType: - // // *Overlay_Animation_AnimationStatic // *Overlay_Animation_AnimationFade // *Overlay_Animation_AnimationEnd @@ -2543,14 +2538,14 @@ type PreprocessingConfig_Audio struct { // Specify audio loudness normalization in loudness units relative to full // scale (LUFS). Enter a value between -24 and 0 (the default), where: // - // - -24 is the Advanced Television Systems Committee (ATSC A/85) standard - // - -23 is the EU R128 broadcast standard - // - -19 is the prior standard for online mono audio - // - -18 is the ReplayGain standard - // - -16 is the prior standard for stereo audio - // - -14 is the new online audio standard recommended by Spotify, as well + // * -24 is the Advanced Television Systems Committee (ATSC A/85) standard + // * -23 is the EU R128 broadcast standard + // * -19 is the prior standard for online mono audio + // * -18 is the ReplayGain standard + // * -16 is the prior standard for stereo audio + // * -14 is the new online audio standard recommended by Spotify, as well // as Amazon Echo - // - 0 disables normalization + // * 0 disables normalization Lufs float64 `protobuf:"fixed64,1,opt,name=lufs,proto3" json:"lufs,omitempty"` // Enable boosting high frequency components. The default is `false`. // @@ -2778,7 +2773,6 @@ type PreprocessingConfig_Deinterlace struct { // Specify the video deinterlacing filter. The default is `yadif`. // // Types that are assignable to DeinterlacingFilter: - // // *PreprocessingConfig_Deinterlace_Yadif // *PreprocessingConfig_Deinterlace_Bwdif DeinterlacingFilter isPreprocessingConfig_Deinterlace_DeinterlacingFilter `protobuf_oneof:"deinterlacing_filter"` @@ -3090,7 +3084,6 @@ type VideoStream_H264CodecSettings struct { // GOP mode can be either by frame count or duration. // // Types that are assignable to GopMode: - // // *VideoStream_H264CodecSettings_GopFrameCount // *VideoStream_H264CodecSettings_GopDuration GopMode isVideoStream_H264CodecSettings_GopMode `protobuf_oneof:"gop_mode"` @@ -3417,7 +3410,6 @@ type VideoStream_H265CodecSettings struct { // GOP mode can be either by frame count or duration. // // Types that are assignable to GopMode: - // // *VideoStream_H265CodecSettings_GopFrameCount // *VideoStream_H265CodecSettings_GopDuration GopMode isVideoStream_H265CodecSettings_GopMode `protobuf_oneof:"gop_mode"` @@ -3446,25 +3438,23 @@ type VideoStream_H265CodecSettings struct { // supported: // // * 8-bit profiles - // - `main` (default) - // - `main-intra` - // - `mainstillpicture` - // + // * `main` (default) + // * `main-intra` + // * `mainstillpicture` // * 10-bit profiles - // - `main10` (default) - // - `main10-intra` - // - `main422-10` - // - `main422-10-intra` - // - `main444-10` - // - `main444-10-intra` - // + // * `main10` (default) + // * `main10-intra` + // * `main422-10` + // * `main422-10-intra` + // * `main444-10` + // * `main444-10-intra` // * 12-bit profiles - // - `main12` (default) - // - `main12-intra` - // - `main422-12` - // - `main422-12-intra` - // - `main444-12` - // - `main444-12-intra` + // * `main12` (default) + // * `main12-intra` + // * `main422-12` + // * `main422-12-intra` + // * `main444-12` + // * `main444-12-intra` // // The available options are // [FFmpeg-compatible](https://x265.readthedocs.io/). @@ -3745,7 +3735,6 @@ type VideoStream_Vp9CodecSettings struct { // GOP mode can be either by frame count or duration. // // Types that are assignable to GopMode: - // // *VideoStream_Vp9CodecSettings_GopFrameCount // *VideoStream_Vp9CodecSettings_GopDuration GopMode isVideoStream_Vp9CodecSettings_GopMode `protobuf_oneof:"gop_mode"` diff --git a/video/transcoder/apiv1/transcoderpb/services.pb.go b/video/transcoder/apiv1/transcoderpb/services.pb.go index d338b119306a..188f4b622dad 100644 --- a/video/transcoder/apiv1/transcoderpb/services.pb.go +++ b/video/transcoder/apiv1/transcoderpb/services.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/video/transcoder/v1/services.proto package transcoderpb diff --git a/videointelligence/apiv1/doc.go b/videointelligence/apiv1/doc.go index fd5edb227c78..9d1a7ba82244 100644 --- a/videointelligence/apiv1/doc.go +++ b/videointelligence/apiv1/doc.go @@ -87,6 +87,8 @@ package videointelligence // import "cloud.google.com/go/videointelligence/apiv1 import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -175,3 +177,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/videointelligence/apiv1/gapic_metadata.json b/videointelligence/apiv1/gapic_metadata.json index ff747ce5951f..30a883a75ff8 100644 --- a/videointelligence/apiv1/gapic_metadata.json +++ b/videointelligence/apiv1/gapic_metadata.json @@ -16,6 +16,16 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "AnnotateVideo": { + "methods": [ + "AnnotateVideo" + ] + } + } } } } diff --git a/videointelligence/apiv1/video_intelligence_client.go b/videointelligence/apiv1/video_intelligence_client.go index 9b9f24ce0f51..40254eab2f8e 100644 --- a/videointelligence/apiv1/video_intelligence_client.go +++ b/videointelligence/apiv1/video_intelligence_client.go @@ -17,21 +17,29 @@ package videointelligence import ( + "bytes" "context" + "fmt" + "io/ioutil" "math" + "net/http" + "net/url" "time" "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" videointelligencepb "cloud.google.com/go/videointelligence/apiv1/videointelligencepb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" ) var newClientHook clientHook @@ -70,6 +78,22 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + AnnotateVideo: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 120000 * time.Millisecond, + Multiplier: 2.50, + }, + http.StatusServiceUnavailable, + http.StatusGatewayTimeout) + }), + }, + } +} + // internalClient is an interface that defines the methods available from Cloud Video Intelligence API. type internalClient interface { Close() error @@ -230,6 +254,89 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new video intelligence service rest client. +// +// Service that implements the Video Intelligence API. +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://videointelligence.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://videointelligence.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://videointelligence.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) AnnotateVideo(ctx context.Context, req *videointelligencepb.AnnotateVideoRequest, opts ...gax.CallOption) (*AnnotateVideoOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) @@ -252,9 +359,79 @@ func (c *gRPCClient) AnnotateVideo(ctx context.Context, req *videointelligencepb }, nil } +// AnnotateVideo performs asynchronous video annotation. Progress and results can be +// retrieved through the google.longrunning.Operations interface. +// Operation.metadata contains AnnotateVideoProgress (progress). +// Operation.response contains AnnotateVideoResponse (results). +func (c *restClient) AnnotateVideo(ctx context.Context, req *videointelligencepb.AnnotateVideoRequest, opts ...gax.CallOption) (*AnnotateVideoOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/videos:annotate") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &AnnotateVideoOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + // AnnotateVideoOperation manages a long-running operation from AnnotateVideo. type AnnotateVideoOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // AnnotateVideoOperation returns a new AnnotateVideoOperation from a given name. @@ -265,10 +442,21 @@ func (c *gRPCClient) AnnotateVideoOperation(name string) *AnnotateVideoOperation } } +// AnnotateVideoOperation returns a new AnnotateVideoOperation from a given name. +// The name must be that of a previously created AnnotateVideoOperation, possibly from a different process. +func (c *restClient) AnnotateVideoOperation(name string) *AnnotateVideoOperation { + override := fmt.Sprintf("/v1/%s", name) + return &AnnotateVideoOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *AnnotateVideoOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*videointelligencepb.AnnotateVideoResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp videointelligencepb.AnnotateVideoResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -286,6 +474,7 @@ func (op *AnnotateVideoOperation) Wait(ctx context.Context, opts ...gax.CallOpti // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *AnnotateVideoOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*videointelligencepb.AnnotateVideoResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp videointelligencepb.AnnotateVideoResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/videointelligence/apiv1/video_intelligence_client_example_test.go b/videointelligence/apiv1/video_intelligence_client_example_test.go index ee9f61e19d70..2fe111aa34d0 100644 --- a/videointelligence/apiv1/video_intelligence_client_example_test.go +++ b/videointelligence/apiv1/video_intelligence_client_example_test.go @@ -40,6 +40,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := videointelligence.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_AnnotateVideo() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/videointelligence/apiv1/videointelligencepb/video_intelligence.pb.go b/videointelligence/apiv1/videointelligencepb/video_intelligence.pb.go index b428b7054067..791a7b82e24d 100644 --- a/videointelligence/apiv1/videointelligencepb/video_intelligence.pb.go +++ b/videointelligence/apiv1/videointelligencepb/video_intelligence.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/videointelligence/v1/video_intelligence.proto package videointelligencepb @@ -3321,7 +3321,6 @@ type ObjectTrackingAnnotation struct { // and streaming modes. // // Types that are assignable to TrackInfo: - // // *ObjectTrackingAnnotation_Segment // *ObjectTrackingAnnotation_TrackId TrackInfo isObjectTrackingAnnotation_TrackInfo `protobuf_oneof:"track_info"` diff --git a/videointelligence/apiv1beta2/video_intelligence_client.go b/videointelligence/apiv1beta2/video_intelligence_client.go index 7cd324322ef3..f717fc8b989f 100644 --- a/videointelligence/apiv1beta2/video_intelligence_client.go +++ b/videointelligence/apiv1beta2/video_intelligence_client.go @@ -376,6 +376,11 @@ func (c *restClient) AnnotateVideo(ctx context.Context, req *videointelligencepb } baseUrl.Path += fmt.Sprintf("/v1beta2/videos:annotate") + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} diff --git a/videointelligence/apiv1beta2/videointelligencepb/video_intelligence.pb.go b/videointelligence/apiv1beta2/videointelligencepb/video_intelligence.pb.go index da33373959cd..4f64096fe009 100644 --- a/videointelligence/apiv1beta2/videointelligencepb/video_intelligence.pb.go +++ b/videointelligence/apiv1beta2/videointelligencepb/video_intelligence.pb.go @@ -15,8 +15,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/videointelligence/v1beta2/video_intelligence.proto package videointelligencepb diff --git a/videointelligence/apiv1p3beta1/streaming_video_intelligence_client.go b/videointelligence/apiv1p3beta1/streaming_video_intelligence_client.go index af587b9dbe3a..f77436b4488f 100644 --- a/videointelligence/apiv1p3beta1/streaming_video_intelligence_client.go +++ b/videointelligence/apiv1p3beta1/streaming_video_intelligence_client.go @@ -132,6 +132,8 @@ func (c *StreamingVideoIntelligenceClient) Connection() *grpc.ClientConn { // StreamingAnnotateVideo performs video annotation with bidirectional streaming: emitting results // while sending video/audio bytes. // This method is only available via the gRPC API (not REST). +// +// This method is not supported for the REST transport. func (c *StreamingVideoIntelligenceClient) StreamingAnnotateVideo(ctx context.Context, opts ...gax.CallOption) (videointelligencepb.StreamingVideoIntelligenceService_StreamingAnnotateVideoClient, error) { return c.internalClient.StreamingAnnotateVideo(ctx, opts...) } @@ -303,6 +305,8 @@ func (c *streamingVideoIntelligenceGRPCClient) StreamingAnnotateVideo(ctx contex // StreamingAnnotateVideo performs video annotation with bidirectional streaming: emitting results // while sending video/audio bytes. // This method is only available via the gRPC API (not REST). +// +// This method is not supported for the REST transport. func (c *streamingVideoIntelligenceRESTClient) StreamingAnnotateVideo(ctx context.Context, opts ...gax.CallOption) (videointelligencepb.StreamingVideoIntelligenceService_StreamingAnnotateVideoClient, error) { return nil, fmt.Errorf("StreamingAnnotateVideo not yet supported for REST clients") } diff --git a/videointelligence/apiv1p3beta1/video_intelligence_client.go b/videointelligence/apiv1p3beta1/video_intelligence_client.go index 17ebabb649c8..c1094a6007cf 100644 --- a/videointelligence/apiv1p3beta1/video_intelligence_client.go +++ b/videointelligence/apiv1p3beta1/video_intelligence_client.go @@ -376,6 +376,11 @@ func (c *restClient) AnnotateVideo(ctx context.Context, req *videointelligencepb } baseUrl.Path += fmt.Sprintf("/v1p3beta1/videos:annotate") + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} diff --git a/videointelligence/apiv1p3beta1/videointelligencepb/video_intelligence.pb.go b/videointelligence/apiv1p3beta1/videointelligencepb/video_intelligence.pb.go index 999c65f8d1cd..e1de6b867ab2 100644 --- a/videointelligence/apiv1p3beta1/videointelligencepb/video_intelligence.pb.go +++ b/videointelligence/apiv1p3beta1/videointelligencepb/video_intelligence.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/videointelligence/v1p3beta1/video_intelligence.proto package videointelligencepb @@ -3349,7 +3349,6 @@ type ObjectTrackingAnnotation struct { // and streaming modes. // // Types that are assignable to TrackInfo: - // // *ObjectTrackingAnnotation_Segment // *ObjectTrackingAnnotation_TrackId TrackInfo isObjectTrackingAnnotation_TrackInfo `protobuf_oneof:"track_info"` @@ -3545,7 +3544,6 @@ type StreamingAnnotateVideoRequest struct { // video content. // // Types that are assignable to StreamingRequest: - // // *StreamingAnnotateVideoRequest_VideoConfig // *StreamingAnnotateVideoRequest_InputContent StreamingRequest isStreamingAnnotateVideoRequest_StreamingRequest `protobuf_oneof:"streaming_request"` @@ -3642,7 +3640,6 @@ type StreamingVideoConfig struct { // Config for requested annotation feature. // // Types that are assignable to StreamingConfig: - // // *StreamingVideoConfig_ShotChangeDetectionConfig // *StreamingVideoConfig_LabelDetectionConfig // *StreamingVideoConfig_ExplicitContentDetectionConfig diff --git a/vision/v2/apiv1/doc.go b/vision/v2/apiv1/doc.go index eba228bb68e9..6cd17b5b4edc 100644 --- a/vision/v2/apiv1/doc.go +++ b/vision/v2/apiv1/doc.go @@ -82,6 +82,8 @@ package vision // import "cloud.google.com/go/vision/v2/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -171,3 +173,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/vision/v2/apiv1/gapic_metadata.json b/vision/v2/apiv1/gapic_metadata.json index 11f7250a2f91..acd87d5edf0b 100644 --- a/vision/v2/apiv1/gapic_metadata.json +++ b/vision/v2/apiv1/gapic_metadata.json @@ -31,6 +31,31 @@ ] } } + }, + "rest": { + "libraryClient": "ImageAnnotatorClient", + "rpcs": { + "AsyncBatchAnnotateFiles": { + "methods": [ + "AsyncBatchAnnotateFiles" + ] + }, + "AsyncBatchAnnotateImages": { + "methods": [ + "AsyncBatchAnnotateImages" + ] + }, + "BatchAnnotateFiles": { + "methods": [ + "BatchAnnotateFiles" + ] + }, + "BatchAnnotateImages": { + "methods": [ + "BatchAnnotateImages" + ] + } + } } } }, @@ -135,6 +160,106 @@ ] } } + }, + "rest": { + "libraryClient": "ProductSearchClient", + "rpcs": { + "AddProductToProductSet": { + "methods": [ + "AddProductToProductSet" + ] + }, + "CreateProduct": { + "methods": [ + "CreateProduct" + ] + }, + "CreateProductSet": { + "methods": [ + "CreateProductSet" + ] + }, + "CreateReferenceImage": { + "methods": [ + "CreateReferenceImage" + ] + }, + "DeleteProduct": { + "methods": [ + "DeleteProduct" + ] + }, + "DeleteProductSet": { + "methods": [ + "DeleteProductSet" + ] + }, + "DeleteReferenceImage": { + "methods": [ + "DeleteReferenceImage" + ] + }, + "GetProduct": { + "methods": [ + "GetProduct" + ] + }, + "GetProductSet": { + "methods": [ + "GetProductSet" + ] + }, + "GetReferenceImage": { + "methods": [ + "GetReferenceImage" + ] + }, + "ImportProductSets": { + "methods": [ + "ImportProductSets" + ] + }, + "ListProductSets": { + "methods": [ + "ListProductSets" + ] + }, + "ListProducts": { + "methods": [ + "ListProducts" + ] + }, + "ListProductsInProductSet": { + "methods": [ + "ListProductsInProductSet" + ] + }, + "ListReferenceImages": { + "methods": [ + "ListReferenceImages" + ] + }, + "PurgeProducts": { + "methods": [ + "PurgeProducts" + ] + }, + "RemoveProductFromProductSet": { + "methods": [ + "RemoveProductFromProductSet" + ] + }, + "UpdateProduct": { + "methods": [ + "UpdateProduct" + ] + }, + "UpdateProductSet": { + "methods": [ + "UpdateProductSet" + ] + } + } } } } diff --git a/vision/v2/apiv1/image_annotator_client.go b/vision/v2/apiv1/image_annotator_client.go index 92baa9c20268..f6b329a26500 100644 --- a/vision/v2/apiv1/image_annotator_client.go +++ b/vision/v2/apiv1/image_annotator_client.go @@ -17,9 +17,12 @@ package vision import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,13 +30,16 @@ import ( lroauto "cloud.google.com/go/longrunning/autogen" visionpb "cloud.google.com/go/vision/v2/apiv1/visionpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" ) var newImageAnnotatorClientHook clientHook @@ -111,6 +117,55 @@ func defaultImageAnnotatorCallOptions() *ImageAnnotatorCallOptions { } } +func defaultImageAnnotatorRESTCallOptions() *ImageAnnotatorCallOptions { + return &ImageAnnotatorCallOptions{ + BatchAnnotateImages: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + BatchAnnotateFiles: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + AsyncBatchAnnotateImages: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + AsyncBatchAnnotateFiles: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + } +} + // internalImageAnnotatorClient is an interface that defines the methods available from Cloud Vision API. type internalImageAnnotatorClient interface { Close() error @@ -316,6 +371,91 @@ func (c *imageAnnotatorGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type imageAnnotatorRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing ImageAnnotatorClient + CallOptions **ImageAnnotatorCallOptions +} + +// NewImageAnnotatorRESTClient creates a new image annotator rest client. +// +// Service that performs Google Cloud Vision API detection tasks over client +// images, such as face, landmark, logo, label, and text detection. The +// ImageAnnotator service returns detected entities from the images. +func NewImageAnnotatorRESTClient(ctx context.Context, opts ...option.ClientOption) (*ImageAnnotatorClient, error) { + clientOpts := append(defaultImageAnnotatorRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultImageAnnotatorRESTCallOptions() + c := &imageAnnotatorRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &ImageAnnotatorClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultImageAnnotatorRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://vision.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://vision.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://vision.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *imageAnnotatorRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *imageAnnotatorRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *imageAnnotatorRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *imageAnnotatorGRPCClient) BatchAnnotateImages(ctx context.Context, req *visionpb.BatchAnnotateImagesRequest, opts ...gax.CallOption) (*visionpb.BatchAnnotateImagesResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) @@ -408,9 +548,293 @@ func (c *imageAnnotatorGRPCClient) AsyncBatchAnnotateFiles(ctx context.Context, }, nil } +// BatchAnnotateImages run image detection and annotation for a batch of images. +func (c *imageAnnotatorRESTClient) BatchAnnotateImages(ctx context.Context, req *visionpb.BatchAnnotateImagesRequest, opts ...gax.CallOption) (*visionpb.BatchAnnotateImagesResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/images:annotate") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).BatchAnnotateImages[0:len((*c.CallOptions).BatchAnnotateImages):len((*c.CallOptions).BatchAnnotateImages)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &visionpb.BatchAnnotateImagesResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// BatchAnnotateFiles service that performs image detection and annotation for a batch of files. +// Now only “application/pdf”, “image/tiff” and “image/gif” are supported. +// +// This service will extract at most 5 (customers can specify which 5 in +// AnnotateFileRequest.pages) frames (gif) or pages (pdf or tiff) from each +// file provided and perform detection and annotation for each image +// extracted. +func (c *imageAnnotatorRESTClient) BatchAnnotateFiles(ctx context.Context, req *visionpb.BatchAnnotateFilesRequest, opts ...gax.CallOption) (*visionpb.BatchAnnotateFilesResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/files:annotate") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).BatchAnnotateFiles[0:len((*c.CallOptions).BatchAnnotateFiles):len((*c.CallOptions).BatchAnnotateFiles)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &visionpb.BatchAnnotateFilesResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// AsyncBatchAnnotateImages run asynchronous image detection and annotation for a list of images. +// +// Progress and results can be retrieved through the +// google.longrunning.Operations interface. +// Operation.metadata contains OperationMetadata (metadata). +// Operation.response contains AsyncBatchAnnotateImagesResponse (results). +// +// This service will write image annotation outputs to json files in customer +// GCS bucket, each json file containing BatchAnnotateImagesResponse proto. +func (c *imageAnnotatorRESTClient) AsyncBatchAnnotateImages(ctx context.Context, req *visionpb.AsyncBatchAnnotateImagesRequest, opts ...gax.CallOption) (*AsyncBatchAnnotateImagesOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/images:asyncBatchAnnotate") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &AsyncBatchAnnotateImagesOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// AsyncBatchAnnotateFiles run asynchronous image detection and annotation for a list of generic +// files, such as PDF files, which may contain multiple pages and multiple +// images per page. Progress and results can be retrieved through the +// google.longrunning.Operations interface. +// Operation.metadata contains OperationMetadata (metadata). +// Operation.response contains AsyncBatchAnnotateFilesResponse (results). +func (c *imageAnnotatorRESTClient) AsyncBatchAnnotateFiles(ctx context.Context, req *visionpb.AsyncBatchAnnotateFilesRequest, opts ...gax.CallOption) (*AsyncBatchAnnotateFilesOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/files:asyncBatchAnnotate") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &AsyncBatchAnnotateFilesOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + // AsyncBatchAnnotateFilesOperation manages a long-running operation from AsyncBatchAnnotateFiles. type AsyncBatchAnnotateFilesOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // AsyncBatchAnnotateFilesOperation returns a new AsyncBatchAnnotateFilesOperation from a given name. @@ -421,10 +845,21 @@ func (c *imageAnnotatorGRPCClient) AsyncBatchAnnotateFilesOperation(name string) } } +// AsyncBatchAnnotateFilesOperation returns a new AsyncBatchAnnotateFilesOperation from a given name. +// The name must be that of a previously created AsyncBatchAnnotateFilesOperation, possibly from a different process. +func (c *imageAnnotatorRESTClient) AsyncBatchAnnotateFilesOperation(name string) *AsyncBatchAnnotateFilesOperation { + override := fmt.Sprintf("/v1/%s", name) + return &AsyncBatchAnnotateFilesOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *AsyncBatchAnnotateFilesOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*visionpb.AsyncBatchAnnotateFilesResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp visionpb.AsyncBatchAnnotateFilesResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -442,6 +877,7 @@ func (op *AsyncBatchAnnotateFilesOperation) Wait(ctx context.Context, opts ...ga // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *AsyncBatchAnnotateFilesOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*visionpb.AsyncBatchAnnotateFilesResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp visionpb.AsyncBatchAnnotateFilesResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -479,7 +915,8 @@ func (op *AsyncBatchAnnotateFilesOperation) Name() string { // AsyncBatchAnnotateImagesOperation manages a long-running operation from AsyncBatchAnnotateImages. type AsyncBatchAnnotateImagesOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // AsyncBatchAnnotateImagesOperation returns a new AsyncBatchAnnotateImagesOperation from a given name. @@ -490,10 +927,21 @@ func (c *imageAnnotatorGRPCClient) AsyncBatchAnnotateImagesOperation(name string } } +// AsyncBatchAnnotateImagesOperation returns a new AsyncBatchAnnotateImagesOperation from a given name. +// The name must be that of a previously created AsyncBatchAnnotateImagesOperation, possibly from a different process. +func (c *imageAnnotatorRESTClient) AsyncBatchAnnotateImagesOperation(name string) *AsyncBatchAnnotateImagesOperation { + override := fmt.Sprintf("/v1/%s", name) + return &AsyncBatchAnnotateImagesOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *AsyncBatchAnnotateImagesOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*visionpb.AsyncBatchAnnotateImagesResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp visionpb.AsyncBatchAnnotateImagesResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -511,6 +959,7 @@ func (op *AsyncBatchAnnotateImagesOperation) Wait(ctx context.Context, opts ...g // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *AsyncBatchAnnotateImagesOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*visionpb.AsyncBatchAnnotateImagesResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp visionpb.AsyncBatchAnnotateImagesResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/vision/v2/apiv1/image_annotator_client_example_test.go b/vision/v2/apiv1/image_annotator_client_example_test.go index 115ca2fdfa64..1f96c0b9e898 100644 --- a/vision/v2/apiv1/image_annotator_client_example_test.go +++ b/vision/v2/apiv1/image_annotator_client_example_test.go @@ -40,6 +40,23 @@ func ExampleNewImageAnnotatorClient() { _ = c } +func ExampleNewImageAnnotatorRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := vision.NewImageAnnotatorRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleImageAnnotatorClient_BatchAnnotateImages() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/vision/v2/apiv1/product_search_client.go b/vision/v2/apiv1/product_search_client.go index c1c039f32f64..3dd52afa4bce 100644 --- a/vision/v2/apiv1/product_search_client.go +++ b/vision/v2/apiv1/product_search_client.go @@ -17,9 +17,12 @@ package vision import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,14 +30,17 @@ import ( lroauto "cloud.google.com/go/longrunning/autogen" visionpb "cloud.google.com/go/vision/v2/apiv1/visionpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -293,6 +299,170 @@ func defaultProductSearchCallOptions() *ProductSearchCallOptions { } } +func defaultProductSearchRESTCallOptions() *ProductSearchCallOptions { + return &ProductSearchCallOptions{ + CreateProductSet: []gax.CallOption{}, + ListProductSets: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + GetProductSet: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + UpdateProductSet: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + DeleteProductSet: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + CreateProduct: []gax.CallOption{}, + ListProducts: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + GetProduct: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + UpdateProduct: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + DeleteProduct: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + CreateReferenceImage: []gax.CallOption{}, + DeleteReferenceImage: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + ListReferenceImages: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + GetReferenceImage: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + AddProductToProductSet: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + RemoveProductFromProductSet: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + ListProductsInProductSet: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + ImportProductSets: []gax.CallOption{}, + PurgeProducts: []gax.CallOption{}, + } +} + // internalProductSearchClient is an interface that defines the methods available from Cloud Vision API. type internalProductSearchClient interface { Close() error @@ -738,6 +908,102 @@ func (c *productSearchGRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type productSearchRESTClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing ProductSearchClient + CallOptions **ProductSearchCallOptions +} + +// NewProductSearchRESTClient creates a new product search rest client. +// +// Manages Products and ProductSets of reference images for use in product +// search. It uses the following resource model: +// +// The API has a collection of ProductSet resources, named +// projects/*/locations/*/productSets/*, which acts as a way to put different +// products into groups to limit identification. +// +// In parallel, +// +// The API has a collection of Product resources, named +// projects/*/locations/*/products/* +// +// Each Product has a collection of ReferenceImage resources, named +// projects/*/locations/*/products/*/referenceImages/* +func NewProductSearchRESTClient(ctx context.Context, opts ...option.ClientOption) (*ProductSearchClient, error) { + clientOpts := append(defaultProductSearchRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultProductSearchRESTCallOptions() + c := &productSearchRESTClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &ProductSearchClient{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultProductSearchRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://vision.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://vision.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://vision.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *productSearchRESTClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *productSearchRESTClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *productSearchRESTClient) Connection() *grpc.ClientConn { + return nil +} func (c *productSearchGRPCClient) CreateProductSet(ctx context.Context, req *visionpb.CreateProductSetRequest, opts ...gax.CallOption) (*visionpb.ProductSet, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) @@ -1232,81 +1498,1464 @@ func (c *productSearchGRPCClient) PurgeProducts(ctx context.Context, req *vision }, nil } -// ImportProductSetsOperation manages a long-running operation from ImportProductSets. -type ImportProductSetsOperation struct { - lro *longrunning.Operation -} - -// ImportProductSetsOperation returns a new ImportProductSetsOperation from a given name. -// The name must be that of a previously created ImportProductSetsOperation, possibly from a different process. -func (c *productSearchGRPCClient) ImportProductSetsOperation(name string) *ImportProductSetsOperation { - return &ImportProductSetsOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), - } -} - -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// CreateProductSet creates and returns a new ProductSet resource. // -// See documentation of Poll for error-handling information. -func (op *ImportProductSetsOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*visionpb.ImportProductSetsResponse, error) { - var resp visionpb.ImportProductSetsResponse - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { +// Possible errors: +// +// Returns INVALID_ARGUMENT if display_name is missing, or is longer than +// 4096 characters. +func (c *productSearchRESTClient) CreateProductSet(ctx context.Context, req *visionpb.CreateProductSetRequest, opts ...gax.CallOption) (*visionpb.ProductSet, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetProductSet() + jsonReq, err := m.Marshal(body) + if err != nil { return nil, err } - return &resp, nil -} -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *ImportProductSetsOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*visionpb.ImportProductSetsResponse, error) { - var resp visionpb.ImportProductSetsResponse - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - if !op.Done() { - return nil, nil - } - return &resp, nil -} + baseUrl.Path += fmt.Sprintf("/v1/%v/productSets", req.GetParent()) -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *ImportProductSetsOperation) Metadata() (*visionpb.BatchOperationMetadata, error) { - var meta visionpb.BatchOperationMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { - return nil, err + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetProductSetId() != "" { + params.Add("productSetId", fmt.Sprintf("%v", req.GetProductSetId())) } - return &meta, nil -} -// Done reports whether the long-running operation has completed. -func (op *ImportProductSetsOperation) Done() bool { - return op.lro.Done() -} + baseUrl.RawQuery = params.Encode() -// 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 *ImportProductSetsOperation) Name() string { - return op.lro.Name() -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) -// PurgeProductsOperation manages a long-running operation from PurgeProducts. -type PurgeProductsOperation struct { - lro *longrunning.Operation + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateProductSet[0:len((*c.CallOptions).CreateProductSet):len((*c.CallOptions).CreateProductSet)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &visionpb.ProductSet{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil } -// PurgeProductsOperation returns a new PurgeProductsOperation from a given name. +// ListProductSets lists ProductSets in an unspecified order. +// +// Possible errors: +// +// Returns INVALID_ARGUMENT if page_size is greater than 100, or less +// than 1. +func (c *productSearchRESTClient) ListProductSets(ctx context.Context, req *visionpb.ListProductSetsRequest, opts ...gax.CallOption) *ProductSetIterator { + it := &ProductSetIterator{} + req = proto.Clone(req).(*visionpb.ListProductSetsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*visionpb.ProductSet, string, error) { + resp := &visionpb.ListProductSetsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/productSets", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetProductSets(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetProductSet gets information associated with a ProductSet. +// +// Possible errors: +// +// Returns NOT_FOUND if the ProductSet does not exist. +func (c *productSearchRESTClient) GetProductSet(ctx context.Context, req *visionpb.GetProductSetRequest, opts ...gax.CallOption) (*visionpb.ProductSet, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetProductSet[0:len((*c.CallOptions).GetProductSet):len((*c.CallOptions).GetProductSet)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &visionpb.ProductSet{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateProductSet makes changes to a ProductSet resource. +// Only display_name can be updated currently. +// +// Possible errors: +// +// Returns NOT_FOUND if the ProductSet does not exist. +// +// Returns INVALID_ARGUMENT if display_name is present in update_mask but +// missing from the request or longer than 4096 characters. +func (c *productSearchRESTClient) UpdateProductSet(ctx context.Context, req *visionpb.UpdateProductSetRequest, opts ...gax.CallOption) (*visionpb.ProductSet, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetProductSet() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetProductSet().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "product_set.name", url.QueryEscape(req.GetProductSet().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateProductSet[0:len((*c.CallOptions).UpdateProductSet):len((*c.CallOptions).UpdateProductSet)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &visionpb.ProductSet{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteProductSet permanently deletes a ProductSet. Products and ReferenceImages in the +// ProductSet are not deleted. +// +// The actual image files are not deleted from Google Cloud Storage. +func (c *productSearchRESTClient) DeleteProductSet(ctx context.Context, req *visionpb.DeleteProductSetRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// CreateProduct creates and returns a new product resource. +// +// Possible errors: +// +// Returns INVALID_ARGUMENT if display_name is missing or longer than 4096 +// characters. +// +// Returns INVALID_ARGUMENT if description is longer than 4096 characters. +// +// Returns INVALID_ARGUMENT if product_category is missing or invalid. +func (c *productSearchRESTClient) CreateProduct(ctx context.Context, req *visionpb.CreateProductRequest, opts ...gax.CallOption) (*visionpb.Product, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetProduct() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/products", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetProductId() != "" { + params.Add("productId", fmt.Sprintf("%v", req.GetProductId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateProduct[0:len((*c.CallOptions).CreateProduct):len((*c.CallOptions).CreateProduct)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &visionpb.Product{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListProducts lists products in an unspecified order. +// +// Possible errors: +// +// Returns INVALID_ARGUMENT if page_size is greater than 100 or less than 1. +func (c *productSearchRESTClient) ListProducts(ctx context.Context, req *visionpb.ListProductsRequest, opts ...gax.CallOption) *ProductIterator { + it := &ProductIterator{} + req = proto.Clone(req).(*visionpb.ListProductsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*visionpb.Product, string, error) { + resp := &visionpb.ListProductsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/products", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetProducts(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetProduct gets information associated with a Product. +// +// Possible errors: +// +// Returns NOT_FOUND if the Product does not exist. +func (c *productSearchRESTClient) GetProduct(ctx context.Context, req *visionpb.GetProductRequest, opts ...gax.CallOption) (*visionpb.Product, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetProduct[0:len((*c.CallOptions).GetProduct):len((*c.CallOptions).GetProduct)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &visionpb.Product{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateProduct makes changes to a Product resource. +// Only the display_name, description, and labels fields can be updated +// right now. +// +// If labels are updated, the change will not be reflected in queries until +// the next index time. +// +// Possible errors: +// +// Returns NOT_FOUND if the Product does not exist. +// +// Returns INVALID_ARGUMENT if display_name is present in update_mask but is +// missing from the request or longer than 4096 characters. +// +// Returns INVALID_ARGUMENT if description is present in update_mask but is +// longer than 4096 characters. +// +// Returns INVALID_ARGUMENT if product_category is present in update_mask. +func (c *productSearchRESTClient) UpdateProduct(ctx context.Context, req *visionpb.UpdateProductRequest, opts ...gax.CallOption) (*visionpb.Product, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetProduct() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetProduct().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "product.name", url.QueryEscape(req.GetProduct().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateProduct[0:len((*c.CallOptions).UpdateProduct):len((*c.CallOptions).UpdateProduct)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &visionpb.Product{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteProduct permanently deletes a product and its reference images. +// +// Metadata of the product and all its images will be deleted right away, but +// search queries against ProductSets containing the product may still work +// until all related caches are refreshed. +func (c *productSearchRESTClient) DeleteProduct(ctx context.Context, req *visionpb.DeleteProductRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// CreateReferenceImage creates and returns a new ReferenceImage resource. +// +// The bounding_poly field is optional. If bounding_poly is not specified, +// the system will try to detect regions of interest in the image that are +// compatible with the product_category on the parent product. If it is +// specified, detection is ALWAYS skipped. The system converts polygons into +// non-rotated rectangles. +// +// Note that the pipeline will resize the image if the image resolution is too +// large to process (above 50MP). +// +// Possible errors: +// +// Returns INVALID_ARGUMENT if the image_uri is missing or longer than 4096 +// characters. +// +// Returns INVALID_ARGUMENT if the product does not exist. +// +// Returns INVALID_ARGUMENT if bounding_poly is not provided, and nothing +// compatible with the parent product’s product_category is detected. +// +// Returns INVALID_ARGUMENT if bounding_poly contains more than 10 polygons. +func (c *productSearchRESTClient) CreateReferenceImage(ctx context.Context, req *visionpb.CreateReferenceImageRequest, opts ...gax.CallOption) (*visionpb.ReferenceImage, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetReferenceImage() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/referenceImages", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetReferenceImageId() != "" { + params.Add("referenceImageId", fmt.Sprintf("%v", req.GetReferenceImageId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateReferenceImage[0:len((*c.CallOptions).CreateReferenceImage):len((*c.CallOptions).CreateReferenceImage)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &visionpb.ReferenceImage{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteReferenceImage permanently deletes a reference image. +// +// The image metadata will be deleted right away, but search queries +// against ProductSets containing the image may still work until all related +// caches are refreshed. +// +// The actual image files are not deleted from Google Cloud Storage. +func (c *productSearchRESTClient) DeleteReferenceImage(ctx context.Context, req *visionpb.DeleteReferenceImageRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// ListReferenceImages lists reference images. +// +// Possible errors: +// +// Returns NOT_FOUND if the parent product does not exist. +// +// Returns INVALID_ARGUMENT if the page_size is greater than 100, or less +// than 1. +func (c *productSearchRESTClient) ListReferenceImages(ctx context.Context, req *visionpb.ListReferenceImagesRequest, opts ...gax.CallOption) *ReferenceImageIterator { + it := &ReferenceImageIterator{} + req = proto.Clone(req).(*visionpb.ListReferenceImagesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*visionpb.ReferenceImage, string, error) { + resp := &visionpb.ListReferenceImagesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/referenceImages", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetReferenceImages(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetReferenceImage gets information associated with a ReferenceImage. +// +// Possible errors: +// +// Returns NOT_FOUND if the specified image does not exist. +func (c *productSearchRESTClient) GetReferenceImage(ctx context.Context, req *visionpb.GetReferenceImageRequest, opts ...gax.CallOption) (*visionpb.ReferenceImage, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetReferenceImage[0:len((*c.CallOptions).GetReferenceImage):len((*c.CallOptions).GetReferenceImage)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &visionpb.ReferenceImage{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// AddProductToProductSet adds a Product to the specified ProductSet. If the Product is already +// present, no change is made. +// +// One Product can be added to at most 100 ProductSets. +// +// Possible errors: +// +// Returns NOT_FOUND if the Product or the ProductSet doesn’t exist. +func (c *productSearchRESTClient) AddProductToProductSet(ctx context.Context, req *visionpb.AddProductToProductSetRequest, opts ...gax.CallOption) error { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:addProduct", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// RemoveProductFromProductSet removes a Product from the specified ProductSet. +func (c *productSearchRESTClient) RemoveProductFromProductSet(ctx context.Context, req *visionpb.RemoveProductFromProductSetRequest, opts ...gax.CallOption) error { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:removeProduct", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// ListProductsInProductSet lists the Products in a ProductSet, in an unspecified order. If the +// ProductSet does not exist, the products field of the response will be +// empty. +// +// Possible errors: +// +// Returns INVALID_ARGUMENT if page_size is greater than 100 or less than 1. +func (c *productSearchRESTClient) ListProductsInProductSet(ctx context.Context, req *visionpb.ListProductsInProductSetRequest, opts ...gax.CallOption) *ProductIterator { + it := &ProductIterator{} + req = proto.Clone(req).(*visionpb.ListProductsInProductSetRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*visionpb.Product, string, error) { + resp := &visionpb.ListProductsInProductSetResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/products", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetProducts(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// ImportProductSets asynchronous API that imports a list of reference images to specified +// product sets based on a list of image information. +// +// The google.longrunning.Operation API can be used to keep track of the +// progress and results of the request. +// Operation.metadata contains BatchOperationMetadata. (progress) +// Operation.response contains ImportProductSetsResponse. (results) +// +// The input source of this method is a csv file on Google Cloud Storage. +// For the format of the csv file please see +// ImportProductSetsGcsSource.csv_file_uri. +func (c *productSearchRESTClient) ImportProductSets(ctx context.Context, req *visionpb.ImportProductSetsRequest, opts ...gax.CallOption) (*ImportProductSetsOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/productSets:import", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &ImportProductSetsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// PurgeProducts asynchronous API to delete all Products in a ProductSet or all Products +// that are in no ProductSet. +// +// If a Product is a member of the specified ProductSet in addition to other +// ProductSets, the Product will still be deleted. +// +// It is recommended to not delete the specified ProductSet until after this +// operation has completed. It is also recommended to not add any of the +// Products involved in the batch delete to a new ProductSet while this +// operation is running because those Products may still end up deleted. +// +// It’s not possible to undo the PurgeProducts operation. Therefore, it is +// recommended to keep the csv files used in ImportProductSets (if that was +// how you originally built the Product Set) before starting PurgeProducts, in +// case you need to re-import the data after deletion. +// +// If the plan is to purge all of the Products from a ProductSet and then +// re-use the empty ProductSet to re-import new Products into the empty +// ProductSet, you must wait until the PurgeProducts operation has finished +// for that ProductSet. +// +// The google.longrunning.Operation API can be used to keep track of the +// progress and results of the request. +// Operation.metadata contains BatchOperationMetadata. (progress) +func (c *productSearchRESTClient) PurgeProducts(ctx context.Context, req *visionpb.PurgeProductsRequest, opts ...gax.CallOption) (*PurgeProductsOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/products:purge", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &PurgeProductsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ImportProductSetsOperation manages a long-running operation from ImportProductSets. +type ImportProductSetsOperation struct { + lro *longrunning.Operation + pollPath string +} + +// ImportProductSetsOperation returns a new ImportProductSetsOperation from a given name. +// The name must be that of a previously created ImportProductSetsOperation, possibly from a different process. +func (c *productSearchGRPCClient) ImportProductSetsOperation(name string) *ImportProductSetsOperation { + return &ImportProductSetsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// ImportProductSetsOperation returns a new ImportProductSetsOperation from a given name. +// The name must be that of a previously created ImportProductSetsOperation, possibly from a different process. +func (c *productSearchRESTClient) ImportProductSetsOperation(name string) *ImportProductSetsOperation { + override := fmt.Sprintf("/v1/%s", name) + return &ImportProductSetsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *ImportProductSetsOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*visionpb.ImportProductSetsResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp visionpb.ImportProductSetsResponse + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *ImportProductSetsOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*visionpb.ImportProductSetsResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp visionpb.ImportProductSetsResponse + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *ImportProductSetsOperation) Metadata() (*visionpb.BatchOperationMetadata, error) { + var meta visionpb.BatchOperationMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *ImportProductSetsOperation) Done() bool { + return op.lro.Done() +} + +// 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 *ImportProductSetsOperation) Name() string { + return op.lro.Name() +} + +// PurgeProductsOperation manages a long-running operation from PurgeProducts. +type PurgeProductsOperation struct { + lro *longrunning.Operation + pollPath string +} + +// PurgeProductsOperation returns a new PurgeProductsOperation from a given name. // The name must be that of a previously created PurgeProductsOperation, possibly from a different process. func (c *productSearchGRPCClient) PurgeProductsOperation(name string) *PurgeProductsOperation { return &PurgeProductsOperation{ @@ -1314,10 +2963,21 @@ func (c *productSearchGRPCClient) PurgeProductsOperation(name string) *PurgeProd } } +// PurgeProductsOperation returns a new PurgeProductsOperation from a given name. +// The name must be that of a previously created PurgeProductsOperation, possibly from a different process. +func (c *productSearchRESTClient) PurgeProductsOperation(name string) *PurgeProductsOperation { + override := fmt.Sprintf("/v1/%s", name) + return &PurgeProductsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *PurgeProductsOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -1331,6 +2991,7 @@ func (op *PurgeProductsOperation) Wait(ctx context.Context, opts ...gax.CallOpti // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *PurgeProductsOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } diff --git a/vision/v2/apiv1/product_search_client_example_test.go b/vision/v2/apiv1/product_search_client_example_test.go index 07ca65163867..5b80f97006d4 100644 --- a/vision/v2/apiv1/product_search_client_example_test.go +++ b/vision/v2/apiv1/product_search_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewProductSearchClient() { _ = c } +func ExampleNewProductSearchRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := vision.NewProductSearchRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleProductSearchClient_CreateProductSet() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/vision/v2/apiv1/visionpb/geometry.pb.go b/vision/v2/apiv1/visionpb/geometry.pb.go index f3abf9dfa85a..0e6ce631369f 100644 --- a/vision/v2/apiv1/visionpb/geometry.pb.go +++ b/vision/v2/apiv1/visionpb/geometry.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/vision/v1/geometry.proto package visionpb diff --git a/vision/v2/apiv1/visionpb/image_annotator.pb.go b/vision/v2/apiv1/visionpb/image_annotator.pb.go index 2590bdb655ba..d49b9db90896 100644 --- a/vision/v2/apiv1/visionpb/image_annotator.pb.go +++ b/vision/v2/apiv1/visionpb/image_annotator.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/vision/v1/image_annotator.proto package visionpb @@ -550,18 +550,18 @@ type ImageSource struct { GcsImageUri string `protobuf:"bytes,1,opt,name=gcs_image_uri,json=gcsImageUri,proto3" json:"gcs_image_uri,omitempty"` // The URI of the source image. Can be either: // - // 1. A Google Cloud Storage URI of the form - // `gs://bucket_name/object_name`. Object versioning is not supported. See - // [Google Cloud Storage Request - // URIs](https://cloud.google.com/storage/docs/reference-uris) for more - // info. + // 1. A Google Cloud Storage URI of the form + // `gs://bucket_name/object_name`. Object versioning is not supported. See + // [Google Cloud Storage Request + // URIs](https://cloud.google.com/storage/docs/reference-uris) for more + // info. // - // 2. A publicly-accessible image HTTP/HTTPS URL. When fetching images from - // HTTP/HTTPS URLs, Google cannot guarantee that the request will be - // completed. Your request may fail if the specified host denies the - // request (e.g. due to request throttling or DOS prevention), or if Google - // throttles requests to the site for abuse prevention. You should not - // depend on externally-hosted images for production applications. + // 2. A publicly-accessible image HTTP/HTTPS URL. When fetching images from + // HTTP/HTTPS URLs, Google cannot guarantee that the request will be + // completed. Your request may fail if the specified host denies the + // request (e.g. due to request throttling or DOS prevention), or if Google + // throttles requests to the site for abuse prevention. You should not + // depend on externally-hosted images for production applications. // // When both `gcs_image_uri` and `image_uri` are specified, `image_uri` takes // precedence. @@ -2232,10 +2232,9 @@ type BatchAnnotateImagesRequest struct { // If no parent is specified, a region will be chosen automatically. // // Supported location-ids: - // - // `us`: USA country only, - // `asia`: East asia areas, like Japan, Taiwan, - // `eu`: The European Union. + // `us`: USA country only, + // `asia`: East asia areas, like Japan, Taiwan, + // `eu`: The European Union. // // Example: `projects/project-A/locations/eu`. Parent string `protobuf:"bytes,4,opt,name=parent,proto3" json:"parent,omitempty"` @@ -2520,10 +2519,9 @@ type BatchAnnotateFilesRequest struct { // If no parent is specified, a region will be chosen automatically. // // Supported location-ids: - // - // `us`: USA country only, - // `asia`: East asia areas, like Japan, Taiwan, - // `eu`: The European Union. + // `us`: USA country only, + // `asia`: East asia areas, like Japan, Taiwan, + // `eu`: The European Union. // // Example: `projects/project-A/locations/eu`. Parent string `protobuf:"bytes,3,opt,name=parent,proto3" json:"parent,omitempty"` @@ -2767,10 +2765,9 @@ type AsyncBatchAnnotateImagesRequest struct { // If no parent is specified, a region will be chosen automatically. // // Supported location-ids: - // - // `us`: USA country only, - // `asia`: East asia areas, like Japan, Taiwan, - // `eu`: The European Union. + // `us`: USA country only, + // `asia`: East asia areas, like Japan, Taiwan, + // `eu`: The European Union. // // Example: `projects/project-A/locations/eu`. Parent string `protobuf:"bytes,4,opt,name=parent,proto3" json:"parent,omitempty"` @@ -2894,10 +2891,9 @@ type AsyncBatchAnnotateFilesRequest struct { // If no parent is specified, a region will be chosen automatically. // // Supported location-ids: - // - // `us`: USA country only, - // `asia`: East asia areas, like Japan, Taiwan, - // `eu`: The European Union. + // `us`: USA country only, + // `asia`: East asia areas, like Japan, Taiwan, + // `eu`: The European Union. // // Example: `projects/project-A/locations/eu`. Parent string `protobuf:"bytes,4,opt,name=parent,proto3" json:"parent,omitempty"` diff --git a/vision/v2/apiv1/visionpb/product_search.pb.go b/vision/v2/apiv1/visionpb/product_search.pb.go index 2a576e49330e..ede994a474f3 100644 --- a/vision/v2/apiv1/visionpb/product_search.pb.go +++ b/vision/v2/apiv1/visionpb/product_search.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/vision/v1/product_search.proto package visionpb diff --git a/vision/v2/apiv1/visionpb/product_search_service.pb.go b/vision/v2/apiv1/visionpb/product_search_service.pb.go index e9188dd0a7b7..af506ec69c38 100644 --- a/vision/v2/apiv1/visionpb/product_search_service.pb.go +++ b/vision/v2/apiv1/visionpb/product_search_service.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/vision/v1/product_search_service.proto package visionpb @@ -1748,7 +1748,7 @@ type ImportProductSetsGcsSource struct { // The `labels` column (optional) is a line containing a list of // comma-separated key-value pairs, in the following format: // - // "key_1=value_1,key_2=value_2,...,key_n=value_n" + // "key_1=value_1,key_2=value_2,...,key_n=value_n" // // The `bounding-poly` column (optional) identifies one region of // interest from the image in the same manner as `CreateReferenceImage`. If @@ -1818,7 +1818,6 @@ type ImportProductSetsInputConfig struct { // The source of the input. // // Types that are assignable to Source: - // // *ImportProductSetsInputConfig_GcsSource Source isImportProductSetsInputConfig_Source `protobuf_oneof:"source"` } @@ -2139,7 +2138,6 @@ type PurgeProductsRequest struct { // The Products to delete. // // Types that are assignable to Target: - // // *PurgeProductsRequest_ProductSetPurgeConfig // *PurgeProductsRequest_DeleteOrphanProducts Target isPurgeProductsRequest_Target `protobuf_oneof:"target"` @@ -3458,15 +3456,15 @@ type ProductSearchClient interface { // // Possible errors: // - // - Returns INVALID_ARGUMENT if display_name is missing, or is longer than - // 4096 characters. + // * Returns INVALID_ARGUMENT if display_name is missing, or is longer than + // 4096 characters. CreateProductSet(ctx context.Context, in *CreateProductSetRequest, opts ...grpc.CallOption) (*ProductSet, error) // Lists ProductSets in an unspecified order. // // Possible errors: // - // - Returns INVALID_ARGUMENT if page_size is greater than 100, or less - // than 1. + // * Returns INVALID_ARGUMENT if page_size is greater than 100, or less + // than 1. ListProductSets(ctx context.Context, in *ListProductSetsRequest, opts ...grpc.CallOption) (*ListProductSetsResponse, error) // Gets information associated with a ProductSet. // @@ -3479,9 +3477,9 @@ type ProductSearchClient interface { // // Possible errors: // - // - Returns NOT_FOUND if the ProductSet does not exist. - // - Returns INVALID_ARGUMENT if display_name is present in update_mask but - // missing from the request or longer than 4096 characters. + // * Returns NOT_FOUND if the ProductSet does not exist. + // * Returns INVALID_ARGUMENT if display_name is present in update_mask but + // missing from the request or longer than 4096 characters. UpdateProductSet(ctx context.Context, in *UpdateProductSetRequest, opts ...grpc.CallOption) (*ProductSet, error) // Permanently deletes a ProductSet. Products and ReferenceImages in the // ProductSet are not deleted. @@ -3492,10 +3490,10 @@ type ProductSearchClient interface { // // Possible errors: // - // - Returns INVALID_ARGUMENT if display_name is missing or longer than 4096 - // characters. - // - Returns INVALID_ARGUMENT if description is longer than 4096 characters. - // - Returns INVALID_ARGUMENT if product_category is missing or invalid. + // * Returns INVALID_ARGUMENT if display_name is missing or longer than 4096 + // characters. + // * Returns INVALID_ARGUMENT if description is longer than 4096 characters. + // * Returns INVALID_ARGUMENT if product_category is missing or invalid. CreateProduct(ctx context.Context, in *CreateProductRequest, opts ...grpc.CallOption) (*Product, error) // Lists products in an unspecified order. // @@ -3518,12 +3516,12 @@ type ProductSearchClient interface { // // Possible errors: // - // - Returns NOT_FOUND if the Product does not exist. - // - Returns INVALID_ARGUMENT if display_name is present in update_mask but is - // missing from the request or longer than 4096 characters. - // - Returns INVALID_ARGUMENT if description is present in update_mask but is - // longer than 4096 characters. - // - Returns INVALID_ARGUMENT if product_category is present in update_mask. + // * Returns NOT_FOUND if the Product does not exist. + // * Returns INVALID_ARGUMENT if display_name is present in update_mask but is + // missing from the request or longer than 4096 characters. + // * Returns INVALID_ARGUMENT if description is present in update_mask but is + // longer than 4096 characters. + // * Returns INVALID_ARGUMENT if product_category is present in update_mask. UpdateProduct(ctx context.Context, in *UpdateProductRequest, opts ...grpc.CallOption) (*Product, error) // Permanently deletes a product and its reference images. // @@ -3544,12 +3542,12 @@ type ProductSearchClient interface { // // Possible errors: // - // - Returns INVALID_ARGUMENT if the image_uri is missing or longer than 4096 - // characters. - // - Returns INVALID_ARGUMENT if the product does not exist. - // - Returns INVALID_ARGUMENT if bounding_poly is not provided, and nothing - // compatible with the parent product's product_category is detected. - // - Returns INVALID_ARGUMENT if bounding_poly contains more than 10 polygons. + // * Returns INVALID_ARGUMENT if the image_uri is missing or longer than 4096 + // characters. + // * Returns INVALID_ARGUMENT if the product does not exist. + // * Returns INVALID_ARGUMENT if bounding_poly is not provided, and nothing + // compatible with the parent product's product_category is detected. + // * Returns INVALID_ARGUMENT if bounding_poly contains more than 10 polygons. CreateReferenceImage(ctx context.Context, in *CreateReferenceImageRequest, opts ...grpc.CallOption) (*ReferenceImage, error) // Permanently deletes a reference image. // @@ -3563,9 +3561,9 @@ type ProductSearchClient interface { // // Possible errors: // - // - Returns NOT_FOUND if the parent product does not exist. - // - Returns INVALID_ARGUMENT if the page_size is greater than 100, or less - // than 1. + // * Returns NOT_FOUND if the parent product does not exist. + // * Returns INVALID_ARGUMENT if the page_size is greater than 100, or less + // than 1. ListReferenceImages(ctx context.Context, in *ListReferenceImagesRequest, opts ...grpc.CallOption) (*ListReferenceImagesResponse, error) // Gets information associated with a ReferenceImage. // @@ -3816,15 +3814,15 @@ type ProductSearchServer interface { // // Possible errors: // - // - Returns INVALID_ARGUMENT if display_name is missing, or is longer than - // 4096 characters. + // * Returns INVALID_ARGUMENT if display_name is missing, or is longer than + // 4096 characters. CreateProductSet(context.Context, *CreateProductSetRequest) (*ProductSet, error) // Lists ProductSets in an unspecified order. // // Possible errors: // - // - Returns INVALID_ARGUMENT if page_size is greater than 100, or less - // than 1. + // * Returns INVALID_ARGUMENT if page_size is greater than 100, or less + // than 1. ListProductSets(context.Context, *ListProductSetsRequest) (*ListProductSetsResponse, error) // Gets information associated with a ProductSet. // @@ -3837,9 +3835,9 @@ type ProductSearchServer interface { // // Possible errors: // - // - Returns NOT_FOUND if the ProductSet does not exist. - // - Returns INVALID_ARGUMENT if display_name is present in update_mask but - // missing from the request or longer than 4096 characters. + // * Returns NOT_FOUND if the ProductSet does not exist. + // * Returns INVALID_ARGUMENT if display_name is present in update_mask but + // missing from the request or longer than 4096 characters. UpdateProductSet(context.Context, *UpdateProductSetRequest) (*ProductSet, error) // Permanently deletes a ProductSet. Products and ReferenceImages in the // ProductSet are not deleted. @@ -3850,10 +3848,10 @@ type ProductSearchServer interface { // // Possible errors: // - // - Returns INVALID_ARGUMENT if display_name is missing or longer than 4096 - // characters. - // - Returns INVALID_ARGUMENT if description is longer than 4096 characters. - // - Returns INVALID_ARGUMENT if product_category is missing or invalid. + // * Returns INVALID_ARGUMENT if display_name is missing or longer than 4096 + // characters. + // * Returns INVALID_ARGUMENT if description is longer than 4096 characters. + // * Returns INVALID_ARGUMENT if product_category is missing or invalid. CreateProduct(context.Context, *CreateProductRequest) (*Product, error) // Lists products in an unspecified order. // @@ -3876,12 +3874,12 @@ type ProductSearchServer interface { // // Possible errors: // - // - Returns NOT_FOUND if the Product does not exist. - // - Returns INVALID_ARGUMENT if display_name is present in update_mask but is - // missing from the request or longer than 4096 characters. - // - Returns INVALID_ARGUMENT if description is present in update_mask but is - // longer than 4096 characters. - // - Returns INVALID_ARGUMENT if product_category is present in update_mask. + // * Returns NOT_FOUND if the Product does not exist. + // * Returns INVALID_ARGUMENT if display_name is present in update_mask but is + // missing from the request or longer than 4096 characters. + // * Returns INVALID_ARGUMENT if description is present in update_mask but is + // longer than 4096 characters. + // * Returns INVALID_ARGUMENT if product_category is present in update_mask. UpdateProduct(context.Context, *UpdateProductRequest) (*Product, error) // Permanently deletes a product and its reference images. // @@ -3902,12 +3900,12 @@ type ProductSearchServer interface { // // Possible errors: // - // - Returns INVALID_ARGUMENT if the image_uri is missing or longer than 4096 - // characters. - // - Returns INVALID_ARGUMENT if the product does not exist. - // - Returns INVALID_ARGUMENT if bounding_poly is not provided, and nothing - // compatible with the parent product's product_category is detected. - // - Returns INVALID_ARGUMENT if bounding_poly contains more than 10 polygons. + // * Returns INVALID_ARGUMENT if the image_uri is missing or longer than 4096 + // characters. + // * Returns INVALID_ARGUMENT if the product does not exist. + // * Returns INVALID_ARGUMENT if bounding_poly is not provided, and nothing + // compatible with the parent product's product_category is detected. + // * Returns INVALID_ARGUMENT if bounding_poly contains more than 10 polygons. CreateReferenceImage(context.Context, *CreateReferenceImageRequest) (*ReferenceImage, error) // Permanently deletes a reference image. // @@ -3921,9 +3919,9 @@ type ProductSearchServer interface { // // Possible errors: // - // - Returns NOT_FOUND if the parent product does not exist. - // - Returns INVALID_ARGUMENT if the page_size is greater than 100, or less - // than 1. + // * Returns NOT_FOUND if the parent product does not exist. + // * Returns INVALID_ARGUMENT if the page_size is greater than 100, or less + // than 1. ListReferenceImages(context.Context, *ListReferenceImagesRequest) (*ListReferenceImagesResponse, error) // Gets information associated with a ReferenceImage. // diff --git a/vision/v2/apiv1/visionpb/text_annotation.pb.go b/vision/v2/apiv1/visionpb/text_annotation.pb.go index 99da98fc35a8..307388f1a47f 100644 --- a/vision/v2/apiv1/visionpb/text_annotation.pb.go +++ b/vision/v2/apiv1/visionpb/text_annotation.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/vision/v1/text_annotation.proto package visionpb @@ -336,17 +336,17 @@ type Block struct { // // * when the text is horizontal it might look like: // - // 0----1 - // | | - // 3----2 + // 0----1 + // | | + // 3----2 // // * when it's rotated 180 degrees around the top-left corner it becomes: // - // 2----3 - // | | - // 1----0 + // 2----3 + // | | + // 1----0 // - // and the vertex order will still be (0, 1, 2, 3). + // and the vertex order will still be (0, 1, 2, 3). BoundingBox *BoundingPoly `protobuf:"bytes,2,opt,name=bounding_box,json=boundingBox,proto3" json:"bounding_box,omitempty"` // List of paragraphs in this block (if this blocks is of type text). Paragraphs []*Paragraph `protobuf:"bytes,3,rep,name=paragraphs,proto3" json:"paragraphs,omitempty"` @@ -437,15 +437,15 @@ type Paragraph struct { // is represented as around the top-left corner as defined when the text is // read in the 'natural' orientation. // For example: - // - when the text is horizontal it might look like: - // 0----1 - // | | - // 3----2 - // - when it's rotated 180 degrees around the top-left corner it becomes: - // 2----3 - // | | - // 1----0 - // and the vertex order will still be (0, 1, 2, 3). + // * when the text is horizontal it might look like: + // 0----1 + // | | + // 3----2 + // * when it's rotated 180 degrees around the top-left corner it becomes: + // 2----3 + // | | + // 1----0 + // and the vertex order will still be (0, 1, 2, 3). BoundingBox *BoundingPoly `protobuf:"bytes,2,opt,name=bounding_box,json=boundingBox,proto3" json:"bounding_box,omitempty"` // List of all words in this paragraph. Words []*Word `protobuf:"bytes,3,rep,name=words,proto3" json:"words,omitempty"` @@ -527,15 +527,15 @@ type Word struct { // is represented as around the top-left corner as defined when the text is // read in the 'natural' orientation. // For example: - // - when the text is horizontal it might look like: - // 0----1 - // | | - // 3----2 - // - when it's rotated 180 degrees around the top-left corner it becomes: - // 2----3 - // | | - // 1----0 - // and the vertex order will still be (0, 1, 2, 3). + // * when the text is horizontal it might look like: + // 0----1 + // | | + // 3----2 + // * when it's rotated 180 degrees around the top-left corner it becomes: + // 2----3 + // | | + // 1----0 + // and the vertex order will still be (0, 1, 2, 3). BoundingBox *BoundingPoly `protobuf:"bytes,2,opt,name=bounding_box,json=boundingBox,proto3" json:"bounding_box,omitempty"` // List of symbols in the word. // The order of the symbols follows the natural reading order. @@ -618,15 +618,15 @@ type Symbol struct { // is represented as around the top-left corner as defined when the text is // read in the 'natural' orientation. // For example: - // - when the text is horizontal it might look like: - // 0----1 - // | | - // 3----2 - // - when it's rotated 180 degrees around the top-left corner it becomes: - // 2----3 - // | | - // 1----0 - // and the vertex order will still be (0, 1, 2, 3). + // * when the text is horizontal it might look like: + // 0----1 + // | | + // 3----2 + // * when it's rotated 180 degrees around the top-left corner it becomes: + // 2----3 + // | | + // 1----0 + // and the vertex order will still be (0, 1, 2, 3). BoundingBox *BoundingPoly `protobuf:"bytes,2,opt,name=bounding_box,json=boundingBox,proto3" json:"bounding_box,omitempty"` // The actual UTF-8 representation of the symbol. Text string `protobuf:"bytes,3,opt,name=text,proto3" json:"text,omitempty"` diff --git a/vision/v2/apiv1/visionpb/web_detection.pb.go b/vision/v2/apiv1/visionpb/web_detection.pb.go index 788a9efdfabf..6c58b5fb50a4 100644 --- a/vision/v2/apiv1/visionpb/web_detection.pb.go +++ b/vision/v2/apiv1/visionpb/web_detection.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/vision/v1/web_detection.proto package visionpb diff --git a/vision/v2/apiv1p1beta1/image_annotator_client.go b/vision/v2/apiv1p1beta1/image_annotator_client.go index 18bc54b1b40c..4ad2260b5188 100644 --- a/vision/v2/apiv1p1beta1/image_annotator_client.go +++ b/vision/v2/apiv1p1beta1/image_annotator_client.go @@ -328,6 +328,11 @@ func (c *imageAnnotatorRESTClient) BatchAnnotateImages(ctx context.Context, req } baseUrl.Path += fmt.Sprintf("/v1p1beta1/images:annotate") + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) opts = append((*c.CallOptions).BatchAnnotateImages[0:len((*c.CallOptions).BatchAnnotateImages):len((*c.CallOptions).BatchAnnotateImages)], opts...) diff --git a/vision/v2/apiv1p1beta1/visionpb/geometry.pb.go b/vision/v2/apiv1p1beta1/visionpb/geometry.pb.go index a7b975d32139..9b6ec33ad548 100644 --- a/vision/v2/apiv1p1beta1/visionpb/geometry.pb.go +++ b/vision/v2/apiv1p1beta1/visionpb/geometry.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/vision/v1p1beta1/geometry.proto package visionpb diff --git a/vision/v2/apiv1p1beta1/visionpb/image_annotator.pb.go b/vision/v2/apiv1p1beta1/visionpb/image_annotator.pb.go index eea6f1f09ea2..6d851344f96a 100644 --- a/vision/v2/apiv1p1beta1/visionpb/image_annotator.pb.go +++ b/vision/v2/apiv1p1beta1/visionpb/image_annotator.pb.go @@ -15,8 +15,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/vision/v1p1beta1/image_annotator.proto package visionpb diff --git a/vision/v2/apiv1p1beta1/visionpb/text_annotation.pb.go b/vision/v2/apiv1p1beta1/visionpb/text_annotation.pb.go index 3192c1f84e1b..868f286807ec 100644 --- a/vision/v2/apiv1p1beta1/visionpb/text_annotation.pb.go +++ b/vision/v2/apiv1p1beta1/visionpb/text_annotation.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/vision/v1p1beta1/text_annotation.proto package visionpb @@ -332,15 +332,15 @@ type Block struct { // is represented as around the top-left corner as defined when the text is // read in the 'natural' orientation. // For example: - // - when the text is horizontal it might look like: - // 0----1 - // | | - // 3----2 - // - when it's rotated 180 degrees around the top-left corner it becomes: - // 2----3 - // | | - // 1----0 - // and the vertice order will still be (0, 1, 2, 3). + // * when the text is horizontal it might look like: + // 0----1 + // | | + // 3----2 + // * when it's rotated 180 degrees around the top-left corner it becomes: + // 2----3 + // | | + // 1----0 + // and the vertice order will still be (0, 1, 2, 3). BoundingBox *BoundingPoly `protobuf:"bytes,2,opt,name=bounding_box,json=boundingBox,proto3" json:"bounding_box,omitempty"` // List of paragraphs in this block (if this blocks is of type text). Paragraphs []*Paragraph `protobuf:"bytes,3,rep,name=paragraphs,proto3" json:"paragraphs,omitempty"` @@ -431,15 +431,15 @@ type Paragraph struct { // is represented as around the top-left corner as defined when the text is // read in the 'natural' orientation. // For example: - // - when the text is horizontal it might look like: - // 0----1 - // | | - // 3----2 - // - when it's rotated 180 degrees around the top-left corner it becomes: - // 2----3 - // | | - // 1----0 - // and the vertice order will still be (0, 1, 2, 3). + // * when the text is horizontal it might look like: + // 0----1 + // | | + // 3----2 + // * when it's rotated 180 degrees around the top-left corner it becomes: + // 2----3 + // | | + // 1----0 + // and the vertice order will still be (0, 1, 2, 3). BoundingBox *BoundingPoly `protobuf:"bytes,2,opt,name=bounding_box,json=boundingBox,proto3" json:"bounding_box,omitempty"` // List of words in this paragraph. Words []*Word `protobuf:"bytes,3,rep,name=words,proto3" json:"words,omitempty"` @@ -521,15 +521,15 @@ type Word struct { // is represented as around the top-left corner as defined when the text is // read in the 'natural' orientation. // For example: - // - when the text is horizontal it might look like: - // 0----1 - // | | - // 3----2 - // - when it's rotated 180 degrees around the top-left corner it becomes: - // 2----3 - // | | - // 1----0 - // and the vertice order will still be (0, 1, 2, 3). + // * when the text is horizontal it might look like: + // 0----1 + // | | + // 3----2 + // * when it's rotated 180 degrees around the top-left corner it becomes: + // 2----3 + // | | + // 1----0 + // and the vertice order will still be (0, 1, 2, 3). BoundingBox *BoundingPoly `protobuf:"bytes,2,opt,name=bounding_box,json=boundingBox,proto3" json:"bounding_box,omitempty"` // List of symbols in the word. // The order of the symbols follows the natural reading order. @@ -612,15 +612,15 @@ type Symbol struct { // is represented as around the top-left corner as defined when the text is // read in the 'natural' orientation. // For example: - // - when the text is horizontal it might look like: - // 0----1 - // | | - // 3----2 - // - when it's rotated 180 degrees around the top-left corner it becomes: - // 2----3 - // | | - // 1----0 - // and the vertice order will still be (0, 1, 2, 3). + // * when the text is horizontal it might look like: + // 0----1 + // | | + // 3----2 + // * when it's rotated 180 degrees around the top-left corner it becomes: + // 2----3 + // | | + // 1----0 + // and the vertice order will still be (0, 1, 2, 3). BoundingBox *BoundingPoly `protobuf:"bytes,2,opt,name=bounding_box,json=boundingBox,proto3" json:"bounding_box,omitempty"` // The actual UTF-8 representation of the symbol. Text string `protobuf:"bytes,3,opt,name=text,proto3" json:"text,omitempty"` diff --git a/vision/v2/apiv1p1beta1/visionpb/web_detection.pb.go b/vision/v2/apiv1p1beta1/visionpb/web_detection.pb.go index 72c48a68a3de..aafa309a1a65 100644 --- a/vision/v2/apiv1p1beta1/visionpb/web_detection.pb.go +++ b/vision/v2/apiv1p1beta1/visionpb/web_detection.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/vision/v1p1beta1/web_detection.proto package visionpb diff --git a/vmmigration/apiv1/doc.go b/vmmigration/apiv1/doc.go index 06c516278473..43b0bf6ff0b0 100644 --- a/vmmigration/apiv1/doc.go +++ b/vmmigration/apiv1/doc.go @@ -87,6 +87,8 @@ package vmmigration // import "cloud.google.com/go/vmmigration/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -175,3 +177,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/vmmigration/apiv1/gapic_metadata.json b/vmmigration/apiv1/gapic_metadata.json index 071a1410042b..c5809526e179 100644 --- a/vmmigration/apiv1/gapic_metadata.json +++ b/vmmigration/apiv1/gapic_metadata.json @@ -231,6 +231,231 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "AddGroupMigration": { + "methods": [ + "AddGroupMigration" + ] + }, + "CancelCloneJob": { + "methods": [ + "CancelCloneJob" + ] + }, + "CancelCutoverJob": { + "methods": [ + "CancelCutoverJob" + ] + }, + "CreateCloneJob": { + "methods": [ + "CreateCloneJob" + ] + }, + "CreateCutoverJob": { + "methods": [ + "CreateCutoverJob" + ] + }, + "CreateDatacenterConnector": { + "methods": [ + "CreateDatacenterConnector" + ] + }, + "CreateGroup": { + "methods": [ + "CreateGroup" + ] + }, + "CreateMigratingVm": { + "methods": [ + "CreateMigratingVm" + ] + }, + "CreateSource": { + "methods": [ + "CreateSource" + ] + }, + "CreateTargetProject": { + "methods": [ + "CreateTargetProject" + ] + }, + "CreateUtilizationReport": { + "methods": [ + "CreateUtilizationReport" + ] + }, + "DeleteDatacenterConnector": { + "methods": [ + "DeleteDatacenterConnector" + ] + }, + "DeleteGroup": { + "methods": [ + "DeleteGroup" + ] + }, + "DeleteMigratingVm": { + "methods": [ + "DeleteMigratingVm" + ] + }, + "DeleteSource": { + "methods": [ + "DeleteSource" + ] + }, + "DeleteTargetProject": { + "methods": [ + "DeleteTargetProject" + ] + }, + "DeleteUtilizationReport": { + "methods": [ + "DeleteUtilizationReport" + ] + }, + "FetchInventory": { + "methods": [ + "FetchInventory" + ] + }, + "FinalizeMigration": { + "methods": [ + "FinalizeMigration" + ] + }, + "GetCloneJob": { + "methods": [ + "GetCloneJob" + ] + }, + "GetCutoverJob": { + "methods": [ + "GetCutoverJob" + ] + }, + "GetDatacenterConnector": { + "methods": [ + "GetDatacenterConnector" + ] + }, + "GetGroup": { + "methods": [ + "GetGroup" + ] + }, + "GetMigratingVm": { + "methods": [ + "GetMigratingVm" + ] + }, + "GetSource": { + "methods": [ + "GetSource" + ] + }, + "GetTargetProject": { + "methods": [ + "GetTargetProject" + ] + }, + "GetUtilizationReport": { + "methods": [ + "GetUtilizationReport" + ] + }, + "ListCloneJobs": { + "methods": [ + "ListCloneJobs" + ] + }, + "ListCutoverJobs": { + "methods": [ + "ListCutoverJobs" + ] + }, + "ListDatacenterConnectors": { + "methods": [ + "ListDatacenterConnectors" + ] + }, + "ListGroups": { + "methods": [ + "ListGroups" + ] + }, + "ListMigratingVms": { + "methods": [ + "ListMigratingVms" + ] + }, + "ListSources": { + "methods": [ + "ListSources" + ] + }, + "ListTargetProjects": { + "methods": [ + "ListTargetProjects" + ] + }, + "ListUtilizationReports": { + "methods": [ + "ListUtilizationReports" + ] + }, + "PauseMigration": { + "methods": [ + "PauseMigration" + ] + }, + "RemoveGroupMigration": { + "methods": [ + "RemoveGroupMigration" + ] + }, + "ResumeMigration": { + "methods": [ + "ResumeMigration" + ] + }, + "StartMigration": { + "methods": [ + "StartMigration" + ] + }, + "UpdateGroup": { + "methods": [ + "UpdateGroup" + ] + }, + "UpdateMigratingVm": { + "methods": [ + "UpdateMigratingVm" + ] + }, + "UpdateSource": { + "methods": [ + "UpdateSource" + ] + }, + "UpdateTargetProject": { + "methods": [ + "UpdateTargetProject" + ] + }, + "UpgradeAppliance": { + "methods": [ + "UpgradeAppliance" + ] + } + } } } } diff --git a/vmmigration/apiv1/vm_migration_client.go b/vmmigration/apiv1/vm_migration_client.go index b4c1551d2cbc..8827bbde4b78 100644 --- a/vmmigration/apiv1/vm_migration_client.go +++ b/vmmigration/apiv1/vm_migration_client.go @@ -17,9 +17,12 @@ package vmmigration import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,13 +30,16 @@ import ( lroauto "cloud.google.com/go/longrunning/autogen" vmmigrationpb "cloud.google.com/go/vmmigration/apiv1/vmmigrationpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -148,6 +154,55 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + ListSources: []gax.CallOption{}, + GetSource: []gax.CallOption{}, + CreateSource: []gax.CallOption{}, + UpdateSource: []gax.CallOption{}, + DeleteSource: []gax.CallOption{}, + FetchInventory: []gax.CallOption{}, + ListUtilizationReports: []gax.CallOption{}, + GetUtilizationReport: []gax.CallOption{}, + CreateUtilizationReport: []gax.CallOption{}, + DeleteUtilizationReport: []gax.CallOption{}, + ListDatacenterConnectors: []gax.CallOption{}, + GetDatacenterConnector: []gax.CallOption{}, + CreateDatacenterConnector: []gax.CallOption{}, + DeleteDatacenterConnector: []gax.CallOption{}, + UpgradeAppliance: []gax.CallOption{}, + CreateMigratingVm: []gax.CallOption{}, + ListMigratingVms: []gax.CallOption{}, + GetMigratingVm: []gax.CallOption{}, + UpdateMigratingVm: []gax.CallOption{}, + DeleteMigratingVm: []gax.CallOption{}, + StartMigration: []gax.CallOption{}, + ResumeMigration: []gax.CallOption{}, + PauseMigration: []gax.CallOption{}, + FinalizeMigration: []gax.CallOption{}, + CreateCloneJob: []gax.CallOption{}, + CancelCloneJob: []gax.CallOption{}, + ListCloneJobs: []gax.CallOption{}, + GetCloneJob: []gax.CallOption{}, + CreateCutoverJob: []gax.CallOption{}, + CancelCutoverJob: []gax.CallOption{}, + ListCutoverJobs: []gax.CallOption{}, + GetCutoverJob: []gax.CallOption{}, + ListGroups: []gax.CallOption{}, + GetGroup: []gax.CallOption{}, + CreateGroup: []gax.CallOption{}, + UpdateGroup: []gax.CallOption{}, + DeleteGroup: []gax.CallOption{}, + AddGroupMigration: []gax.CallOption{}, + RemoveGroupMigration: []gax.CallOption{}, + ListTargetProjects: []gax.CallOption{}, + GetTargetProject: []gax.CallOption{}, + CreateTargetProject: []gax.CallOption{}, + UpdateTargetProject: []gax.CallOption{}, + DeleteTargetProject: []gax.CallOption{}, + } +} + // internalClient is an interface that defines the methods available from VM Migration API. type internalClient interface { Close() error @@ -774,6 +829,89 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new vm migration rest client. +// +// VM Migration Service +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://vmmigration.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://vmmigration.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://vmmigration.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) ListSources(ctx context.Context, req *vmmigrationpb.ListSourcesRequest, opts ...gax.CallOption) *SourceIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1980,125 +2118,3352 @@ func (c *gRPCClient) DeleteTargetProject(ctx context.Context, req *vmmigrationpb }, nil } -// AddGroupMigrationOperation manages a long-running operation from AddGroupMigration. -type AddGroupMigrationOperation struct { - lro *longrunning.Operation -} +// ListSources lists Sources in a given project and location. +func (c *restClient) ListSources(ctx context.Context, req *vmmigrationpb.ListSourcesRequest, opts ...gax.CallOption) *SourceIterator { + it := &SourceIterator{} + req = proto.Clone(req).(*vmmigrationpb.ListSourcesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*vmmigrationpb.Source, string, error) { + resp := &vmmigrationpb.ListSourcesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/sources", req.GetParent()) -// AddGroupMigrationOperation returns a new AddGroupMigrationOperation from a given name. -// The name must be that of a previously created AddGroupMigrationOperation, possibly from a different process. -func (c *gRPCClient) AddGroupMigrationOperation(name string) *AddGroupMigrationOperation { - return &AddGroupMigrationOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetSources(), resp.GetNextPageToken(), nil } -} -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *AddGroupMigrationOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*vmmigrationpb.AddGroupMigrationResponse, error) { - var resp vmmigrationpb.AddGroupMigrationResponse - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { - return nil, err + 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 } - return &resp, nil -} -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *AddGroupMigrationOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*vmmigrationpb.AddGroupMigrationResponse, error) { - var resp vmmigrationpb.AddGroupMigrationResponse - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { - return nil, err - } - if !op.Done() { - return nil, nil - } - return &resp, nil + it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it } -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *AddGroupMigrationOperation) Metadata() (*vmmigrationpb.OperationMetadata, error) { - var meta vmmigrationpb.OperationMetadata - if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { - return nil, nil - } else if err != nil { +// GetSource gets details of a single Source. +func (c *restClient) GetSource(ctx context.Context, req *vmmigrationpb.GetSourceRequest, opts ...gax.CallOption) (*vmmigrationpb.Source, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - return &meta, nil -} + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) -// Done reports whether the long-running operation has completed. -func (op *AddGroupMigrationOperation) Done() bool { - return op.lro.Done() -} + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") -// 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 *AddGroupMigrationOperation) Name() string { - return op.lro.Name() -} + baseUrl.RawQuery = params.Encode() -// CancelCloneJobOperation manages a long-running operation from CancelCloneJob. -type CancelCloneJobOperation struct { - lro *longrunning.Operation -} + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) -// CancelCloneJobOperation returns a new CancelCloneJobOperation from a given name. -// The name must be that of a previously created CancelCloneJobOperation, possibly from a different process. -func (c *gRPCClient) CancelCloneJobOperation(name string) *CancelCloneJobOperation { - return &CancelCloneJobOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetSource[0:len((*c.CallOptions).GetSource):len((*c.CallOptions).GetSource)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &vmmigrationpb.Source{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e } + return resp, nil } -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *CancelCloneJobOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*vmmigrationpb.CancelCloneJobResponse, error) { - var resp vmmigrationpb.CancelCloneJobResponse - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { +// CreateSource creates a new Source in a given project and location. +func (c *restClient) CreateSource(ctx context.Context, req *vmmigrationpb.CreateSourceRequest, opts ...gax.CallOption) (*CreateSourceOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetSource() + jsonReq, err := m.Marshal(body) + if err != nil { return nil, err } - return &resp, nil -} -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *CancelCloneJobOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*vmmigrationpb.CancelCloneJobResponse, error) { - var resp vmmigrationpb.CancelCloneJobResponse - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - if !op.Done() { - return nil, nil + baseUrl.Path += fmt.Sprintf("/v1/%v/sources", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) } - return &resp, nil -} + params.Add("sourceId", fmt.Sprintf("%v", req.GetSourceId())) -// Metadata returns metadata associated with the long-running operation. -// Metadata itself does not contact the server, but Poll does. -// To get the latest metadata, call this method after a successful call to Poll. -// If the metadata is not available, the returned metadata and error are both nil. -func (op *CancelCloneJobOperation) Metadata() (*vmmigrationpb.OperationMetadata, error) { - var meta vmmigrationpb.OperationMetadata + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateSourceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateSource updates the parameters of a single Source. +func (c *restClient) UpdateSource(ctx context.Context, req *vmmigrationpb.UpdateSourceRequest, opts ...gax.CallOption) (*UpdateSourceOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetSource() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetSource().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "source.name", url.QueryEscape(req.GetSource().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateSourceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteSource deletes a single Source. +func (c *restClient) DeleteSource(ctx context.Context, req *vmmigrationpb.DeleteSourceRequest, opts ...gax.CallOption) (*DeleteSourceOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteSourceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// FetchInventory list remote source’s inventory of VMs. +// The remote source is the onprem vCenter (remote in the sense it’s not in +// Compute Engine). The inventory describes the list of existing VMs in that +// source. Note that this operation lists the VMs on the remote source, as +// opposed to listing the MigratingVms resources in the vmmigration service. +func (c *restClient) FetchInventory(ctx context.Context, req *vmmigrationpb.FetchInventoryRequest, opts ...gax.CallOption) (*vmmigrationpb.FetchInventoryResponse, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:fetchInventory", req.GetSource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetForceRefresh() { + params.Add("forceRefresh", fmt.Sprintf("%v", req.GetForceRefresh())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "source", url.QueryEscape(req.GetSource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).FetchInventory[0:len((*c.CallOptions).FetchInventory):len((*c.CallOptions).FetchInventory)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &vmmigrationpb.FetchInventoryResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListUtilizationReports lists Utilization Reports of the given Source. +func (c *restClient) ListUtilizationReports(ctx context.Context, req *vmmigrationpb.ListUtilizationReportsRequest, opts ...gax.CallOption) *UtilizationReportIterator { + it := &UtilizationReportIterator{} + req = proto.Clone(req).(*vmmigrationpb.ListUtilizationReportsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*vmmigrationpb.UtilizationReport, string, error) { + resp := &vmmigrationpb.ListUtilizationReportsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/utilizationReports", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + if req.GetView() != 0 { + params.Add("view", fmt.Sprintf("%v", req.GetView())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetUtilizationReports(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetUtilizationReport gets a single Utilization Report. +func (c *restClient) GetUtilizationReport(ctx context.Context, req *vmmigrationpb.GetUtilizationReportRequest, opts ...gax.CallOption) (*vmmigrationpb.UtilizationReport, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetView() != 0 { + params.Add("view", fmt.Sprintf("%v", req.GetView())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetUtilizationReport[0:len((*c.CallOptions).GetUtilizationReport):len((*c.CallOptions).GetUtilizationReport)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &vmmigrationpb.UtilizationReport{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateUtilizationReport creates a new UtilizationReport. +func (c *restClient) CreateUtilizationReport(ctx context.Context, req *vmmigrationpb.CreateUtilizationReportRequest, opts ...gax.CallOption) (*CreateUtilizationReportOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetUtilizationReport() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/utilizationReports", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + params.Add("utilizationReportId", fmt.Sprintf("%v", req.GetUtilizationReportId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateUtilizationReportOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteUtilizationReport deletes a single Utilization Report. +func (c *restClient) DeleteUtilizationReport(ctx context.Context, req *vmmigrationpb.DeleteUtilizationReportRequest, opts ...gax.CallOption) (*DeleteUtilizationReportOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteUtilizationReportOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListDatacenterConnectors lists DatacenterConnectors in a given Source. +func (c *restClient) ListDatacenterConnectors(ctx context.Context, req *vmmigrationpb.ListDatacenterConnectorsRequest, opts ...gax.CallOption) *DatacenterConnectorIterator { + it := &DatacenterConnectorIterator{} + req = proto.Clone(req).(*vmmigrationpb.ListDatacenterConnectorsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*vmmigrationpb.DatacenterConnector, string, error) { + resp := &vmmigrationpb.ListDatacenterConnectorsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/datacenterConnectors", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetDatacenterConnectors(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetDatacenterConnector gets details of a single DatacenterConnector. +func (c *restClient) GetDatacenterConnector(ctx context.Context, req *vmmigrationpb.GetDatacenterConnectorRequest, opts ...gax.CallOption) (*vmmigrationpb.DatacenterConnector, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetDatacenterConnector[0:len((*c.CallOptions).GetDatacenterConnector):len((*c.CallOptions).GetDatacenterConnector)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &vmmigrationpb.DatacenterConnector{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateDatacenterConnector creates a new DatacenterConnector in a given Source. +func (c *restClient) CreateDatacenterConnector(ctx context.Context, req *vmmigrationpb.CreateDatacenterConnectorRequest, opts ...gax.CallOption) (*CreateDatacenterConnectorOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetDatacenterConnector() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/datacenterConnectors", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("datacenterConnectorId", fmt.Sprintf("%v", req.GetDatacenterConnectorId())) + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateDatacenterConnectorOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteDatacenterConnector deletes a single DatacenterConnector. +func (c *restClient) DeleteDatacenterConnector(ctx context.Context, req *vmmigrationpb.DeleteDatacenterConnectorRequest, opts ...gax.CallOption) (*DeleteDatacenterConnectorOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteDatacenterConnectorOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpgradeAppliance upgrades the appliance relate to this DatacenterConnector to the in-place +// updateable version. +func (c *restClient) UpgradeAppliance(ctx context.Context, req *vmmigrationpb.UpgradeApplianceRequest, opts ...gax.CallOption) (*UpgradeApplianceOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:upgradeAppliance", req.GetDatacenterConnector()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "datacenter_connector", url.QueryEscape(req.GetDatacenterConnector()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpgradeApplianceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// CreateMigratingVm creates a new MigratingVm in a given Source. +func (c *restClient) CreateMigratingVm(ctx context.Context, req *vmmigrationpb.CreateMigratingVmRequest, opts ...gax.CallOption) (*CreateMigratingVmOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetMigratingVm() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/migratingVms", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("migratingVmId", fmt.Sprintf("%v", req.GetMigratingVmId())) + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateMigratingVmOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListMigratingVms lists MigratingVms in a given Source. +func (c *restClient) ListMigratingVms(ctx context.Context, req *vmmigrationpb.ListMigratingVmsRequest, opts ...gax.CallOption) *MigratingVmIterator { + it := &MigratingVmIterator{} + req = proto.Clone(req).(*vmmigrationpb.ListMigratingVmsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*vmmigrationpb.MigratingVm, string, error) { + resp := &vmmigrationpb.ListMigratingVmsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/migratingVms", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + if req.GetView() != 0 { + params.Add("view", fmt.Sprintf("%v", req.GetView())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetMigratingVms(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetMigratingVm gets details of a single MigratingVm. +func (c *restClient) GetMigratingVm(ctx context.Context, req *vmmigrationpb.GetMigratingVmRequest, opts ...gax.CallOption) (*vmmigrationpb.MigratingVm, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetView() != 0 { + params.Add("view", fmt.Sprintf("%v", req.GetView())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetMigratingVm[0:len((*c.CallOptions).GetMigratingVm):len((*c.CallOptions).GetMigratingVm)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &vmmigrationpb.MigratingVm{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// UpdateMigratingVm updates the parameters of a single MigratingVm. +func (c *restClient) UpdateMigratingVm(ctx context.Context, req *vmmigrationpb.UpdateMigratingVmRequest, opts ...gax.CallOption) (*UpdateMigratingVmOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetMigratingVm() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetMigratingVm().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "migrating_vm.name", url.QueryEscape(req.GetMigratingVm().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateMigratingVmOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteMigratingVm deletes a single MigratingVm. +func (c *restClient) DeleteMigratingVm(ctx context.Context, req *vmmigrationpb.DeleteMigratingVmRequest, opts ...gax.CallOption) (*DeleteMigratingVmOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteMigratingVmOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// StartMigration starts migration for a VM. Starts the process of uploading +// data and creating snapshots, in replication cycles scheduled by the policy. +func (c *restClient) StartMigration(ctx context.Context, req *vmmigrationpb.StartMigrationRequest, opts ...gax.CallOption) (*StartMigrationOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:startMigration", req.GetMigratingVm()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "migrating_vm", url.QueryEscape(req.GetMigratingVm()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &StartMigrationOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ResumeMigration resumes a migration for a VM. When called on a paused migration, will start +// the process of uploading data and creating snapshots; when called on a +// completed cut-over migration, will update the migration to active state and +// start the process of uploading data and creating snapshots. +func (c *restClient) ResumeMigration(ctx context.Context, req *vmmigrationpb.ResumeMigrationRequest, opts ...gax.CallOption) (*ResumeMigrationOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:resumeMigration", req.GetMigratingVm()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "migrating_vm", url.QueryEscape(req.GetMigratingVm()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &ResumeMigrationOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// PauseMigration pauses a migration for a VM. If cycle tasks are running they will be +// cancelled, preserving source task data. Further replication cycles will not +// be triggered while the VM is paused. +func (c *restClient) PauseMigration(ctx context.Context, req *vmmigrationpb.PauseMigrationRequest, opts ...gax.CallOption) (*PauseMigrationOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:pauseMigration", req.GetMigratingVm()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "migrating_vm", url.QueryEscape(req.GetMigratingVm()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &PauseMigrationOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// FinalizeMigration marks a migration as completed, deleting migration resources that are no +// longer being used. Only applicable after cutover is done. +func (c *restClient) FinalizeMigration(ctx context.Context, req *vmmigrationpb.FinalizeMigrationRequest, opts ...gax.CallOption) (*FinalizeMigrationOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:finalizeMigration", req.GetMigratingVm()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "migrating_vm", url.QueryEscape(req.GetMigratingVm()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &FinalizeMigrationOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// CreateCloneJob initiates a Clone of a specific migrating VM. +func (c *restClient) CreateCloneJob(ctx context.Context, req *vmmigrationpb.CreateCloneJobRequest, opts ...gax.CallOption) (*CreateCloneJobOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetCloneJob() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/cloneJobs", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("cloneJobId", fmt.Sprintf("%v", req.GetCloneJobId())) + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateCloneJobOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// CancelCloneJob initiates the cancellation of a running clone job. +func (c *restClient) CancelCloneJob(ctx context.Context, req *vmmigrationpb.CancelCloneJobRequest, opts ...gax.CallOption) (*CancelCloneJobOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CancelCloneJobOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListCloneJobs lists CloneJobs of a given migrating VM. +func (c *restClient) ListCloneJobs(ctx context.Context, req *vmmigrationpb.ListCloneJobsRequest, opts ...gax.CallOption) *CloneJobIterator { + it := &CloneJobIterator{} + req = proto.Clone(req).(*vmmigrationpb.ListCloneJobsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*vmmigrationpb.CloneJob, string, error) { + resp := &vmmigrationpb.ListCloneJobsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/cloneJobs", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetCloneJobs(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetCloneJob gets details of a single CloneJob. +func (c *restClient) GetCloneJob(ctx context.Context, req *vmmigrationpb.GetCloneJobRequest, opts ...gax.CallOption) (*vmmigrationpb.CloneJob, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetCloneJob[0:len((*c.CallOptions).GetCloneJob):len((*c.CallOptions).GetCloneJob)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &vmmigrationpb.CloneJob{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateCutoverJob initiates a Cutover of a specific migrating VM. +// The returned LRO is completed when the cutover job resource is created +// and the job is initiated. +func (c *restClient) CreateCutoverJob(ctx context.Context, req *vmmigrationpb.CreateCutoverJobRequest, opts ...gax.CallOption) (*CreateCutoverJobOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetCutoverJob() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/cutoverJobs", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("cutoverJobId", fmt.Sprintf("%v", req.GetCutoverJobId())) + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateCutoverJobOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// CancelCutoverJob initiates the cancellation of a running cutover job. +func (c *restClient) CancelCutoverJob(ctx context.Context, req *vmmigrationpb.CancelCutoverJobRequest, opts ...gax.CallOption) (*CancelCutoverJobOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:cancel", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CancelCutoverJobOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListCutoverJobs lists CutoverJobs of a given migrating VM. +func (c *restClient) ListCutoverJobs(ctx context.Context, req *vmmigrationpb.ListCutoverJobsRequest, opts ...gax.CallOption) *CutoverJobIterator { + it := &CutoverJobIterator{} + req = proto.Clone(req).(*vmmigrationpb.ListCutoverJobsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*vmmigrationpb.CutoverJob, string, error) { + resp := &vmmigrationpb.ListCutoverJobsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/cutoverJobs", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetCutoverJobs(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetCutoverJob gets details of a single CutoverJob. +func (c *restClient) GetCutoverJob(ctx context.Context, req *vmmigrationpb.GetCutoverJobRequest, opts ...gax.CallOption) (*vmmigrationpb.CutoverJob, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetCutoverJob[0:len((*c.CallOptions).GetCutoverJob):len((*c.CallOptions).GetCutoverJob)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &vmmigrationpb.CutoverJob{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListGroups lists Groups in a given project and location. +func (c *restClient) ListGroups(ctx context.Context, req *vmmigrationpb.ListGroupsRequest, opts ...gax.CallOption) *GroupIterator { + it := &GroupIterator{} + req = proto.Clone(req).(*vmmigrationpb.ListGroupsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*vmmigrationpb.Group, string, error) { + resp := &vmmigrationpb.ListGroupsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/groups", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetGroups(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetGroup gets details of a single Group. +func (c *restClient) GetGroup(ctx context.Context, req *vmmigrationpb.GetGroupRequest, opts ...gax.CallOption) (*vmmigrationpb.Group, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetGroup[0:len((*c.CallOptions).GetGroup):len((*c.CallOptions).GetGroup)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &vmmigrationpb.Group{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateGroup creates a new Group in a given project and location. +func (c *restClient) CreateGroup(ctx context.Context, req *vmmigrationpb.CreateGroupRequest, opts ...gax.CallOption) (*CreateGroupOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetGroup() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/groups", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("groupId", fmt.Sprintf("%v", req.GetGroupId())) + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateGroupOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateGroup updates the parameters of a single Group. +func (c *restClient) UpdateGroup(ctx context.Context, req *vmmigrationpb.UpdateGroupRequest, opts ...gax.CallOption) (*UpdateGroupOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetGroup() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetGroup().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "group.name", url.QueryEscape(req.GetGroup().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateGroupOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteGroup deletes a single Group. +func (c *restClient) DeleteGroup(ctx context.Context, req *vmmigrationpb.DeleteGroupRequest, opts ...gax.CallOption) (*DeleteGroupOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteGroupOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// AddGroupMigration adds a MigratingVm to a Group. +func (c *restClient) AddGroupMigration(ctx context.Context, req *vmmigrationpb.AddGroupMigrationRequest, opts ...gax.CallOption) (*AddGroupMigrationOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:addGroupMigration", req.GetGroup()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "group", url.QueryEscape(req.GetGroup()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &AddGroupMigrationOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// RemoveGroupMigration removes a MigratingVm from a Group. +func (c *restClient) RemoveGroupMigration(ctx context.Context, req *vmmigrationpb.RemoveGroupMigrationRequest, opts ...gax.CallOption) (*RemoveGroupMigrationOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:removeGroupMigration", req.GetGroup()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "group", url.QueryEscape(req.GetGroup()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &RemoveGroupMigrationOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListTargetProjects lists TargetProjects in a given project. +// +// NOTE: TargetProject is a global resource; hence the only supported value +// for location is global. +func (c *restClient) ListTargetProjects(ctx context.Context, req *vmmigrationpb.ListTargetProjectsRequest, opts ...gax.CallOption) *TargetProjectIterator { + it := &TargetProjectIterator{} + req = proto.Clone(req).(*vmmigrationpb.ListTargetProjectsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*vmmigrationpb.TargetProject, string, error) { + resp := &vmmigrationpb.ListTargetProjectsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/targetProjects", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetTargetProjects(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetTargetProject gets details of a single TargetProject. +// +// NOTE: TargetProject is a global resource; hence the only supported value +// for location is global. +func (c *restClient) GetTargetProject(ctx context.Context, req *vmmigrationpb.GetTargetProjectRequest, opts ...gax.CallOption) (*vmmigrationpb.TargetProject, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetTargetProject[0:len((*c.CallOptions).GetTargetProject):len((*c.CallOptions).GetTargetProject)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &vmmigrationpb.TargetProject{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateTargetProject creates a new TargetProject in a given project. +// +// NOTE: TargetProject is a global resource; hence the only supported value +// for location is global. +func (c *restClient) CreateTargetProject(ctx context.Context, req *vmmigrationpb.CreateTargetProjectRequest, opts ...gax.CallOption) (*CreateTargetProjectOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetTargetProject() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/targetProjects", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + params.Add("targetProjectId", fmt.Sprintf("%v", req.GetTargetProjectId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateTargetProjectOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateTargetProject updates the parameters of a single TargetProject. +// +// NOTE: TargetProject is a global resource; hence the only supported value +// for location is global. +func (c *restClient) UpdateTargetProject(ctx context.Context, req *vmmigrationpb.UpdateTargetProjectRequest, opts ...gax.CallOption) (*UpdateTargetProjectOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetTargetProject() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetTargetProject().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "target_project.name", url.QueryEscape(req.GetTargetProject().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateTargetProjectOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteTargetProject deletes a single TargetProject. +// +// NOTE: TargetProject is a global resource; hence the only supported value +// for location is global. +func (c *restClient) DeleteTargetProject(ctx context.Context, req *vmmigrationpb.DeleteTargetProjectRequest, opts ...gax.CallOption) (*DeleteTargetProjectOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteTargetProjectOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// AddGroupMigrationOperation manages a long-running operation from AddGroupMigration. +type AddGroupMigrationOperation struct { + lro *longrunning.Operation + pollPath string +} + +// AddGroupMigrationOperation returns a new AddGroupMigrationOperation from a given name. +// The name must be that of a previously created AddGroupMigrationOperation, possibly from a different process. +func (c *gRPCClient) AddGroupMigrationOperation(name string) *AddGroupMigrationOperation { + return &AddGroupMigrationOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// AddGroupMigrationOperation returns a new AddGroupMigrationOperation from a given name. +// The name must be that of a previously created AddGroupMigrationOperation, possibly from a different process. +func (c *restClient) AddGroupMigrationOperation(name string) *AddGroupMigrationOperation { + override := fmt.Sprintf("/v1/%s", name) + return &AddGroupMigrationOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *AddGroupMigrationOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*vmmigrationpb.AddGroupMigrationResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp vmmigrationpb.AddGroupMigrationResponse + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *AddGroupMigrationOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*vmmigrationpb.AddGroupMigrationResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp vmmigrationpb.AddGroupMigrationResponse + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *AddGroupMigrationOperation) Metadata() (*vmmigrationpb.OperationMetadata, error) { + var meta vmmigrationpb.OperationMetadata + if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { + return nil, nil + } else if err != nil { + return nil, err + } + return &meta, nil +} + +// Done reports whether the long-running operation has completed. +func (op *AddGroupMigrationOperation) Done() bool { + return op.lro.Done() +} + +// 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 *AddGroupMigrationOperation) Name() string { + return op.lro.Name() +} + +// CancelCloneJobOperation manages a long-running operation from CancelCloneJob. +type CancelCloneJobOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CancelCloneJobOperation returns a new CancelCloneJobOperation from a given name. +// The name must be that of a previously created CancelCloneJobOperation, possibly from a different process. +func (c *gRPCClient) CancelCloneJobOperation(name string) *CancelCloneJobOperation { + return &CancelCloneJobOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CancelCloneJobOperation returns a new CancelCloneJobOperation from a given name. +// The name must be that of a previously created CancelCloneJobOperation, possibly from a different process. +func (c *restClient) CancelCloneJobOperation(name string) *CancelCloneJobOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CancelCloneJobOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CancelCloneJobOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*vmmigrationpb.CancelCloneJobResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp vmmigrationpb.CancelCloneJobResponse + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *CancelCloneJobOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*vmmigrationpb.CancelCloneJobResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp vmmigrationpb.CancelCloneJobResponse + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } + return &resp, nil +} + +// Metadata returns metadata associated with the long-running operation. +// Metadata itself does not contact the server, but Poll does. +// To get the latest metadata, call this method after a successful call to Poll. +// If the metadata is not available, the returned metadata and error are both nil. +func (op *CancelCloneJobOperation) Metadata() (*vmmigrationpb.OperationMetadata, error) { + var meta vmmigrationpb.OperationMetadata if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { return nil, nil } else if err != nil { @@ -2120,7 +5485,8 @@ func (op *CancelCloneJobOperation) Name() string { // CancelCutoverJobOperation manages a long-running operation from CancelCutoverJob. type CancelCutoverJobOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CancelCutoverJobOperation returns a new CancelCutoverJobOperation from a given name. @@ -2131,10 +5497,21 @@ func (c *gRPCClient) CancelCutoverJobOperation(name string) *CancelCutoverJobOpe } } +// CancelCutoverJobOperation returns a new CancelCutoverJobOperation from a given name. +// The name must be that of a previously created CancelCutoverJobOperation, possibly from a different process. +func (c *restClient) CancelCutoverJobOperation(name string) *CancelCutoverJobOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CancelCutoverJobOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CancelCutoverJobOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*vmmigrationpb.CancelCutoverJobResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmmigrationpb.CancelCutoverJobResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2152,6 +5529,7 @@ func (op *CancelCutoverJobOperation) Wait(ctx context.Context, opts ...gax.CallO // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CancelCutoverJobOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*vmmigrationpb.CancelCutoverJobResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmmigrationpb.CancelCutoverJobResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2189,7 +5567,8 @@ func (op *CancelCutoverJobOperation) Name() string { // CreateCloneJobOperation manages a long-running operation from CreateCloneJob. type CreateCloneJobOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateCloneJobOperation returns a new CreateCloneJobOperation from a given name. @@ -2200,10 +5579,21 @@ func (c *gRPCClient) CreateCloneJobOperation(name string) *CreateCloneJobOperati } } +// CreateCloneJobOperation returns a new CreateCloneJobOperation from a given name. +// The name must be that of a previously created CreateCloneJobOperation, possibly from a different process. +func (c *restClient) CreateCloneJobOperation(name string) *CreateCloneJobOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateCloneJobOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateCloneJobOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*vmmigrationpb.CloneJob, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmmigrationpb.CloneJob if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2221,6 +5611,7 @@ func (op *CreateCloneJobOperation) Wait(ctx context.Context, opts ...gax.CallOpt // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateCloneJobOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*vmmigrationpb.CloneJob, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmmigrationpb.CloneJob if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2258,7 +5649,8 @@ func (op *CreateCloneJobOperation) Name() string { // CreateCutoverJobOperation manages a long-running operation from CreateCutoverJob. type CreateCutoverJobOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateCutoverJobOperation returns a new CreateCutoverJobOperation from a given name. @@ -2269,10 +5661,21 @@ func (c *gRPCClient) CreateCutoverJobOperation(name string) *CreateCutoverJobOpe } } +// CreateCutoverJobOperation returns a new CreateCutoverJobOperation from a given name. +// The name must be that of a previously created CreateCutoverJobOperation, possibly from a different process. +func (c *restClient) CreateCutoverJobOperation(name string) *CreateCutoverJobOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateCutoverJobOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateCutoverJobOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*vmmigrationpb.CutoverJob, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmmigrationpb.CutoverJob if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2290,6 +5693,7 @@ func (op *CreateCutoverJobOperation) Wait(ctx context.Context, opts ...gax.CallO // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateCutoverJobOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*vmmigrationpb.CutoverJob, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmmigrationpb.CutoverJob if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2327,7 +5731,8 @@ func (op *CreateCutoverJobOperation) Name() string { // CreateDatacenterConnectorOperation manages a long-running operation from CreateDatacenterConnector. type CreateDatacenterConnectorOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateDatacenterConnectorOperation returns a new CreateDatacenterConnectorOperation from a given name. @@ -2338,10 +5743,21 @@ func (c *gRPCClient) CreateDatacenterConnectorOperation(name string) *CreateData } } +// CreateDatacenterConnectorOperation returns a new CreateDatacenterConnectorOperation from a given name. +// The name must be that of a previously created CreateDatacenterConnectorOperation, possibly from a different process. +func (c *restClient) CreateDatacenterConnectorOperation(name string) *CreateDatacenterConnectorOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateDatacenterConnectorOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateDatacenterConnectorOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*vmmigrationpb.DatacenterConnector, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmmigrationpb.DatacenterConnector if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2359,6 +5775,7 @@ func (op *CreateDatacenterConnectorOperation) Wait(ctx context.Context, opts ... // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateDatacenterConnectorOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*vmmigrationpb.DatacenterConnector, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmmigrationpb.DatacenterConnector if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2396,7 +5813,8 @@ func (op *CreateDatacenterConnectorOperation) Name() string { // CreateGroupOperation manages a long-running operation from CreateGroup. type CreateGroupOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateGroupOperation returns a new CreateGroupOperation from a given name. @@ -2407,10 +5825,21 @@ func (c *gRPCClient) CreateGroupOperation(name string) *CreateGroupOperation { } } +// CreateGroupOperation returns a new CreateGroupOperation from a given name. +// The name must be that of a previously created CreateGroupOperation, possibly from a different process. +func (c *restClient) CreateGroupOperation(name string) *CreateGroupOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateGroupOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateGroupOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*vmmigrationpb.Group, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmmigrationpb.Group if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2428,6 +5857,7 @@ func (op *CreateGroupOperation) Wait(ctx context.Context, opts ...gax.CallOption // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateGroupOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*vmmigrationpb.Group, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmmigrationpb.Group if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2465,7 +5895,8 @@ func (op *CreateGroupOperation) Name() string { // CreateMigratingVmOperation manages a long-running operation from CreateMigratingVm. type CreateMigratingVmOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateMigratingVmOperation returns a new CreateMigratingVmOperation from a given name. @@ -2476,10 +5907,21 @@ func (c *gRPCClient) CreateMigratingVmOperation(name string) *CreateMigratingVmO } } +// CreateMigratingVmOperation returns a new CreateMigratingVmOperation from a given name. +// The name must be that of a previously created CreateMigratingVmOperation, possibly from a different process. +func (c *restClient) CreateMigratingVmOperation(name string) *CreateMigratingVmOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateMigratingVmOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateMigratingVmOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*vmmigrationpb.MigratingVm, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmmigrationpb.MigratingVm if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2497,6 +5939,7 @@ func (op *CreateMigratingVmOperation) Wait(ctx context.Context, opts ...gax.Call // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateMigratingVmOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*vmmigrationpb.MigratingVm, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmmigrationpb.MigratingVm if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2534,7 +5977,8 @@ func (op *CreateMigratingVmOperation) Name() string { // CreateSourceOperation manages a long-running operation from CreateSource. type CreateSourceOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateSourceOperation returns a new CreateSourceOperation from a given name. @@ -2545,10 +5989,21 @@ func (c *gRPCClient) CreateSourceOperation(name string) *CreateSourceOperation { } } +// CreateSourceOperation returns a new CreateSourceOperation from a given name. +// The name must be that of a previously created CreateSourceOperation, possibly from a different process. +func (c *restClient) CreateSourceOperation(name string) *CreateSourceOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateSourceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateSourceOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*vmmigrationpb.Source, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmmigrationpb.Source if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2566,6 +6021,7 @@ func (op *CreateSourceOperation) Wait(ctx context.Context, opts ...gax.CallOptio // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateSourceOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*vmmigrationpb.Source, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmmigrationpb.Source if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2603,7 +6059,8 @@ func (op *CreateSourceOperation) Name() string { // CreateTargetProjectOperation manages a long-running operation from CreateTargetProject. type CreateTargetProjectOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateTargetProjectOperation returns a new CreateTargetProjectOperation from a given name. @@ -2614,10 +6071,21 @@ func (c *gRPCClient) CreateTargetProjectOperation(name string) *CreateTargetProj } } +// CreateTargetProjectOperation returns a new CreateTargetProjectOperation from a given name. +// The name must be that of a previously created CreateTargetProjectOperation, possibly from a different process. +func (c *restClient) CreateTargetProjectOperation(name string) *CreateTargetProjectOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateTargetProjectOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateTargetProjectOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*vmmigrationpb.TargetProject, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmmigrationpb.TargetProject if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2635,6 +6103,7 @@ func (op *CreateTargetProjectOperation) Wait(ctx context.Context, opts ...gax.Ca // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateTargetProjectOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*vmmigrationpb.TargetProject, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmmigrationpb.TargetProject if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2672,7 +6141,8 @@ func (op *CreateTargetProjectOperation) Name() string { // CreateUtilizationReportOperation manages a long-running operation from CreateUtilizationReport. type CreateUtilizationReportOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateUtilizationReportOperation returns a new CreateUtilizationReportOperation from a given name. @@ -2683,10 +6153,21 @@ func (c *gRPCClient) CreateUtilizationReportOperation(name string) *CreateUtiliz } } +// CreateUtilizationReportOperation returns a new CreateUtilizationReportOperation from a given name. +// The name must be that of a previously created CreateUtilizationReportOperation, possibly from a different process. +func (c *restClient) CreateUtilizationReportOperation(name string) *CreateUtilizationReportOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateUtilizationReportOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateUtilizationReportOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*vmmigrationpb.UtilizationReport, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmmigrationpb.UtilizationReport if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2704,6 +6185,7 @@ func (op *CreateUtilizationReportOperation) Wait(ctx context.Context, opts ...ga // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateUtilizationReportOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*vmmigrationpb.UtilizationReport, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmmigrationpb.UtilizationReport if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2741,7 +6223,8 @@ func (op *CreateUtilizationReportOperation) Name() string { // DeleteDatacenterConnectorOperation manages a long-running operation from DeleteDatacenterConnector. type DeleteDatacenterConnectorOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteDatacenterConnectorOperation returns a new DeleteDatacenterConnectorOperation from a given name. @@ -2752,10 +6235,21 @@ func (c *gRPCClient) DeleteDatacenterConnectorOperation(name string) *DeleteData } } +// DeleteDatacenterConnectorOperation returns a new DeleteDatacenterConnectorOperation from a given name. +// The name must be that of a previously created DeleteDatacenterConnectorOperation, possibly from a different process. +func (c *restClient) DeleteDatacenterConnectorOperation(name string) *DeleteDatacenterConnectorOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteDatacenterConnectorOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteDatacenterConnectorOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -2769,6 +6263,7 @@ func (op *DeleteDatacenterConnectorOperation) Wait(ctx context.Context, opts ... // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteDatacenterConnectorOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -2799,7 +6294,8 @@ func (op *DeleteDatacenterConnectorOperation) Name() string { // DeleteGroupOperation manages a long-running operation from DeleteGroup. type DeleteGroupOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteGroupOperation returns a new DeleteGroupOperation from a given name. @@ -2810,10 +6306,21 @@ func (c *gRPCClient) DeleteGroupOperation(name string) *DeleteGroupOperation { } } +// DeleteGroupOperation returns a new DeleteGroupOperation from a given name. +// The name must be that of a previously created DeleteGroupOperation, possibly from a different process. +func (c *restClient) DeleteGroupOperation(name string) *DeleteGroupOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteGroupOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteGroupOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -2827,6 +6334,7 @@ func (op *DeleteGroupOperation) Wait(ctx context.Context, opts ...gax.CallOption // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteGroupOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -2857,7 +6365,8 @@ func (op *DeleteGroupOperation) Name() string { // DeleteMigratingVmOperation manages a long-running operation from DeleteMigratingVm. type DeleteMigratingVmOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteMigratingVmOperation returns a new DeleteMigratingVmOperation from a given name. @@ -2868,10 +6377,21 @@ func (c *gRPCClient) DeleteMigratingVmOperation(name string) *DeleteMigratingVmO } } +// DeleteMigratingVmOperation returns a new DeleteMigratingVmOperation from a given name. +// The name must be that of a previously created DeleteMigratingVmOperation, possibly from a different process. +func (c *restClient) DeleteMigratingVmOperation(name string) *DeleteMigratingVmOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteMigratingVmOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteMigratingVmOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -2885,6 +6405,7 @@ func (op *DeleteMigratingVmOperation) Wait(ctx context.Context, opts ...gax.Call // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteMigratingVmOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -2915,7 +6436,8 @@ func (op *DeleteMigratingVmOperation) Name() string { // DeleteSourceOperation manages a long-running operation from DeleteSource. type DeleteSourceOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteSourceOperation returns a new DeleteSourceOperation from a given name. @@ -2926,10 +6448,21 @@ func (c *gRPCClient) DeleteSourceOperation(name string) *DeleteSourceOperation { } } +// DeleteSourceOperation returns a new DeleteSourceOperation from a given name. +// The name must be that of a previously created DeleteSourceOperation, possibly from a different process. +func (c *restClient) DeleteSourceOperation(name string) *DeleteSourceOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteSourceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteSourceOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -2943,6 +6476,7 @@ func (op *DeleteSourceOperation) Wait(ctx context.Context, opts ...gax.CallOptio // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteSourceOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -2973,7 +6507,8 @@ func (op *DeleteSourceOperation) Name() string { // DeleteTargetProjectOperation manages a long-running operation from DeleteTargetProject. type DeleteTargetProjectOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteTargetProjectOperation returns a new DeleteTargetProjectOperation from a given name. @@ -2984,10 +6519,21 @@ func (c *gRPCClient) DeleteTargetProjectOperation(name string) *DeleteTargetProj } } +// DeleteTargetProjectOperation returns a new DeleteTargetProjectOperation from a given name. +// The name must be that of a previously created DeleteTargetProjectOperation, possibly from a different process. +func (c *restClient) DeleteTargetProjectOperation(name string) *DeleteTargetProjectOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteTargetProjectOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteTargetProjectOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -3001,6 +6547,7 @@ func (op *DeleteTargetProjectOperation) Wait(ctx context.Context, opts ...gax.Ca // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteTargetProjectOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -3031,7 +6578,8 @@ func (op *DeleteTargetProjectOperation) Name() string { // DeleteUtilizationReportOperation manages a long-running operation from DeleteUtilizationReport. type DeleteUtilizationReportOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteUtilizationReportOperation returns a new DeleteUtilizationReportOperation from a given name. @@ -3042,10 +6590,21 @@ func (c *gRPCClient) DeleteUtilizationReportOperation(name string) *DeleteUtiliz } } +// DeleteUtilizationReportOperation returns a new DeleteUtilizationReportOperation from a given name. +// The name must be that of a previously created DeleteUtilizationReportOperation, possibly from a different process. +func (c *restClient) DeleteUtilizationReportOperation(name string) *DeleteUtilizationReportOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteUtilizationReportOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteUtilizationReportOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -3059,6 +6618,7 @@ func (op *DeleteUtilizationReportOperation) Wait(ctx context.Context, opts ...ga // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteUtilizationReportOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -3089,7 +6649,8 @@ func (op *DeleteUtilizationReportOperation) Name() string { // FinalizeMigrationOperation manages a long-running operation from FinalizeMigration. type FinalizeMigrationOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // FinalizeMigrationOperation returns a new FinalizeMigrationOperation from a given name. @@ -3100,10 +6661,21 @@ func (c *gRPCClient) FinalizeMigrationOperation(name string) *FinalizeMigrationO } } +// FinalizeMigrationOperation returns a new FinalizeMigrationOperation from a given name. +// The name must be that of a previously created FinalizeMigrationOperation, possibly from a different process. +func (c *restClient) FinalizeMigrationOperation(name string) *FinalizeMigrationOperation { + override := fmt.Sprintf("/v1/%s", name) + return &FinalizeMigrationOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *FinalizeMigrationOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*vmmigrationpb.FinalizeMigrationResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmmigrationpb.FinalizeMigrationResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -3121,6 +6693,7 @@ func (op *FinalizeMigrationOperation) Wait(ctx context.Context, opts ...gax.Call // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *FinalizeMigrationOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*vmmigrationpb.FinalizeMigrationResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmmigrationpb.FinalizeMigrationResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -3158,7 +6731,8 @@ func (op *FinalizeMigrationOperation) Name() string { // PauseMigrationOperation manages a long-running operation from PauseMigration. type PauseMigrationOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // PauseMigrationOperation returns a new PauseMigrationOperation from a given name. @@ -3169,10 +6743,21 @@ func (c *gRPCClient) PauseMigrationOperation(name string) *PauseMigrationOperati } } +// PauseMigrationOperation returns a new PauseMigrationOperation from a given name. +// The name must be that of a previously created PauseMigrationOperation, possibly from a different process. +func (c *restClient) PauseMigrationOperation(name string) *PauseMigrationOperation { + override := fmt.Sprintf("/v1/%s", name) + return &PauseMigrationOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *PauseMigrationOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*vmmigrationpb.PauseMigrationResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmmigrationpb.PauseMigrationResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -3190,6 +6775,7 @@ func (op *PauseMigrationOperation) Wait(ctx context.Context, opts ...gax.CallOpt // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *PauseMigrationOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*vmmigrationpb.PauseMigrationResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmmigrationpb.PauseMigrationResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -3227,7 +6813,8 @@ func (op *PauseMigrationOperation) Name() string { // RemoveGroupMigrationOperation manages a long-running operation from RemoveGroupMigration. type RemoveGroupMigrationOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // RemoveGroupMigrationOperation returns a new RemoveGroupMigrationOperation from a given name. @@ -3238,10 +6825,21 @@ func (c *gRPCClient) RemoveGroupMigrationOperation(name string) *RemoveGroupMigr } } +// RemoveGroupMigrationOperation returns a new RemoveGroupMigrationOperation from a given name. +// The name must be that of a previously created RemoveGroupMigrationOperation, possibly from a different process. +func (c *restClient) RemoveGroupMigrationOperation(name string) *RemoveGroupMigrationOperation { + override := fmt.Sprintf("/v1/%s", name) + return &RemoveGroupMigrationOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *RemoveGroupMigrationOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*vmmigrationpb.RemoveGroupMigrationResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmmigrationpb.RemoveGroupMigrationResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -3259,6 +6857,7 @@ func (op *RemoveGroupMigrationOperation) Wait(ctx context.Context, opts ...gax.C // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *RemoveGroupMigrationOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*vmmigrationpb.RemoveGroupMigrationResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmmigrationpb.RemoveGroupMigrationResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -3296,7 +6895,8 @@ func (op *RemoveGroupMigrationOperation) Name() string { // ResumeMigrationOperation manages a long-running operation from ResumeMigration. type ResumeMigrationOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // ResumeMigrationOperation returns a new ResumeMigrationOperation from a given name. @@ -3307,10 +6907,21 @@ func (c *gRPCClient) ResumeMigrationOperation(name string) *ResumeMigrationOpera } } +// ResumeMigrationOperation returns a new ResumeMigrationOperation from a given name. +// The name must be that of a previously created ResumeMigrationOperation, possibly from a different process. +func (c *restClient) ResumeMigrationOperation(name string) *ResumeMigrationOperation { + override := fmt.Sprintf("/v1/%s", name) + return &ResumeMigrationOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *ResumeMigrationOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*vmmigrationpb.ResumeMigrationResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmmigrationpb.ResumeMigrationResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -3328,6 +6939,7 @@ func (op *ResumeMigrationOperation) Wait(ctx context.Context, opts ...gax.CallOp // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *ResumeMigrationOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*vmmigrationpb.ResumeMigrationResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmmigrationpb.ResumeMigrationResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -3365,7 +6977,8 @@ func (op *ResumeMigrationOperation) Name() string { // StartMigrationOperation manages a long-running operation from StartMigration. type StartMigrationOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // StartMigrationOperation returns a new StartMigrationOperation from a given name. @@ -3376,10 +6989,21 @@ func (c *gRPCClient) StartMigrationOperation(name string) *StartMigrationOperati } } +// StartMigrationOperation returns a new StartMigrationOperation from a given name. +// The name must be that of a previously created StartMigrationOperation, possibly from a different process. +func (c *restClient) StartMigrationOperation(name string) *StartMigrationOperation { + override := fmt.Sprintf("/v1/%s", name) + return &StartMigrationOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *StartMigrationOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*vmmigrationpb.StartMigrationResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmmigrationpb.StartMigrationResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -3397,6 +7021,7 @@ func (op *StartMigrationOperation) Wait(ctx context.Context, opts ...gax.CallOpt // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *StartMigrationOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*vmmigrationpb.StartMigrationResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmmigrationpb.StartMigrationResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -3434,7 +7059,8 @@ func (op *StartMigrationOperation) Name() string { // UpdateGroupOperation manages a long-running operation from UpdateGroup. type UpdateGroupOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateGroupOperation returns a new UpdateGroupOperation from a given name. @@ -3445,10 +7071,21 @@ func (c *gRPCClient) UpdateGroupOperation(name string) *UpdateGroupOperation { } } +// UpdateGroupOperation returns a new UpdateGroupOperation from a given name. +// The name must be that of a previously created UpdateGroupOperation, possibly from a different process. +func (c *restClient) UpdateGroupOperation(name string) *UpdateGroupOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateGroupOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateGroupOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*vmmigrationpb.Group, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmmigrationpb.Group if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -3466,6 +7103,7 @@ func (op *UpdateGroupOperation) Wait(ctx context.Context, opts ...gax.CallOption // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateGroupOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*vmmigrationpb.Group, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmmigrationpb.Group if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -3503,7 +7141,8 @@ func (op *UpdateGroupOperation) Name() string { // UpdateMigratingVmOperation manages a long-running operation from UpdateMigratingVm. type UpdateMigratingVmOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateMigratingVmOperation returns a new UpdateMigratingVmOperation from a given name. @@ -3514,10 +7153,21 @@ func (c *gRPCClient) UpdateMigratingVmOperation(name string) *UpdateMigratingVmO } } +// UpdateMigratingVmOperation returns a new UpdateMigratingVmOperation from a given name. +// The name must be that of a previously created UpdateMigratingVmOperation, possibly from a different process. +func (c *restClient) UpdateMigratingVmOperation(name string) *UpdateMigratingVmOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateMigratingVmOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateMigratingVmOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*vmmigrationpb.MigratingVm, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmmigrationpb.MigratingVm if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -3535,6 +7185,7 @@ func (op *UpdateMigratingVmOperation) Wait(ctx context.Context, opts ...gax.Call // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateMigratingVmOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*vmmigrationpb.MigratingVm, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmmigrationpb.MigratingVm if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -3572,7 +7223,8 @@ func (op *UpdateMigratingVmOperation) Name() string { // UpdateSourceOperation manages a long-running operation from UpdateSource. type UpdateSourceOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateSourceOperation returns a new UpdateSourceOperation from a given name. @@ -3583,10 +7235,21 @@ func (c *gRPCClient) UpdateSourceOperation(name string) *UpdateSourceOperation { } } +// UpdateSourceOperation returns a new UpdateSourceOperation from a given name. +// The name must be that of a previously created UpdateSourceOperation, possibly from a different process. +func (c *restClient) UpdateSourceOperation(name string) *UpdateSourceOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateSourceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateSourceOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*vmmigrationpb.Source, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmmigrationpb.Source if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -3604,6 +7267,7 @@ func (op *UpdateSourceOperation) Wait(ctx context.Context, opts ...gax.CallOptio // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateSourceOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*vmmigrationpb.Source, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmmigrationpb.Source if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -3641,7 +7305,8 @@ func (op *UpdateSourceOperation) Name() string { // UpdateTargetProjectOperation manages a long-running operation from UpdateTargetProject. type UpdateTargetProjectOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateTargetProjectOperation returns a new UpdateTargetProjectOperation from a given name. @@ -3652,10 +7317,21 @@ func (c *gRPCClient) UpdateTargetProjectOperation(name string) *UpdateTargetProj } } +// UpdateTargetProjectOperation returns a new UpdateTargetProjectOperation from a given name. +// The name must be that of a previously created UpdateTargetProjectOperation, possibly from a different process. +func (c *restClient) UpdateTargetProjectOperation(name string) *UpdateTargetProjectOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateTargetProjectOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateTargetProjectOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*vmmigrationpb.TargetProject, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmmigrationpb.TargetProject if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -3673,6 +7349,7 @@ func (op *UpdateTargetProjectOperation) Wait(ctx context.Context, opts ...gax.Ca // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateTargetProjectOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*vmmigrationpb.TargetProject, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmmigrationpb.TargetProject if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -3710,7 +7387,8 @@ func (op *UpdateTargetProjectOperation) Name() string { // UpgradeApplianceOperation manages a long-running operation from UpgradeAppliance. type UpgradeApplianceOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpgradeApplianceOperation returns a new UpgradeApplianceOperation from a given name. @@ -3721,10 +7399,21 @@ func (c *gRPCClient) UpgradeApplianceOperation(name string) *UpgradeApplianceOpe } } +// UpgradeApplianceOperation returns a new UpgradeApplianceOperation from a given name. +// The name must be that of a previously created UpgradeApplianceOperation, possibly from a different process. +func (c *restClient) UpgradeApplianceOperation(name string) *UpgradeApplianceOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpgradeApplianceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpgradeApplianceOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*vmmigrationpb.UpgradeApplianceResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmmigrationpb.UpgradeApplianceResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -3742,6 +7431,7 @@ func (op *UpgradeApplianceOperation) Wait(ctx context.Context, opts ...gax.CallO // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpgradeApplianceOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*vmmigrationpb.UpgradeApplianceResponse, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmmigrationpb.UpgradeApplianceResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/vmmigration/apiv1/vm_migration_client_example_test.go b/vmmigration/apiv1/vm_migration_client_example_test.go index ba0b31006d7c..86bdb8c53f25 100644 --- a/vmmigration/apiv1/vm_migration_client_example_test.go +++ b/vmmigration/apiv1/vm_migration_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := vmmigration.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_ListSources() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/vmmigration/apiv1/vmmigrationpb/vmmigration.pb.go b/vmmigration/apiv1/vmmigrationpb/vmmigration.pb.go index dff72d674174..934c44a206f1 100644 --- a/vmmigration/apiv1/vmmigrationpb/vmmigration.pb.go +++ b/vmmigration/apiv1/vmmigrationpb/vmmigration.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/vmmigration/v1/vmmigration.proto package vmmigrationpb @@ -1331,7 +1331,6 @@ type MigratingVm struct { // result of the migration. // // Types that are assignable to TargetVmDefaults: - // // *MigratingVm_ComputeEngineTargetDefaults TargetVmDefaults isMigratingVm_TargetVmDefaults `protobuf_oneof:"target_vm_defaults"` // Output only. The identifier of the MigratingVm. @@ -1571,7 +1570,6 @@ type CloneJob struct { // Details of the VM to create as the target of this clone job. // // Types that are assignable to TargetVmDetails: - // // *CloneJob_ComputeEngineTargetDetails TargetVmDetails isCloneJob_TargetVmDetails `protobuf_oneof:"target_vm_details"` // Output only. The time the clone job was created (as an API call, not when @@ -1700,7 +1698,6 @@ type CutoverJob struct { // Details of the VM to create as the target of this cutover job. // // Types that are assignable to TargetVmDetails: - // // *CutoverJob_ComputeEngineTargetDetails TargetVmDetails isCutoverJob_TargetVmDetails `protobuf_oneof:"target_vm_details"` // Output only. The time the cutover job was created (as an API call, not when @@ -2230,7 +2227,6 @@ type Source struct { unknownFields protoimpl.UnknownFields // Types that are assignable to SourceDetails: - // // *Source_Vmware SourceDetails isSource_SourceDetails `protobuf_oneof:"source_details"` // Output only. The Source name. @@ -3536,7 +3532,6 @@ type FetchInventoryResponse struct { unknownFields protoimpl.UnknownFields // Types that are assignable to SourceVms: - // // *FetchInventoryResponse_VmwareVms SourceVms isFetchInventoryResponse_SourceVms `protobuf_oneof:"SourceVms"` // Output only. The timestamp when the source was last queried (if the result @@ -3754,7 +3749,6 @@ type VmUtilizationInfo struct { unknownFields protoimpl.UnknownFields // Types that are assignable to VmDetails: - // // *VmUtilizationInfo_VmwareVmDetails VmDetails isVmUtilizationInfo_VmDetails `protobuf_oneof:"VmDetails"` // The VM's ID in the source. diff --git a/vmwareengine/apiv1/doc.go b/vmwareengine/apiv1/doc.go index 0d9e6035ea7f..724bf94a2768 100644 --- a/vmwareengine/apiv1/doc.go +++ b/vmwareengine/apiv1/doc.go @@ -89,6 +89,8 @@ package vmwareengine // import "cloud.google.com/go/vmwareengine/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -177,3 +179,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/vmwareengine/apiv1/gapic_metadata.json b/vmwareengine/apiv1/gapic_metadata.json index 2b24ca3ca00e..282b44c32e7e 100644 --- a/vmwareengine/apiv1/gapic_metadata.json +++ b/vmwareengine/apiv1/gapic_metadata.json @@ -206,6 +206,206 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "CreateCluster": { + "methods": [ + "CreateCluster" + ] + }, + "CreateHcxActivationKey": { + "methods": [ + "CreateHcxActivationKey" + ] + }, + "CreateNetworkPolicy": { + "methods": [ + "CreateNetworkPolicy" + ] + }, + "CreatePrivateCloud": { + "methods": [ + "CreatePrivateCloud" + ] + }, + "CreateVmwareEngineNetwork": { + "methods": [ + "CreateVmwareEngineNetwork" + ] + }, + "DeleteCluster": { + "methods": [ + "DeleteCluster" + ] + }, + "DeleteNetworkPolicy": { + "methods": [ + "DeleteNetworkPolicy" + ] + }, + "DeleteOperation": { + "methods": [ + "DeleteOperation" + ] + }, + "DeletePrivateCloud": { + "methods": [ + "DeletePrivateCloud" + ] + }, + "DeleteVmwareEngineNetwork": { + "methods": [ + "DeleteVmwareEngineNetwork" + ] + }, + "GetCluster": { + "methods": [ + "GetCluster" + ] + }, + "GetHcxActivationKey": { + "methods": [ + "GetHcxActivationKey" + ] + }, + "GetIamPolicy": { + "methods": [ + "GetIamPolicy" + ] + }, + "GetLocation": { + "methods": [ + "GetLocation" + ] + }, + "GetNetworkPolicy": { + "methods": [ + "GetNetworkPolicy" + ] + }, + "GetNodeType": { + "methods": [ + "GetNodeType" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "GetPrivateCloud": { + "methods": [ + "GetPrivateCloud" + ] + }, + "GetVmwareEngineNetwork": { + "methods": [ + "GetVmwareEngineNetwork" + ] + }, + "ListClusters": { + "methods": [ + "ListClusters" + ] + }, + "ListHcxActivationKeys": { + "methods": [ + "ListHcxActivationKeys" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListNetworkPolicies": { + "methods": [ + "ListNetworkPolicies" + ] + }, + "ListNodeTypes": { + "methods": [ + "ListNodeTypes" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + }, + "ListPrivateClouds": { + "methods": [ + "ListPrivateClouds" + ] + }, + "ListSubnets": { + "methods": [ + "ListSubnets" + ] + }, + "ListVmwareEngineNetworks": { + "methods": [ + "ListVmwareEngineNetworks" + ] + }, + "ResetNsxCredentials": { + "methods": [ + "ResetNsxCredentials" + ] + }, + "ResetVcenterCredentials": { + "methods": [ + "ResetVcenterCredentials" + ] + }, + "SetIamPolicy": { + "methods": [ + "SetIamPolicy" + ] + }, + "ShowNsxCredentials": { + "methods": [ + "ShowNsxCredentials" + ] + }, + "ShowVcenterCredentials": { + "methods": [ + "ShowVcenterCredentials" + ] + }, + "TestIamPermissions": { + "methods": [ + "TestIamPermissions" + ] + }, + "UndeletePrivateCloud": { + "methods": [ + "UndeletePrivateCloud" + ] + }, + "UpdateCluster": { + "methods": [ + "UpdateCluster" + ] + }, + "UpdateNetworkPolicy": { + "methods": [ + "UpdateNetworkPolicy" + ] + }, + "UpdatePrivateCloud": { + "methods": [ + "UpdatePrivateCloud" + ] + }, + "UpdateVmwareEngineNetwork": { + "methods": [ + "UpdateVmwareEngineNetwork" + ] + } + } } } } diff --git a/vmwareengine/apiv1/vmware_engine_client.go b/vmwareengine/apiv1/vmware_engine_client.go index 4f41ca875bc5..104ac4de359b 100644 --- a/vmwareengine/apiv1/vmware_engine_client.go +++ b/vmwareengine/apiv1/vmware_engine_client.go @@ -17,9 +17,12 @@ package vmwareengine import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,16 +30,19 @@ import ( lroauto "cloud.google.com/go/longrunning/autogen" vmwareenginepb "cloud.google.com/go/vmwareengine/apiv1/vmwareenginepb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" iampb "google.golang.org/genproto/googleapis/iam/v1" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -291,6 +297,185 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + ListPrivateClouds: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetPrivateCloud: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreatePrivateCloud: []gax.CallOption{}, + UpdatePrivateCloud: []gax.CallOption{}, + DeletePrivateCloud: []gax.CallOption{}, + UndeletePrivateCloud: []gax.CallOption{}, + ListClusters: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetCluster: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateCluster: []gax.CallOption{}, + UpdateCluster: []gax.CallOption{}, + DeleteCluster: []gax.CallOption{}, + ListSubnets: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListNodeTypes: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetNodeType: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ShowNsxCredentials: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ShowVcenterCredentials: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ResetNsxCredentials: []gax.CallOption{}, + ResetVcenterCredentials: []gax.CallOption{}, + CreateHcxActivationKey: []gax.CallOption{}, + ListHcxActivationKeys: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetHcxActivationKey: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetNetworkPolicy: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListNetworkPolicies: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + CreateNetworkPolicy: []gax.CallOption{}, + UpdateNetworkPolicy: []gax.CallOption{}, + DeleteNetworkPolicy: []gax.CallOption{}, + CreateVmwareEngineNetwork: []gax.CallOption{}, + UpdateVmwareEngineNetwork: []gax.CallOption{}, + DeleteVmwareEngineNetwork: []gax.CallOption{}, + GetVmwareEngineNetwork: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + ListVmwareEngineNetworks: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 1000 * time.Millisecond, + Max: 10000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusServiceUnavailable) + }), + }, + GetLocation: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + GetIamPolicy: []gax.CallOption{}, + SetIamPolicy: []gax.CallOption{}, + TestIamPermissions: []gax.CallOption{}, + DeleteOperation: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalClient is an interface that defines the methods available from VMware Engine API. type internalClient interface { Close() error @@ -867,6 +1052,89 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new vmware engine rest client. +// +// VMwareEngine manages VMware’s private clusters in the Cloud. +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://vmwareengine.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://vmwareengine.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://vmwareengine.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) ListPrivateClouds(ctx context.Context, req *vmwareenginepb.ListPrivateCloudsRequest, opts ...gax.CallOption) *PrivateCloudIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -1930,47 +2198,2934 @@ func (c *gRPCClient) ListOperations(ctx context.Context, req *longrunningpb.List return it } -// CreateClusterOperation manages a long-running operation from CreateCluster. -type CreateClusterOperation struct { - lro *longrunning.Operation -} +// ListPrivateClouds lists PrivateCloud resources in a given project and location. +func (c *restClient) ListPrivateClouds(ctx context.Context, req *vmwareenginepb.ListPrivateCloudsRequest, opts ...gax.CallOption) *PrivateCloudIterator { + it := &PrivateCloudIterator{} + req = proto.Clone(req).(*vmwareenginepb.ListPrivateCloudsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*vmwareenginepb.PrivateCloud, string, error) { + resp := &vmwareenginepb.ListPrivateCloudsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/privateClouds", req.GetParent()) -// CreateClusterOperation returns a new CreateClusterOperation from a given name. -// The name must be that of a previously created CreateClusterOperation, possibly from a different process. -func (c *gRPCClient) CreateClusterOperation(name string) *CreateClusterOperation { - return &CreateClusterOperation{ - lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetPrivateClouds(), resp.GetNextPageToken(), nil } -} -// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. -// -// See documentation of Poll for error-handling information. -func (op *CreateClusterOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*vmwareenginepb.Cluster, error) { - var resp vmwareenginepb.Cluster - if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { - return nil, err + 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 } - return &resp, nil + + it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it } -// Poll fetches the latest state of the long-running operation. -// -// Poll also fetches the latest metadata, which can be retrieved by Metadata. -// -// 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, and the response of the operation is returned. -// If Poll succeeds and the operation has not completed, the returned response and error are both nil. -func (op *CreateClusterOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*vmwareenginepb.Cluster, error) { - var resp vmwareenginepb.Cluster - if err := op.lro.Poll(ctx, &resp, opts...); err != nil { +// GetPrivateCloud retrieves a PrivateCloud resource by its resource name. +func (c *restClient) GetPrivateCloud(ctx context.Context, req *vmwareenginepb.GetPrivateCloudRequest, opts ...gax.CallOption) (*vmwareenginepb.PrivateCloud, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { return nil, err } - if !op.Done() { - return nil, nil - } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetPrivateCloud[0:len((*c.CallOptions).GetPrivateCloud):len((*c.CallOptions).GetPrivateCloud)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &vmwareenginepb.PrivateCloud{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreatePrivateCloud creates a new PrivateCloud resource in a given project and location. +// Private clouds can only be created in zones, regional private clouds are +// not supported. +// +// Creating a private cloud also creates a management +// cluster (at https://cloud.google.com/vmware-engine/docs/concepts-vmware-components) +// for that private cloud. +func (c *restClient) CreatePrivateCloud(ctx context.Context, req *vmwareenginepb.CreatePrivateCloudRequest, opts ...gax.CallOption) (*CreatePrivateCloudOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetPrivateCloud() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/privateClouds", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("privateCloudId", fmt.Sprintf("%v", req.GetPrivateCloudId())) + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreatePrivateCloudOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdatePrivateCloud modifies a PrivateCloud resource. Only the following fields can be +// updated: description. +// Only fields specified in updateMask are applied. +// +// During operation processing, the resource is temporarily in the ACTIVE +// state before the operation fully completes. For that period of time, you +// can’t update the resource. Use the operation status to determine when the +// processing fully completes. +func (c *restClient) UpdatePrivateCloud(ctx context.Context, req *vmwareenginepb.UpdatePrivateCloudRequest, opts ...gax.CallOption) (*UpdatePrivateCloudOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetPrivateCloud() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetPrivateCloud().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "private_cloud.name", url.QueryEscape(req.GetPrivateCloud().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdatePrivateCloudOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeletePrivateCloud schedules a PrivateCloud resource for deletion. +// +// A PrivateCloud resource scheduled for deletion has PrivateCloud.state +// set to DELETED and expireTime set to the time when deletion is final +// and can no longer be reversed. The delete operation is marked as done +// as soon as the PrivateCloud is successfully scheduled for deletion +// (this also applies when delayHours is set to zero), and the operation is +// not kept in pending state until PrivateCloud is purged. +// PrivateCloud can be restored using UndeletePrivateCloud method before +// the expireTime elapses. When expireTime is reached, deletion is final +// and all private cloud resources are irreversibly removed and billing stops. +// During the final removal process, PrivateCloud.state is set to PURGING. +// PrivateCloud can be polled using standard GET method for the whole +// period of deletion and purging. It will not be returned only +// when it is completely purged. +func (c *restClient) DeletePrivateCloud(ctx context.Context, req *vmwareenginepb.DeletePrivateCloudRequest, opts ...gax.CallOption) (*DeletePrivateCloudOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req != nil && req.DelayHours != nil { + params.Add("delayHours", fmt.Sprintf("%v", req.GetDelayHours())) + } + if req.GetForce() { + params.Add("force", fmt.Sprintf("%v", req.GetForce())) + } + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeletePrivateCloudOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UndeletePrivateCloud restores a private cloud that was previously scheduled for deletion by +// DeletePrivateCloud. A PrivateCloud resource scheduled for deletion has +// PrivateCloud.state set to DELETED and PrivateCloud.expireTime set to +// the time when deletion can no longer be reversed. +func (c *restClient) UndeletePrivateCloud(ctx context.Context, req *vmwareenginepb.UndeletePrivateCloudRequest, opts ...gax.CallOption) (*UndeletePrivateCloudOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:undelete", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UndeletePrivateCloudOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListClusters lists Cluster resources in a given private cloud. +func (c *restClient) ListClusters(ctx context.Context, req *vmwareenginepb.ListClustersRequest, opts ...gax.CallOption) *ClusterIterator { + it := &ClusterIterator{} + req = proto.Clone(req).(*vmwareenginepb.ListClustersRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*vmwareenginepb.Cluster, string, error) { + resp := &vmwareenginepb.ListClustersResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/clusters", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetClusters(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetCluster retrieves a Cluster resource by its resource name. +func (c *restClient) GetCluster(ctx context.Context, req *vmwareenginepb.GetClusterRequest, opts ...gax.CallOption) (*vmwareenginepb.Cluster, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetCluster[0:len((*c.CallOptions).GetCluster):len((*c.CallOptions).GetCluster)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &vmwareenginepb.Cluster{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateCluster creates a new cluster in a given private cloud. +// Creating a new cluster provides additional nodes for +// use in the parent private cloud and requires sufficient node +// quota (at https://cloud.google.com/vmware-engine/quotas). +func (c *restClient) CreateCluster(ctx context.Context, req *vmwareenginepb.CreateClusterRequest, opts ...gax.CallOption) (*CreateClusterOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetCluster() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/clusters", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("clusterId", fmt.Sprintf("%v", req.GetClusterId())) + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateClusterOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateCluster modifies a Cluster resource. Only the following fields can be updated: +// node_type_configs.*.node_count. Only fields specified in updateMask are +// applied. +// +// During operation processing, the resource is temporarily in the ACTIVE +// state before the operation fully completes. For that period of time, you +// can’t update the resource. Use the operation status to determine when the +// processing fully completes. +func (c *restClient) UpdateCluster(ctx context.Context, req *vmwareenginepb.UpdateClusterRequest, opts ...gax.CallOption) (*UpdateClusterOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetCluster() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetCluster().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + if req.GetValidateOnly() { + params.Add("validateOnly", fmt.Sprintf("%v", req.GetValidateOnly())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "cluster.name", url.QueryEscape(req.GetCluster().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateClusterOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteCluster deletes a Cluster resource. To avoid unintended data loss, migrate or +// gracefully shut down any workloads running on the cluster before deletion. +// You cannot delete the management cluster of a private cloud using this +// method. +func (c *restClient) DeleteCluster(ctx context.Context, req *vmwareenginepb.DeleteClusterRequest, opts ...gax.CallOption) (*DeleteClusterOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteClusterOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListSubnets lists subnets in a given private cloud. +func (c *restClient) ListSubnets(ctx context.Context, req *vmwareenginepb.ListSubnetsRequest, opts ...gax.CallOption) *SubnetIterator { + it := &SubnetIterator{} + req = proto.Clone(req).(*vmwareenginepb.ListSubnetsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*vmwareenginepb.Subnet, string, error) { + resp := &vmwareenginepb.ListSubnetsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/subnets", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetSubnets(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// ListNodeTypes lists node types +func (c *restClient) ListNodeTypes(ctx context.Context, req *vmwareenginepb.ListNodeTypesRequest, opts ...gax.CallOption) *NodeTypeIterator { + it := &NodeTypeIterator{} + req = proto.Clone(req).(*vmwareenginepb.ListNodeTypesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*vmwareenginepb.NodeType, string, error) { + resp := &vmwareenginepb.ListNodeTypesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/nodeTypes", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetNodeTypes(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetNodeType gets details of a single NodeType. +func (c *restClient) GetNodeType(ctx context.Context, req *vmwareenginepb.GetNodeTypeRequest, opts ...gax.CallOption) (*vmwareenginepb.NodeType, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetNodeType[0:len((*c.CallOptions).GetNodeType):len((*c.CallOptions).GetNodeType)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &vmwareenginepb.NodeType{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ShowNsxCredentials gets details of credentials for NSX appliance. +func (c *restClient) ShowNsxCredentials(ctx context.Context, req *vmwareenginepb.ShowNsxCredentialsRequest, opts ...gax.CallOption) (*vmwareenginepb.Credentials, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:showNsxCredentials", req.GetPrivateCloud()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "private_cloud", url.QueryEscape(req.GetPrivateCloud()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).ShowNsxCredentials[0:len((*c.CallOptions).ShowNsxCredentials):len((*c.CallOptions).ShowNsxCredentials)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &vmwareenginepb.Credentials{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ShowVcenterCredentials gets details of credentials for Vcenter appliance. +func (c *restClient) ShowVcenterCredentials(ctx context.Context, req *vmwareenginepb.ShowVcenterCredentialsRequest, opts ...gax.CallOption) (*vmwareenginepb.Credentials, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:showVcenterCredentials", req.GetPrivateCloud()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "private_cloud", url.QueryEscape(req.GetPrivateCloud()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).ShowVcenterCredentials[0:len((*c.CallOptions).ShowVcenterCredentials):len((*c.CallOptions).ShowVcenterCredentials)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &vmwareenginepb.Credentials{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ResetNsxCredentials resets credentials of the NSX appliance. +func (c *restClient) ResetNsxCredentials(ctx context.Context, req *vmwareenginepb.ResetNsxCredentialsRequest, opts ...gax.CallOption) (*ResetNsxCredentialsOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:resetNsxCredentials", req.GetPrivateCloud()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "private_cloud", url.QueryEscape(req.GetPrivateCloud()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &ResetNsxCredentialsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ResetVcenterCredentials resets credentials of the Vcenter appliance. +func (c *restClient) ResetVcenterCredentials(ctx context.Context, req *vmwareenginepb.ResetVcenterCredentialsRequest, opts ...gax.CallOption) (*ResetVcenterCredentialsOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:resetVcenterCredentials", req.GetPrivateCloud()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "private_cloud", url.QueryEscape(req.GetPrivateCloud()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &ResetVcenterCredentialsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// CreateHcxActivationKey creates a new HCX activation key in a given private cloud. +func (c *restClient) CreateHcxActivationKey(ctx context.Context, req *vmwareenginepb.CreateHcxActivationKeyRequest, opts ...gax.CallOption) (*CreateHcxActivationKeyOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetHcxActivationKey() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/hcxActivationKeys", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("hcxActivationKeyId", fmt.Sprintf("%v", req.GetHcxActivationKeyId())) + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateHcxActivationKeyOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListHcxActivationKeys lists HcxActivationKey resources in a given private cloud. +func (c *restClient) ListHcxActivationKeys(ctx context.Context, req *vmwareenginepb.ListHcxActivationKeysRequest, opts ...gax.CallOption) *HcxActivationKeyIterator { + it := &HcxActivationKeyIterator{} + req = proto.Clone(req).(*vmwareenginepb.ListHcxActivationKeysRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*vmwareenginepb.HcxActivationKey, string, error) { + resp := &vmwareenginepb.ListHcxActivationKeysResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/hcxActivationKeys", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetHcxActivationKeys(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetHcxActivationKey retrieves a HcxActivationKey resource by its resource name. +func (c *restClient) GetHcxActivationKey(ctx context.Context, req *vmwareenginepb.GetHcxActivationKeyRequest, opts ...gax.CallOption) (*vmwareenginepb.HcxActivationKey, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetHcxActivationKey[0:len((*c.CallOptions).GetHcxActivationKey):len((*c.CallOptions).GetHcxActivationKey)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &vmwareenginepb.HcxActivationKey{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetNetworkPolicy retrieves a NetworkPolicy resource by its resource name. +func (c *restClient) GetNetworkPolicy(ctx context.Context, req *vmwareenginepb.GetNetworkPolicyRequest, opts ...gax.CallOption) (*vmwareenginepb.NetworkPolicy, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetNetworkPolicy[0:len((*c.CallOptions).GetNetworkPolicy):len((*c.CallOptions).GetNetworkPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &vmwareenginepb.NetworkPolicy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListNetworkPolicies lists NetworkPolicy resources in a specified project and location. +func (c *restClient) ListNetworkPolicies(ctx context.Context, req *vmwareenginepb.ListNetworkPoliciesRequest, opts ...gax.CallOption) *NetworkPolicyIterator { + it := &NetworkPolicyIterator{} + req = proto.Clone(req).(*vmwareenginepb.ListNetworkPoliciesRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*vmwareenginepb.NetworkPolicy, string, error) { + resp := &vmwareenginepb.ListNetworkPoliciesResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/networkPolicies", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetNetworkPolicies(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CreateNetworkPolicy creates a new network policy in a given VMware Engine network of a +// project and location (region). A new network policy cannot be created if +// another network policy already exists in the same scope. +func (c *restClient) CreateNetworkPolicy(ctx context.Context, req *vmwareenginepb.CreateNetworkPolicyRequest, opts ...gax.CallOption) (*CreateNetworkPolicyOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetNetworkPolicy() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/networkPolicies", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("networkPolicyId", fmt.Sprintf("%v", req.GetNetworkPolicyId())) + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateNetworkPolicyOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateNetworkPolicy modifies a NetworkPolicy resource. Only the following fields can be +// updated: internet_access, external_ip, edge_services_cidr. +// Only fields specified in updateMask are applied. When updating a network +// policy, the external IP network service can only be disabled if there are +// no external IP addresses present in the scope of the policy. Also, a +// NetworkService cannot be updated when NetworkService.state is set +// to RECONCILING. +// +// During operation processing, the resource is temporarily in the ACTIVE +// state before the operation fully completes. For that period of time, you +// can’t update the resource. Use the operation status to determine when the +// processing fully completes. +func (c *restClient) UpdateNetworkPolicy(ctx context.Context, req *vmwareenginepb.UpdateNetworkPolicyRequest, opts ...gax.CallOption) (*UpdateNetworkPolicyOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetNetworkPolicy() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetNetworkPolicy().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "network_policy.name", url.QueryEscape(req.GetNetworkPolicy().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateNetworkPolicyOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteNetworkPolicy deletes a NetworkPolicy resource. A network policy cannot be deleted +// when NetworkService.state is set to RECONCILING for either its external +// IP or internet access service. +func (c *restClient) DeleteNetworkPolicy(ctx context.Context, req *vmwareenginepb.DeleteNetworkPolicyRequest, opts ...gax.CallOption) (*DeleteNetworkPolicyOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteNetworkPolicyOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// CreateVmwareEngineNetwork creates a new VMware Engine network that can be used by a private cloud. +func (c *restClient) CreateVmwareEngineNetwork(ctx context.Context, req *vmwareenginepb.CreateVmwareEngineNetworkRequest, opts ...gax.CallOption) (*CreateVmwareEngineNetworkOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetVmwareEngineNetwork() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/vmwareEngineNetworks", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + params.Add("vmwareEngineNetworkId", fmt.Sprintf("%v", req.GetVmwareEngineNetworkId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateVmwareEngineNetworkOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateVmwareEngineNetwork modifies a VMware Engine network resource. Only the following fields can be +// updated: description. Only fields specified in updateMask are +// applied. +func (c *restClient) UpdateVmwareEngineNetwork(ctx context.Context, req *vmwareenginepb.UpdateVmwareEngineNetworkRequest, opts ...gax.CallOption) (*UpdateVmwareEngineNetworkOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetVmwareEngineNetwork() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetVmwareEngineNetwork().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "vmware_engine_network.name", url.QueryEscape(req.GetVmwareEngineNetwork().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateVmwareEngineNetworkOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteVmwareEngineNetwork deletes a VmwareEngineNetwork resource. You can only delete a VMware +// Engine network after all resources that refer to it are deleted. For +// example, a private cloud, a network peering, and a network policy can all +// refer to the same VMware Engine network. +func (c *restClient) DeleteVmwareEngineNetwork(ctx context.Context, req *vmwareenginepb.DeleteVmwareEngineNetworkRequest, opts ...gax.CallOption) (*DeleteVmwareEngineNetworkOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetEtag() != "" { + params.Add("etag", fmt.Sprintf("%v", req.GetEtag())) + } + if req.GetRequestId() != "" { + params.Add("requestId", fmt.Sprintf("%v", req.GetRequestId())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteVmwareEngineNetworkOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetVmwareEngineNetwork retrieves a VmwareEngineNetwork resource by its resource name. The +// resource contains details of the VMware Engine network, such as its VMware +// Engine network type, peered networks in a service project, and state +// (for example, CREATING, ACTIVE, DELETING). +func (c *restClient) GetVmwareEngineNetwork(ctx context.Context, req *vmwareenginepb.GetVmwareEngineNetworkRequest, opts ...gax.CallOption) (*vmwareenginepb.VmwareEngineNetwork, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetVmwareEngineNetwork[0:len((*c.CallOptions).GetVmwareEngineNetwork):len((*c.CallOptions).GetVmwareEngineNetwork)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &vmwareenginepb.VmwareEngineNetwork{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListVmwareEngineNetworks lists VmwareEngineNetwork resources in a given project and location. +func (c *restClient) ListVmwareEngineNetworks(ctx context.Context, req *vmwareenginepb.ListVmwareEngineNetworksRequest, opts ...gax.CallOption) *VmwareEngineNetworkIterator { + it := &VmwareEngineNetworkIterator{} + req = proto.Clone(req).(*vmwareenginepb.ListVmwareEngineNetworksRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*vmwareenginepb.VmwareEngineNetwork, string, error) { + resp := &vmwareenginepb.ListVmwareEngineNetworksResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/vmwareEngineNetworks", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetVmwareEngineNetworks(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetLocation gets information about a location. +func (c *restClient) GetLocation(ctx context.Context, req *locationpb.GetLocationRequest, opts ...gax.CallOption) (*locationpb.Location, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetLocation[0:len((*c.CallOptions).GetLocation):len((*c.CallOptions).GetLocation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &locationpb.Location{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *restClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetIamPolicy gets the access control policy for a resource. Returns an empty policy +// if the resource exists and does not have a policy set. +func (c *restClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:getIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetOptions().GetRequestedPolicyVersion() != 0 { + params.Add("options.requestedPolicyVersion", fmt.Sprintf("%v", req.GetOptions().GetRequestedPolicyVersion())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SetIamPolicy sets the access control policy on the specified resource. Replaces +// any existing policy. +// +// Can return NOT_FOUND, INVALID_ARGUMENT, and PERMISSION_DENIED +// errors. +func (c *restClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:setIamPolicy", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.Policy{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// TestIamPermissions returns permissions that a caller has on the specified resource. If the +// resource does not exist, this will return an empty set of +// permissions, not a NOT_FOUND error. +// +// Note: This operation is designed to be used for building +// permission-aware UIs and command-line tools, not for authorization +// checking. This operation may “fail open” without warning. +func (c *restClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:testIamPermissions", req.GetResource()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &iampb.TestIamPermissionsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteOperation is a utility method from google.longrunning.Operations. +func (c *restClient) DeleteOperation(ctx context.Context, req *longrunningpb.DeleteOperationRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *restClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *restClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// CreateClusterOperation manages a long-running operation from CreateCluster. +type CreateClusterOperation struct { + lro *longrunning.Operation + pollPath string +} + +// CreateClusterOperation returns a new CreateClusterOperation from a given name. +// The name must be that of a previously created CreateClusterOperation, possibly from a different process. +func (c *gRPCClient) CreateClusterOperation(name string) *CreateClusterOperation { + return &CreateClusterOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + } +} + +// CreateClusterOperation returns a new CreateClusterOperation from a given name. +// The name must be that of a previously created CreateClusterOperation, possibly from a different process. +func (c *restClient) CreateClusterOperation(name string) *CreateClusterOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateClusterOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + +// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. +// +// See documentation of Poll for error-handling information. +func (op *CreateClusterOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*vmwareenginepb.Cluster, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp vmwareenginepb.Cluster + if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { + return nil, err + } + return &resp, nil +} + +// Poll fetches the latest state of the long-running operation. +// +// Poll also fetches the latest metadata, which can be retrieved by Metadata. +// +// 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, and the response of the operation is returned. +// If Poll succeeds and the operation has not completed, the returned response and error are both nil. +func (op *CreateClusterOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*vmwareenginepb.Cluster, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) + var resp vmwareenginepb.Cluster + if err := op.lro.Poll(ctx, &resp, opts...); err != nil { + return nil, err + } + if !op.Done() { + return nil, nil + } return &resp, nil } @@ -2001,7 +5156,8 @@ func (op *CreateClusterOperation) Name() string { // CreateHcxActivationKeyOperation manages a long-running operation from CreateHcxActivationKey. type CreateHcxActivationKeyOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateHcxActivationKeyOperation returns a new CreateHcxActivationKeyOperation from a given name. @@ -2012,10 +5168,21 @@ func (c *gRPCClient) CreateHcxActivationKeyOperation(name string) *CreateHcxActi } } +// CreateHcxActivationKeyOperation returns a new CreateHcxActivationKeyOperation from a given name. +// The name must be that of a previously created CreateHcxActivationKeyOperation, possibly from a different process. +func (c *restClient) CreateHcxActivationKeyOperation(name string) *CreateHcxActivationKeyOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateHcxActivationKeyOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateHcxActivationKeyOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*vmwareenginepb.HcxActivationKey, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmwareenginepb.HcxActivationKey if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2033,6 +5200,7 @@ func (op *CreateHcxActivationKeyOperation) Wait(ctx context.Context, opts ...gax // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateHcxActivationKeyOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*vmwareenginepb.HcxActivationKey, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmwareenginepb.HcxActivationKey if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2070,7 +5238,8 @@ func (op *CreateHcxActivationKeyOperation) Name() string { // CreateNetworkPolicyOperation manages a long-running operation from CreateNetworkPolicy. type CreateNetworkPolicyOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateNetworkPolicyOperation returns a new CreateNetworkPolicyOperation from a given name. @@ -2081,10 +5250,21 @@ func (c *gRPCClient) CreateNetworkPolicyOperation(name string) *CreateNetworkPol } } +// CreateNetworkPolicyOperation returns a new CreateNetworkPolicyOperation from a given name. +// The name must be that of a previously created CreateNetworkPolicyOperation, possibly from a different process. +func (c *restClient) CreateNetworkPolicyOperation(name string) *CreateNetworkPolicyOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateNetworkPolicyOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateNetworkPolicyOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*vmwareenginepb.NetworkPolicy, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmwareenginepb.NetworkPolicy if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2102,6 +5282,7 @@ func (op *CreateNetworkPolicyOperation) Wait(ctx context.Context, opts ...gax.Ca // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateNetworkPolicyOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*vmwareenginepb.NetworkPolicy, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmwareenginepb.NetworkPolicy if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2139,7 +5320,8 @@ func (op *CreateNetworkPolicyOperation) Name() string { // CreatePrivateCloudOperation manages a long-running operation from CreatePrivateCloud. type CreatePrivateCloudOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreatePrivateCloudOperation returns a new CreatePrivateCloudOperation from a given name. @@ -2150,10 +5332,21 @@ func (c *gRPCClient) CreatePrivateCloudOperation(name string) *CreatePrivateClou } } +// CreatePrivateCloudOperation returns a new CreatePrivateCloudOperation from a given name. +// The name must be that of a previously created CreatePrivateCloudOperation, possibly from a different process. +func (c *restClient) CreatePrivateCloudOperation(name string) *CreatePrivateCloudOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreatePrivateCloudOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreatePrivateCloudOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*vmwareenginepb.PrivateCloud, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmwareenginepb.PrivateCloud if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2171,6 +5364,7 @@ func (op *CreatePrivateCloudOperation) Wait(ctx context.Context, opts ...gax.Cal // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreatePrivateCloudOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*vmwareenginepb.PrivateCloud, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmwareenginepb.PrivateCloud if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2208,7 +5402,8 @@ func (op *CreatePrivateCloudOperation) Name() string { // CreateVmwareEngineNetworkOperation manages a long-running operation from CreateVmwareEngineNetwork. type CreateVmwareEngineNetworkOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateVmwareEngineNetworkOperation returns a new CreateVmwareEngineNetworkOperation from a given name. @@ -2219,10 +5414,21 @@ func (c *gRPCClient) CreateVmwareEngineNetworkOperation(name string) *CreateVmwa } } +// CreateVmwareEngineNetworkOperation returns a new CreateVmwareEngineNetworkOperation from a given name. +// The name must be that of a previously created CreateVmwareEngineNetworkOperation, possibly from a different process. +func (c *restClient) CreateVmwareEngineNetworkOperation(name string) *CreateVmwareEngineNetworkOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateVmwareEngineNetworkOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateVmwareEngineNetworkOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*vmwareenginepb.VmwareEngineNetwork, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmwareenginepb.VmwareEngineNetwork if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2240,6 +5446,7 @@ func (op *CreateVmwareEngineNetworkOperation) Wait(ctx context.Context, opts ... // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateVmwareEngineNetworkOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*vmwareenginepb.VmwareEngineNetwork, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmwareenginepb.VmwareEngineNetwork if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2277,7 +5484,8 @@ func (op *CreateVmwareEngineNetworkOperation) Name() string { // DeleteClusterOperation manages a long-running operation from DeleteCluster. type DeleteClusterOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteClusterOperation returns a new DeleteClusterOperation from a given name. @@ -2288,10 +5496,21 @@ func (c *gRPCClient) DeleteClusterOperation(name string) *DeleteClusterOperation } } +// DeleteClusterOperation returns a new DeleteClusterOperation from a given name. +// The name must be that of a previously created DeleteClusterOperation, possibly from a different process. +func (c *restClient) DeleteClusterOperation(name string) *DeleteClusterOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteClusterOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteClusterOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -2305,6 +5524,7 @@ func (op *DeleteClusterOperation) Wait(ctx context.Context, opts ...gax.CallOpti // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteClusterOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -2335,7 +5555,8 @@ func (op *DeleteClusterOperation) Name() string { // DeleteNetworkPolicyOperation manages a long-running operation from DeleteNetworkPolicy. type DeleteNetworkPolicyOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteNetworkPolicyOperation returns a new DeleteNetworkPolicyOperation from a given name. @@ -2346,10 +5567,21 @@ func (c *gRPCClient) DeleteNetworkPolicyOperation(name string) *DeleteNetworkPol } } +// DeleteNetworkPolicyOperation returns a new DeleteNetworkPolicyOperation from a given name. +// The name must be that of a previously created DeleteNetworkPolicyOperation, possibly from a different process. +func (c *restClient) DeleteNetworkPolicyOperation(name string) *DeleteNetworkPolicyOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteNetworkPolicyOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteNetworkPolicyOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -2363,6 +5595,7 @@ func (op *DeleteNetworkPolicyOperation) Wait(ctx context.Context, opts ...gax.Ca // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteNetworkPolicyOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -2393,7 +5626,8 @@ func (op *DeleteNetworkPolicyOperation) Name() string { // DeletePrivateCloudOperation manages a long-running operation from DeletePrivateCloud. type DeletePrivateCloudOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeletePrivateCloudOperation returns a new DeletePrivateCloudOperation from a given name. @@ -2404,10 +5638,21 @@ func (c *gRPCClient) DeletePrivateCloudOperation(name string) *DeletePrivateClou } } +// DeletePrivateCloudOperation returns a new DeletePrivateCloudOperation from a given name. +// The name must be that of a previously created DeletePrivateCloudOperation, possibly from a different process. +func (c *restClient) DeletePrivateCloudOperation(name string) *DeletePrivateCloudOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeletePrivateCloudOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeletePrivateCloudOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*vmwareenginepb.PrivateCloud, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmwareenginepb.PrivateCloud if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2425,6 +5670,7 @@ func (op *DeletePrivateCloudOperation) Wait(ctx context.Context, opts ...gax.Cal // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeletePrivateCloudOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*vmwareenginepb.PrivateCloud, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmwareenginepb.PrivateCloud if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2462,7 +5708,8 @@ func (op *DeletePrivateCloudOperation) Name() string { // DeleteVmwareEngineNetworkOperation manages a long-running operation from DeleteVmwareEngineNetwork. type DeleteVmwareEngineNetworkOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteVmwareEngineNetworkOperation returns a new DeleteVmwareEngineNetworkOperation from a given name. @@ -2473,10 +5720,21 @@ func (c *gRPCClient) DeleteVmwareEngineNetworkOperation(name string) *DeleteVmwa } } +// DeleteVmwareEngineNetworkOperation returns a new DeleteVmwareEngineNetworkOperation from a given name. +// The name must be that of a previously created DeleteVmwareEngineNetworkOperation, possibly from a different process. +func (c *restClient) DeleteVmwareEngineNetworkOperation(name string) *DeleteVmwareEngineNetworkOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteVmwareEngineNetworkOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteVmwareEngineNetworkOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -2490,6 +5748,7 @@ func (op *DeleteVmwareEngineNetworkOperation) Wait(ctx context.Context, opts ... // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteVmwareEngineNetworkOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -2520,7 +5779,8 @@ func (op *DeleteVmwareEngineNetworkOperation) Name() string { // ResetNsxCredentialsOperation manages a long-running operation from ResetNsxCredentials. type ResetNsxCredentialsOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // ResetNsxCredentialsOperation returns a new ResetNsxCredentialsOperation from a given name. @@ -2531,10 +5791,21 @@ func (c *gRPCClient) ResetNsxCredentialsOperation(name string) *ResetNsxCredenti } } +// ResetNsxCredentialsOperation returns a new ResetNsxCredentialsOperation from a given name. +// The name must be that of a previously created ResetNsxCredentialsOperation, possibly from a different process. +func (c *restClient) ResetNsxCredentialsOperation(name string) *ResetNsxCredentialsOperation { + override := fmt.Sprintf("/v1/%s", name) + return &ResetNsxCredentialsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *ResetNsxCredentialsOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*vmwareenginepb.PrivateCloud, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmwareenginepb.PrivateCloud if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2552,6 +5823,7 @@ func (op *ResetNsxCredentialsOperation) Wait(ctx context.Context, opts ...gax.Ca // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *ResetNsxCredentialsOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*vmwareenginepb.PrivateCloud, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmwareenginepb.PrivateCloud if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2589,7 +5861,8 @@ func (op *ResetNsxCredentialsOperation) Name() string { // ResetVcenterCredentialsOperation manages a long-running operation from ResetVcenterCredentials. type ResetVcenterCredentialsOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // ResetVcenterCredentialsOperation returns a new ResetVcenterCredentialsOperation from a given name. @@ -2600,10 +5873,21 @@ func (c *gRPCClient) ResetVcenterCredentialsOperation(name string) *ResetVcenter } } +// ResetVcenterCredentialsOperation returns a new ResetVcenterCredentialsOperation from a given name. +// The name must be that of a previously created ResetVcenterCredentialsOperation, possibly from a different process. +func (c *restClient) ResetVcenterCredentialsOperation(name string) *ResetVcenterCredentialsOperation { + override := fmt.Sprintf("/v1/%s", name) + return &ResetVcenterCredentialsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *ResetVcenterCredentialsOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*vmwareenginepb.PrivateCloud, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmwareenginepb.PrivateCloud if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2621,6 +5905,7 @@ func (op *ResetVcenterCredentialsOperation) Wait(ctx context.Context, opts ...ga // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *ResetVcenterCredentialsOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*vmwareenginepb.PrivateCloud, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmwareenginepb.PrivateCloud if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2658,7 +5943,8 @@ func (op *ResetVcenterCredentialsOperation) Name() string { // UndeletePrivateCloudOperation manages a long-running operation from UndeletePrivateCloud. type UndeletePrivateCloudOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UndeletePrivateCloudOperation returns a new UndeletePrivateCloudOperation from a given name. @@ -2669,10 +5955,21 @@ func (c *gRPCClient) UndeletePrivateCloudOperation(name string) *UndeletePrivate } } +// UndeletePrivateCloudOperation returns a new UndeletePrivateCloudOperation from a given name. +// The name must be that of a previously created UndeletePrivateCloudOperation, possibly from a different process. +func (c *restClient) UndeletePrivateCloudOperation(name string) *UndeletePrivateCloudOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UndeletePrivateCloudOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UndeletePrivateCloudOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*vmwareenginepb.PrivateCloud, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmwareenginepb.PrivateCloud if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2690,6 +5987,7 @@ func (op *UndeletePrivateCloudOperation) Wait(ctx context.Context, opts ...gax.C // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UndeletePrivateCloudOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*vmwareenginepb.PrivateCloud, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmwareenginepb.PrivateCloud if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2727,7 +6025,8 @@ func (op *UndeletePrivateCloudOperation) Name() string { // UpdateClusterOperation manages a long-running operation from UpdateCluster. type UpdateClusterOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateClusterOperation returns a new UpdateClusterOperation from a given name. @@ -2738,10 +6037,21 @@ func (c *gRPCClient) UpdateClusterOperation(name string) *UpdateClusterOperation } } +// UpdateClusterOperation returns a new UpdateClusterOperation from a given name. +// The name must be that of a previously created UpdateClusterOperation, possibly from a different process. +func (c *restClient) UpdateClusterOperation(name string) *UpdateClusterOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateClusterOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateClusterOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*vmwareenginepb.Cluster, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmwareenginepb.Cluster if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2759,6 +6069,7 @@ func (op *UpdateClusterOperation) Wait(ctx context.Context, opts ...gax.CallOpti // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateClusterOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*vmwareenginepb.Cluster, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmwareenginepb.Cluster if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2796,7 +6107,8 @@ func (op *UpdateClusterOperation) Name() string { // UpdateNetworkPolicyOperation manages a long-running operation from UpdateNetworkPolicy. type UpdateNetworkPolicyOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateNetworkPolicyOperation returns a new UpdateNetworkPolicyOperation from a given name. @@ -2807,10 +6119,21 @@ func (c *gRPCClient) UpdateNetworkPolicyOperation(name string) *UpdateNetworkPol } } +// UpdateNetworkPolicyOperation returns a new UpdateNetworkPolicyOperation from a given name. +// The name must be that of a previously created UpdateNetworkPolicyOperation, possibly from a different process. +func (c *restClient) UpdateNetworkPolicyOperation(name string) *UpdateNetworkPolicyOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateNetworkPolicyOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateNetworkPolicyOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*vmwareenginepb.NetworkPolicy, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmwareenginepb.NetworkPolicy if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2828,6 +6151,7 @@ func (op *UpdateNetworkPolicyOperation) Wait(ctx context.Context, opts ...gax.Ca // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateNetworkPolicyOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*vmwareenginepb.NetworkPolicy, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmwareenginepb.NetworkPolicy if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2865,7 +6189,8 @@ func (op *UpdateNetworkPolicyOperation) Name() string { // UpdatePrivateCloudOperation manages a long-running operation from UpdatePrivateCloud. type UpdatePrivateCloudOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdatePrivateCloudOperation returns a new UpdatePrivateCloudOperation from a given name. @@ -2876,10 +6201,21 @@ func (c *gRPCClient) UpdatePrivateCloudOperation(name string) *UpdatePrivateClou } } +// UpdatePrivateCloudOperation returns a new UpdatePrivateCloudOperation from a given name. +// The name must be that of a previously created UpdatePrivateCloudOperation, possibly from a different process. +func (c *restClient) UpdatePrivateCloudOperation(name string) *UpdatePrivateCloudOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdatePrivateCloudOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdatePrivateCloudOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*vmwareenginepb.PrivateCloud, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmwareenginepb.PrivateCloud if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2897,6 +6233,7 @@ func (op *UpdatePrivateCloudOperation) Wait(ctx context.Context, opts ...gax.Cal // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdatePrivateCloudOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*vmwareenginepb.PrivateCloud, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmwareenginepb.PrivateCloud if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -2934,7 +6271,8 @@ func (op *UpdatePrivateCloudOperation) Name() string { // UpdateVmwareEngineNetworkOperation manages a long-running operation from UpdateVmwareEngineNetwork. type UpdateVmwareEngineNetworkOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateVmwareEngineNetworkOperation returns a new UpdateVmwareEngineNetworkOperation from a given name. @@ -2945,10 +6283,21 @@ func (c *gRPCClient) UpdateVmwareEngineNetworkOperation(name string) *UpdateVmwa } } +// UpdateVmwareEngineNetworkOperation returns a new UpdateVmwareEngineNetworkOperation from a given name. +// The name must be that of a previously created UpdateVmwareEngineNetworkOperation, possibly from a different process. +func (c *restClient) UpdateVmwareEngineNetworkOperation(name string) *UpdateVmwareEngineNetworkOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateVmwareEngineNetworkOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateVmwareEngineNetworkOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*vmwareenginepb.VmwareEngineNetwork, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmwareenginepb.VmwareEngineNetwork if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -2966,6 +6315,7 @@ func (op *UpdateVmwareEngineNetworkOperation) Wait(ctx context.Context, opts ... // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateVmwareEngineNetworkOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*vmwareenginepb.VmwareEngineNetwork, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vmwareenginepb.VmwareEngineNetwork if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/vmwareengine/apiv1/vmware_engine_client_example_test.go b/vmwareengine/apiv1/vmware_engine_client_example_test.go index 838c0bec430e..c4debe7cc57d 100644 --- a/vmwareengine/apiv1/vmware_engine_client_example_test.go +++ b/vmwareengine/apiv1/vmware_engine_client_example_test.go @@ -44,6 +44,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := vmwareengine.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_ListPrivateClouds() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/vmwareengine/apiv1/vmwareenginepb/vmwareengine.pb.go b/vmwareengine/apiv1/vmwareenginepb/vmwareengine.pb.go index 62a3ed649467..9e292d68bd02 100644 --- a/vmwareengine/apiv1/vmwareenginepb/vmwareengine.pb.go +++ b/vmwareengine/apiv1/vmwareenginepb/vmwareengine.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/vmwareengine/v1/vmwareengine.proto package vmwareenginepb @@ -1713,6 +1713,7 @@ type ListClustersRequest struct { // When paginating, all other parameters provided to `ListClusters` // must match the call that provided the page token. PageToken string `protobuf:"bytes,3,opt,name=page_token,json=pageToken,proto3" json:"page_token,omitempty"` + // // To filter on multiple expressions, provide each separate expression within // parentheses. For example: // ``` @@ -4291,8 +4292,7 @@ type CreateNetworkPolicyRequest struct { // Resource names are schemeless URIs that follow the conventions in // https://cloud.google.com/apis/design/resource_names. // For example: - // - // `projects/my-project/locations/us-central1` + // `projects/my-project/locations/us-central1` Parent string `protobuf:"bytes,1,opt,name=parent,proto3" json:"parent,omitempty"` // Required. The user-provided identifier of the network policy to be created. // This identifier must be unique within parent diff --git a/vpcaccess/apiv1/doc.go b/vpcaccess/apiv1/doc.go index 5552d9f550cd..29de6f8be340 100644 --- a/vpcaccess/apiv1/doc.go +++ b/vpcaccess/apiv1/doc.go @@ -85,6 +85,8 @@ package vpcaccess // import "cloud.google.com/go/vpcaccess/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -173,3 +175,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/vpcaccess/apiv1/gapic_metadata.json b/vpcaccess/apiv1/gapic_metadata.json index 032bc74e56be..c20426ae34fc 100644 --- a/vpcaccess/apiv1/gapic_metadata.json +++ b/vpcaccess/apiv1/gapic_metadata.json @@ -46,6 +46,46 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "CreateConnector": { + "methods": [ + "CreateConnector" + ] + }, + "DeleteConnector": { + "methods": [ + "DeleteConnector" + ] + }, + "GetConnector": { + "methods": [ + "GetConnector" + ] + }, + "GetOperation": { + "methods": [ + "GetOperation" + ] + }, + "ListConnectors": { + "methods": [ + "ListConnectors" + ] + }, + "ListLocations": { + "methods": [ + "ListLocations" + ] + }, + "ListOperations": { + "methods": [ + "ListOperations" + ] + } + } } } } diff --git a/vpcaccess/apiv1/vpc_access_client.go b/vpcaccess/apiv1/vpc_access_client.go index e23392635fd6..beb6ca77f503 100644 --- a/vpcaccess/apiv1/vpc_access_client.go +++ b/vpcaccess/apiv1/vpc_access_client.go @@ -17,9 +17,12 @@ package vpcaccess import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,14 +30,17 @@ import ( lroauto "cloud.google.com/go/longrunning/autogen" vpcaccesspb "cloud.google.com/go/vpcaccess/apiv1/vpcaccesspb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" locationpb "google.golang.org/genproto/googleapis/cloud/location" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -75,6 +81,18 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + CreateConnector: []gax.CallOption{}, + GetConnector: []gax.CallOption{}, + ListConnectors: []gax.CallOption{}, + DeleteConnector: []gax.CallOption{}, + ListLocations: []gax.CallOption{}, + GetOperation: []gax.CallOption{}, + ListOperations: []gax.CallOption{}, + } +} + // internalClient is an interface that defines the methods available from Serverless VPC Access API. type internalClient interface { Close() error @@ -287,6 +305,91 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new vpc access service rest client. +// +// Serverless VPC Access API allows users to create and manage connectors for +// App Engine, Cloud Functions and Cloud Run to have internal connections to +// Virtual Private Cloud networks. +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://vpcaccess.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://vpcaccess.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://vpcaccess.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) CreateConnector(ctx context.Context, req *vpcaccesspb.CreateConnectorRequest, opts ...gax.CallOption) (*CreateConnectorOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) @@ -509,9 +612,530 @@ func (c *gRPCClient) ListOperations(ctx context.Context, req *longrunningpb.List return it } +// CreateConnector creates a Serverless VPC Access connector, returns an operation. +func (c *restClient) CreateConnector(ctx context.Context, req *vpcaccesspb.CreateConnectorRequest, opts ...gax.CallOption) (*CreateConnectorOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetConnector() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/connectors", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("connectorId", fmt.Sprintf("%v", req.GetConnectorId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateConnectorOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// GetConnector gets a Serverless VPC Access connector. Returns NOT_FOUND if the resource +// does not exist. +func (c *restClient) GetConnector(ctx context.Context, req *vpcaccesspb.GetConnectorRequest, opts ...gax.CallOption) (*vpcaccesspb.Connector, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetConnector[0:len((*c.CallOptions).GetConnector):len((*c.CallOptions).GetConnector)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &vpcaccesspb.Connector{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListConnectors lists Serverless VPC Access connectors. +func (c *restClient) ListConnectors(ctx context.Context, req *vpcaccesspb.ListConnectorsRequest, opts ...gax.CallOption) *ConnectorIterator { + it := &ConnectorIterator{} + req = proto.Clone(req).(*vpcaccesspb.ListConnectorsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*vpcaccesspb.Connector, string, error) { + resp := &vpcaccesspb.ListConnectorsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/connectors", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetConnectors(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// DeleteConnector deletes a Serverless VPC Access connector. Returns NOT_FOUND if the +// resource does not exist. +func (c *restClient) DeleteConnector(ctx context.Context, req *vpcaccesspb.DeleteConnectorRequest, opts ...gax.CallOption) (*DeleteConnectorOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteConnectorOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// ListLocations lists information about the supported locations for this service. +func (c *restClient) ListLocations(ctx context.Context, req *locationpb.ListLocationsRequest, opts ...gax.CallOption) *LocationIterator { + it := &LocationIterator{} + req = proto.Clone(req).(*locationpb.ListLocationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*locationpb.Location, string, error) { + resp := &locationpb.ListLocationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/locations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetLocations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetOperation is a utility method from google.longrunning.Operations. +func (c *restClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListOperations is a utility method from google.longrunning.Operations. +func (c *restClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + it := &OperationIterator{} + req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { + resp := &longrunningpb.ListOperationsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/operations", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetOperations(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + // CreateConnectorOperation manages a long-running operation from CreateConnector. type CreateConnectorOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateConnectorOperation returns a new CreateConnectorOperation from a given name. @@ -522,10 +1146,21 @@ func (c *gRPCClient) CreateConnectorOperation(name string) *CreateConnectorOpera } } +// CreateConnectorOperation returns a new CreateConnectorOperation from a given name. +// The name must be that of a previously created CreateConnectorOperation, possibly from a different process. +func (c *restClient) CreateConnectorOperation(name string) *CreateConnectorOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateConnectorOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateConnectorOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*vpcaccesspb.Connector, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vpcaccesspb.Connector if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -543,6 +1178,7 @@ func (op *CreateConnectorOperation) Wait(ctx context.Context, opts ...gax.CallOp // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateConnectorOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*vpcaccesspb.Connector, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp vpcaccesspb.Connector if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -580,7 +1216,8 @@ func (op *CreateConnectorOperation) Name() string { // DeleteConnectorOperation manages a long-running operation from DeleteConnector. type DeleteConnectorOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteConnectorOperation returns a new DeleteConnectorOperation from a given name. @@ -591,10 +1228,21 @@ func (c *gRPCClient) DeleteConnectorOperation(name string) *DeleteConnectorOpera } } +// DeleteConnectorOperation returns a new DeleteConnectorOperation from a given name. +// The name must be that of a previously created DeleteConnectorOperation, possibly from a different process. +func (c *restClient) DeleteConnectorOperation(name string) *DeleteConnectorOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteConnectorOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteConnectorOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -608,6 +1256,7 @@ func (op *DeleteConnectorOperation) Wait(ctx context.Context, opts ...gax.CallOp // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteConnectorOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } diff --git a/vpcaccess/apiv1/vpc_access_client_example_test.go b/vpcaccess/apiv1/vpc_access_client_example_test.go index 41ab3e636c56..fd460e9a4e2a 100644 --- a/vpcaccess/apiv1/vpc_access_client_example_test.go +++ b/vpcaccess/apiv1/vpc_access_client_example_test.go @@ -43,6 +43,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := vpcaccess.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_CreateConnector() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/vpcaccess/apiv1/vpcaccesspb/vpc_access.pb.go b/vpcaccess/apiv1/vpcaccesspb/vpc_access.pb.go index a99760ed7bd1..40964ff48387 100644 --- a/vpcaccess/apiv1/vpcaccesspb/vpc_access.pb.go +++ b/vpcaccess/apiv1/vpcaccesspb/vpc_access.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/vpcaccess/v1/vpc_access.proto package vpcaccesspb diff --git a/webrisk/apiv1/doc.go b/webrisk/apiv1/doc.go index 87b7a55972b2..32ad89f0dee1 100644 --- a/webrisk/apiv1/doc.go +++ b/webrisk/apiv1/doc.go @@ -78,6 +78,8 @@ package webrisk // import "cloud.google.com/go/webrisk/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -166,3 +168,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/webrisk/apiv1/gapic_metadata.json b/webrisk/apiv1/gapic_metadata.json index f8d27fd70289..3a5beba99123 100644 --- a/webrisk/apiv1/gapic_metadata.json +++ b/webrisk/apiv1/gapic_metadata.json @@ -31,6 +31,31 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "ComputeThreatListDiff": { + "methods": [ + "ComputeThreatListDiff" + ] + }, + "CreateSubmission": { + "methods": [ + "CreateSubmission" + ] + }, + "SearchHashes": { + "methods": [ + "SearchHashes" + ] + }, + "SearchUris": { + "methods": [ + "SearchUris" + ] + } + } } } } diff --git a/webrisk/apiv1/web_risk_client.go b/webrisk/apiv1/web_risk_client.go index 69ddfd085224..db9f4ad2dd14 100644 --- a/webrisk/apiv1/web_risk_client.go +++ b/webrisk/apiv1/web_risk_client.go @@ -17,20 +17,26 @@ package webrisk import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" webriskpb "cloud.google.com/go/webrisk/apiv1/webriskpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" ) var newClientHook clientHook @@ -97,6 +103,45 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + ComputeThreatListDiff: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + SearchUris: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + SearchHashes: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + CreateSubmission: []gax.CallOption{}, + } +} + // internalClient is an interface that defines the methods available from Web Risk API. type internalClient interface { Close() error @@ -265,6 +310,75 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new web risk service rest client. +// +// Web Risk API defines an interface to detect malicious URLs on your +// website and in client applications. +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://webrisk.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://webrisk.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://webrisk.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) ComputeThreatListDiff(ctx context.Context, req *webriskpb.ComputeThreatListDiffRequest, opts ...gax.CallOption) (*webriskpb.ComputeThreatListDiffResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) @@ -346,3 +460,284 @@ func (c *gRPCClient) CreateSubmission(ctx context.Context, req *webriskpb.Create } return resp, nil } + +// ComputeThreatListDiff gets the most recent threat list diffs. These diffs should be applied to +// a local database of hashes to keep it up-to-date. If the local database is +// empty or excessively out-of-date, a complete snapshot of the database will +// be returned. This Method only updates a single ThreatList at a time. To +// update multiple ThreatList databases, this method needs to be called once +// for each list. +func (c *restClient) ComputeThreatListDiff(ctx context.Context, req *webriskpb.ComputeThreatListDiffRequest, opts ...gax.CallOption) (*webriskpb.ComputeThreatListDiffResponse, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/threatLists:computeDiff") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetConstraints().GetMaxDatabaseEntries() != 0 { + params.Add("constraints.maxDatabaseEntries", fmt.Sprintf("%v", req.GetConstraints().GetMaxDatabaseEntries())) + } + if req.GetConstraints().GetMaxDiffEntries() != 0 { + params.Add("constraints.maxDiffEntries", fmt.Sprintf("%v", req.GetConstraints().GetMaxDiffEntries())) + } + if items := req.GetConstraints().GetSupportedCompressions(); len(items) > 0 { + for _, item := range items { + params.Add("constraints.supportedCompressions", fmt.Sprintf("%v", item)) + } + } + params.Add("threatType", fmt.Sprintf("%v", req.GetThreatType())) + if req.GetVersionToken() != nil { + params.Add("versionToken", fmt.Sprintf("%v", req.GetVersionToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).ComputeThreatListDiff[0:len((*c.CallOptions).ComputeThreatListDiff):len((*c.CallOptions).ComputeThreatListDiff)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &webriskpb.ComputeThreatListDiffResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SearchUris this method is used to check whether a URI is on a given threatList. +// Multiple threatLists may be searched in a single query. +// The response will list all requested threatLists the URI was found to +// match. If the URI is not found on any of the requested ThreatList an +// empty response will be returned. +func (c *restClient) SearchUris(ctx context.Context, req *webriskpb.SearchUrisRequest, opts ...gax.CallOption) (*webriskpb.SearchUrisResponse, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/uris:search") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if items := req.GetThreatTypes(); len(items) > 0 { + for _, item := range items { + params.Add("threatTypes", fmt.Sprintf("%v", item)) + } + } + params.Add("uri", fmt.Sprintf("%v", req.GetUri())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SearchUris[0:len((*c.CallOptions).SearchUris):len((*c.CallOptions).SearchUris)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &webriskpb.SearchUrisResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// SearchHashes gets the full hashes that match the requested hash prefix. +// This is used after a hash prefix is looked up in a threatList +// and there is a match. The client side threatList only holds partial hashes +// so the client must query this method to determine if there is a full +// hash match of a threat. +func (c *restClient) SearchHashes(ctx context.Context, req *webriskpb.SearchHashesRequest, opts ...gax.CallOption) (*webriskpb.SearchHashesResponse, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/hashes:search") + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetHashPrefix() != nil { + params.Add("hashPrefix", fmt.Sprintf("%v", req.GetHashPrefix())) + } + if items := req.GetThreatTypes(); len(items) > 0 { + for _, item := range items { + params.Add("threatTypes", fmt.Sprintf("%v", item)) + } + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).SearchHashes[0:len((*c.CallOptions).SearchHashes):len((*c.CallOptions).SearchHashes)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &webriskpb.SearchHashesResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateSubmission creates a Submission of a URI suspected of containing phishing content to +// be reviewed. If the result verifies the existence of malicious phishing +// content, the site will be added to the Google’s Social Engineering +// lists (at https://support.google.com/webmasters/answer/6350487/) in order to +// protect users that could get exposed to this threat in the future. Only +// allowlisted projects can use this method during Early Access. Please reach +// out to Sales or your customer engineer to obtain access. +func (c *restClient) CreateSubmission(ctx context.Context, req *webriskpb.CreateSubmissionRequest, opts ...gax.CallOption) (*webriskpb.Submission, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetSubmission() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/submissions", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateSubmission[0:len((*c.CallOptions).CreateSubmission):len((*c.CallOptions).CreateSubmission)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &webriskpb.Submission{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} diff --git a/webrisk/apiv1/web_risk_client_example_test.go b/webrisk/apiv1/web_risk_client_example_test.go index 9d65eb3025d3..fe5c2b64640a 100644 --- a/webrisk/apiv1/web_risk_client_example_test.go +++ b/webrisk/apiv1/web_risk_client_example_test.go @@ -40,6 +40,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := webrisk.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_ComputeThreatListDiff() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/webrisk/apiv1/webriskpb/webrisk.pb.go b/webrisk/apiv1/webriskpb/webrisk.pb.go index c897d389bf25..de2d9d065ab5 100644 --- a/webrisk/apiv1/webriskpb/webrisk.pb.go +++ b/webrisk/apiv1/webriskpb/webrisk.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/webrisk/v1/webrisk.proto package webriskpb diff --git a/webrisk/apiv1beta1/web_risk_service_v1_beta1_client.go b/webrisk/apiv1beta1/web_risk_service_v1_beta1_client.go index 5d3b63ea9aba..5fb1785df821 100644 --- a/webrisk/apiv1beta1/web_risk_service_v1_beta1_client.go +++ b/webrisk/apiv1beta1/web_risk_service_v1_beta1_client.go @@ -423,14 +423,17 @@ func (c *webRiskServiceV1Beta1RESTClient) ComputeThreatListDiff(ctx context.Cont baseUrl.Path += fmt.Sprintf("/v1beta1/threatLists:computeDiff") params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetConstraints().GetMaxDatabaseEntries() != 0 { params.Add("constraints.maxDatabaseEntries", fmt.Sprintf("%v", req.GetConstraints().GetMaxDatabaseEntries())) } if req.GetConstraints().GetMaxDiffEntries() != 0 { params.Add("constraints.maxDiffEntries", fmt.Sprintf("%v", req.GetConstraints().GetMaxDiffEntries())) } - if req.GetConstraints().GetSupportedCompressions() != nil { - params.Add("constraints.supportedCompressions", fmt.Sprintf("%v", req.GetConstraints().GetSupportedCompressions())) + if items := req.GetConstraints().GetSupportedCompressions(); len(items) > 0 { + for _, item := range items { + params.Add("constraints.supportedCompressions", fmt.Sprintf("%v", item)) + } } params.Add("threatType", fmt.Sprintf("%v", req.GetThreatType())) if req.GetVersionToken() != nil { @@ -491,8 +494,11 @@ func (c *webRiskServiceV1Beta1RESTClient) SearchUris(ctx context.Context, req *w baseUrl.Path += fmt.Sprintf("/v1beta1/uris:search") params := url.Values{} - if req.GetThreatTypes() != nil { - params.Add("threatTypes", fmt.Sprintf("%v", req.GetThreatTypes())) + params.Add("$alt", "json;enum-encoding=int") + if items := req.GetThreatTypes(); len(items) > 0 { + for _, item := range items { + params.Add("threatTypes", fmt.Sprintf("%v", item)) + } } params.Add("uri", fmt.Sprintf("%v", req.GetUri())) @@ -554,11 +560,14 @@ func (c *webRiskServiceV1Beta1RESTClient) SearchHashes(ctx context.Context, req baseUrl.Path += fmt.Sprintf("/v1beta1/hashes:search") params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetHashPrefix() != nil { params.Add("hashPrefix", fmt.Sprintf("%v", req.GetHashPrefix())) } - if req.GetThreatTypes() != nil { - params.Add("threatTypes", fmt.Sprintf("%v", req.GetThreatTypes())) + if items := req.GetThreatTypes(); len(items) > 0 { + for _, item := range items { + params.Add("threatTypes", fmt.Sprintf("%v", item)) + } } baseUrl.RawQuery = params.Encode() diff --git a/webrisk/apiv1beta1/webriskpb/webrisk.pb.go b/webrisk/apiv1beta1/webriskpb/webrisk.pb.go index 924c20108661..fa163288e12c 100644 --- a/webrisk/apiv1beta1/webriskpb/webrisk.pb.go +++ b/webrisk/apiv1beta1/webriskpb/webrisk.pb.go @@ -15,8 +15,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/webrisk/v1beta1/webrisk.proto package webriskpb diff --git a/websecurityscanner/apiv1/doc.go b/websecurityscanner/apiv1/doc.go index 4d3251c173e9..c864833cd5cb 100644 --- a/websecurityscanner/apiv1/doc.go +++ b/websecurityscanner/apiv1/doc.go @@ -80,6 +80,8 @@ package websecurityscanner // import "cloud.google.com/go/websecurityscanner/api import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -168,3 +170,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/websecurityscanner/apiv1/gapic_metadata.json b/websecurityscanner/apiv1/gapic_metadata.json index 9fc5f875602a..0f806929c50a 100644 --- a/websecurityscanner/apiv1/gapic_metadata.json +++ b/websecurityscanner/apiv1/gapic_metadata.json @@ -76,6 +76,76 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "CreateScanConfig": { + "methods": [ + "CreateScanConfig" + ] + }, + "DeleteScanConfig": { + "methods": [ + "DeleteScanConfig" + ] + }, + "GetFinding": { + "methods": [ + "GetFinding" + ] + }, + "GetScanConfig": { + "methods": [ + "GetScanConfig" + ] + }, + "GetScanRun": { + "methods": [ + "GetScanRun" + ] + }, + "ListCrawledUrls": { + "methods": [ + "ListCrawledUrls" + ] + }, + "ListFindingTypeStats": { + "methods": [ + "ListFindingTypeStats" + ] + }, + "ListFindings": { + "methods": [ + "ListFindings" + ] + }, + "ListScanConfigs": { + "methods": [ + "ListScanConfigs" + ] + }, + "ListScanRuns": { + "methods": [ + "ListScanRuns" + ] + }, + "StartScanRun": { + "methods": [ + "StartScanRun" + ] + }, + "StopScanRun": { + "methods": [ + "StopScanRun" + ] + }, + "UpdateScanConfig": { + "methods": [ + "UpdateScanConfig" + ] + } + } } } } diff --git a/websecurityscanner/apiv1/web_security_scanner_client.go b/websecurityscanner/apiv1/web_security_scanner_client.go index e5792e1b6fed..eec6551938f9 100644 --- a/websecurityscanner/apiv1/web_security_scanner_client.go +++ b/websecurityscanner/apiv1/web_security_scanner_client.go @@ -17,21 +17,27 @@ package websecurityscanner import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" websecurityscannerpb "cloud.google.com/go/websecurityscanner/apiv1/websecurityscannerpb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -183,6 +189,114 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + CreateScanConfig: []gax.CallOption{}, + DeleteScanConfig: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + GetScanConfig: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + ListScanConfigs: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + UpdateScanConfig: []gax.CallOption{}, + StartScanRun: []gax.CallOption{}, + GetScanRun: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + ListScanRuns: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + StopScanRun: []gax.CallOption{}, + ListCrawledUrls: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + GetFinding: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + ListFindings: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + ListFindingTypeStats: []gax.CallOption{ + gax.WithRetry(func() gax.Retryer { + return gax.OnHTTPCodes(gax.Backoff{ + Initial: 100 * time.Millisecond, + Max: 60000 * time.Millisecond, + Multiplier: 1.30, + }, + http.StatusGatewayTimeout, + http.StatusServiceUnavailable) + }), + }, + } +} + // internalClient is an interface that defines the methods available from Web Security Scanner API. type internalClient interface { Close() error @@ -389,6 +503,76 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new web security scanner rest client. +// +// Web Security Scanner Service identifies security vulnerabilities in web +// applications hosted on Google Cloud. It crawls your application, and +// attempts to exercise as many user inputs and event handlers as possible. +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://websecurityscanner.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://websecurityscanner.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://websecurityscanner.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) CreateScanConfig(ctx context.Context, req *websecurityscannerpb.CreateScanConfigRequest, opts ...gax.CallOption) (*websecurityscannerpb.ScanConfig, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) @@ -763,6 +947,899 @@ func (c *gRPCClient) ListFindingTypeStats(ctx context.Context, req *websecuritys return resp, nil } +// CreateScanConfig creates a new ScanConfig. +func (c *restClient) CreateScanConfig(ctx context.Context, req *websecurityscannerpb.CreateScanConfigRequest, opts ...gax.CallOption) (*websecurityscannerpb.ScanConfig, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetScanConfig() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/scanConfigs", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).CreateScanConfig[0:len((*c.CallOptions).CreateScanConfig):len((*c.CallOptions).CreateScanConfig)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &websecurityscannerpb.ScanConfig{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// DeleteScanConfig deletes an existing ScanConfig and its child resources. +func (c *restClient) DeleteScanConfig(ctx context.Context, req *websecurityscannerpb.DeleteScanConfigRequest, opts ...gax.CallOption) error { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + return gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + // Returns nil if there is no error, otherwise wraps + // the response code and body into a non-nil error + return googleapi.CheckResponse(httpRsp) + }, opts...) +} + +// GetScanConfig gets a ScanConfig. +func (c *restClient) GetScanConfig(ctx context.Context, req *websecurityscannerpb.GetScanConfigRequest, opts ...gax.CallOption) (*websecurityscannerpb.ScanConfig, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetScanConfig[0:len((*c.CallOptions).GetScanConfig):len((*c.CallOptions).GetScanConfig)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &websecurityscannerpb.ScanConfig{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListScanConfigs lists ScanConfigs under a given project. +func (c *restClient) ListScanConfigs(ctx context.Context, req *websecurityscannerpb.ListScanConfigsRequest, opts ...gax.CallOption) *ScanConfigIterator { + it := &ScanConfigIterator{} + req = proto.Clone(req).(*websecurityscannerpb.ListScanConfigsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*websecurityscannerpb.ScanConfig, string, error) { + resp := &websecurityscannerpb.ListScanConfigsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/scanConfigs", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetScanConfigs(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// UpdateScanConfig updates a ScanConfig. This method support partial update of a ScanConfig. +func (c *restClient) UpdateScanConfig(ctx context.Context, req *websecurityscannerpb.UpdateScanConfigRequest, opts ...gax.CallOption) (*websecurityscannerpb.ScanConfig, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetScanConfig() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetScanConfig().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "scan_config.name", url.QueryEscape(req.GetScanConfig().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).UpdateScanConfig[0:len((*c.CallOptions).UpdateScanConfig):len((*c.CallOptions).UpdateScanConfig)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &websecurityscannerpb.ScanConfig{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// StartScanRun start a ScanRun according to the given ScanConfig. +func (c *restClient) StartScanRun(ctx context.Context, req *websecurityscannerpb.StartScanRunRequest, opts ...gax.CallOption) (*websecurityscannerpb.ScanRun, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:start", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).StartScanRun[0:len((*c.CallOptions).StartScanRun):len((*c.CallOptions).StartScanRun)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &websecurityscannerpb.ScanRun{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// GetScanRun gets a ScanRun. +func (c *restClient) GetScanRun(ctx context.Context, req *websecurityscannerpb.GetScanRunRequest, opts ...gax.CallOption) (*websecurityscannerpb.ScanRun, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetScanRun[0:len((*c.CallOptions).GetScanRun):len((*c.CallOptions).GetScanRun)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &websecurityscannerpb.ScanRun{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListScanRuns lists ScanRuns under a given ScanConfig, in descending order of ScanRun +// stop time. +func (c *restClient) ListScanRuns(ctx context.Context, req *websecurityscannerpb.ListScanRunsRequest, opts ...gax.CallOption) *ScanRunIterator { + it := &ScanRunIterator{} + req = proto.Clone(req).(*websecurityscannerpb.ListScanRunsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*websecurityscannerpb.ScanRun, string, error) { + resp := &websecurityscannerpb.ListScanRunsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/scanRuns", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetScanRuns(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// StopScanRun stops a ScanRun. The stopped ScanRun is returned. +func (c *restClient) StopScanRun(ctx context.Context, req *websecurityscannerpb.StopScanRunRequest, opts ...gax.CallOption) (*websecurityscannerpb.ScanRun, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + jsonReq, err := m.Marshal(req) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v:stop", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).StopScanRun[0:len((*c.CallOptions).StopScanRun):len((*c.CallOptions).StopScanRun)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &websecurityscannerpb.ScanRun{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListCrawledUrls list CrawledUrls under a given ScanRun. +func (c *restClient) ListCrawledUrls(ctx context.Context, req *websecurityscannerpb.ListCrawledUrlsRequest, opts ...gax.CallOption) *CrawledUrlIterator { + it := &CrawledUrlIterator{} + req = proto.Clone(req).(*websecurityscannerpb.ListCrawledUrlsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*websecurityscannerpb.CrawledUrl, string, error) { + resp := &websecurityscannerpb.ListCrawledUrlsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/crawledUrls", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetCrawledUrls(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetFinding gets a Finding. +func (c *restClient) GetFinding(ctx context.Context, req *websecurityscannerpb.GetFindingRequest, opts ...gax.CallOption) (*websecurityscannerpb.Finding, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetFinding[0:len((*c.CallOptions).GetFinding):len((*c.CallOptions).GetFinding)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &websecurityscannerpb.Finding{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// ListFindings list Findings under a given ScanRun. +func (c *restClient) ListFindings(ctx context.Context, req *websecurityscannerpb.ListFindingsRequest, opts ...gax.CallOption) *FindingIterator { + it := &FindingIterator{} + req = proto.Clone(req).(*websecurityscannerpb.ListFindingsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*websecurityscannerpb.Finding, string, error) { + resp := &websecurityscannerpb.ListFindingsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/findings", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetFindings(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// ListFindingTypeStats list all FindingTypeStats under a given ScanRun. +func (c *restClient) ListFindingTypeStats(ctx context.Context, req *websecurityscannerpb.ListFindingTypeStatsRequest, opts ...gax.CallOption) (*websecurityscannerpb.ListFindingTypeStatsResponse, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/findingTypeStats", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).ListFindingTypeStats[0:len((*c.CallOptions).ListFindingTypeStats):len((*c.CallOptions).ListFindingTypeStats)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &websecurityscannerpb.ListFindingTypeStatsResponse{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + // CrawledUrlIterator manages a stream of *websecurityscannerpb.CrawledUrl. type CrawledUrlIterator struct { items []*websecurityscannerpb.CrawledUrl diff --git a/websecurityscanner/apiv1/web_security_scanner_client_example_test.go b/websecurityscanner/apiv1/web_security_scanner_client_example_test.go index 11fc07d72ad6..0e790018cccb 100644 --- a/websecurityscanner/apiv1/web_security_scanner_client_example_test.go +++ b/websecurityscanner/apiv1/web_security_scanner_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := websecurityscanner.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_CreateScanConfig() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/websecurityscanner/apiv1/websecurityscannerpb/crawled_url.pb.go b/websecurityscanner/apiv1/websecurityscannerpb/crawled_url.pb.go index 76d88a4044ad..57f38507d2b7 100644 --- a/websecurityscanner/apiv1/websecurityscannerpb/crawled_url.pb.go +++ b/websecurityscanner/apiv1/websecurityscannerpb/crawled_url.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/websecurityscanner/v1/crawled_url.proto package websecurityscannerpb diff --git a/websecurityscanner/apiv1/websecurityscannerpb/finding.pb.go b/websecurityscanner/apiv1/websecurityscannerpb/finding.pb.go index c4141dc77fec..50b3da162e48 100644 --- a/websecurityscanner/apiv1/websecurityscannerpb/finding.pb.go +++ b/websecurityscanner/apiv1/websecurityscannerpb/finding.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/websecurityscanner/v1/finding.proto package websecurityscannerpb diff --git a/websecurityscanner/apiv1/websecurityscannerpb/finding_addon.pb.go b/websecurityscanner/apiv1/websecurityscannerpb/finding_addon.pb.go index f5c68a88fb2e..cbc1722d9eb1 100644 --- a/websecurityscanner/apiv1/websecurityscannerpb/finding_addon.pb.go +++ b/websecurityscanner/apiv1/websecurityscannerpb/finding_addon.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/websecurityscanner/v1/finding_addon.proto package websecurityscannerpb diff --git a/websecurityscanner/apiv1/websecurityscannerpb/finding_type_stats.pb.go b/websecurityscanner/apiv1/websecurityscannerpb/finding_type_stats.pb.go index 16b79be0bca4..ad7cb9b5dd21 100644 --- a/websecurityscanner/apiv1/websecurityscannerpb/finding_type_stats.pb.go +++ b/websecurityscanner/apiv1/websecurityscannerpb/finding_type_stats.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/websecurityscanner/v1/finding_type_stats.proto package websecurityscannerpb diff --git a/websecurityscanner/apiv1/websecurityscannerpb/scan_config.pb.go b/websecurityscanner/apiv1/websecurityscannerpb/scan_config.pb.go index 13f617990607..be563147f8f2 100644 --- a/websecurityscanner/apiv1/websecurityscannerpb/scan_config.pb.go +++ b/websecurityscanner/apiv1/websecurityscannerpb/scan_config.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/websecurityscanner/v1/scan_config.proto package websecurityscannerpb @@ -380,7 +380,6 @@ type ScanConfig_Authentication struct { // Authentication configuration // // Types that are assignable to Authentication: - // // *ScanConfig_Authentication_GoogleAccount_ // *ScanConfig_Authentication_CustomAccount_ // *ScanConfig_Authentication_IapCredential_ @@ -674,7 +673,6 @@ type ScanConfig_Authentication_IapCredential struct { // Identity-Aware-Proxy (IAP) Authentication Configuration // // Types that are assignable to IapCredentials: - // // *ScanConfig_Authentication_IapCredential_IapTestServiceAccountInfo_ IapCredentials isScanConfig_Authentication_IapCredential_IapCredentials `protobuf_oneof:"iap_credentials"` } diff --git a/websecurityscanner/apiv1/websecurityscannerpb/scan_config_error.pb.go b/websecurityscanner/apiv1/websecurityscannerpb/scan_config_error.pb.go index df5fef854b72..7e8feed868bc 100644 --- a/websecurityscanner/apiv1/websecurityscannerpb/scan_config_error.pb.go +++ b/websecurityscanner/apiv1/websecurityscannerpb/scan_config_error.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/websecurityscanner/v1/scan_config_error.proto package websecurityscannerpb diff --git a/websecurityscanner/apiv1/websecurityscannerpb/scan_run.pb.go b/websecurityscanner/apiv1/websecurityscannerpb/scan_run.pb.go index 70a0850b0791..775581ce1188 100644 --- a/websecurityscanner/apiv1/websecurityscannerpb/scan_run.pb.go +++ b/websecurityscanner/apiv1/websecurityscannerpb/scan_run.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/websecurityscanner/v1/scan_run.proto package websecurityscannerpb diff --git a/websecurityscanner/apiv1/websecurityscannerpb/scan_run_error_trace.pb.go b/websecurityscanner/apiv1/websecurityscannerpb/scan_run_error_trace.pb.go index c07cfbbfd7cc..4f2957a2faaa 100644 --- a/websecurityscanner/apiv1/websecurityscannerpb/scan_run_error_trace.pb.go +++ b/websecurityscanner/apiv1/websecurityscannerpb/scan_run_error_trace.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/websecurityscanner/v1/scan_run_error_trace.proto package websecurityscannerpb diff --git a/websecurityscanner/apiv1/websecurityscannerpb/scan_run_log.pb.go b/websecurityscanner/apiv1/websecurityscannerpb/scan_run_log.pb.go index 25d14738f878..c8f558086d96 100644 --- a/websecurityscanner/apiv1/websecurityscannerpb/scan_run_log.pb.go +++ b/websecurityscanner/apiv1/websecurityscannerpb/scan_run_log.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/websecurityscanner/v1/scan_run_log.proto package websecurityscannerpb diff --git a/websecurityscanner/apiv1/websecurityscannerpb/scan_run_warning_trace.pb.go b/websecurityscanner/apiv1/websecurityscannerpb/scan_run_warning_trace.pb.go index da5ef8ddfd9d..844d88fb17ba 100644 --- a/websecurityscanner/apiv1/websecurityscannerpb/scan_run_warning_trace.pb.go +++ b/websecurityscanner/apiv1/websecurityscannerpb/scan_run_warning_trace.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/websecurityscanner/v1/scan_run_warning_trace.proto package websecurityscannerpb diff --git a/websecurityscanner/apiv1/websecurityscannerpb/web_security_scanner.pb.go b/websecurityscanner/apiv1/websecurityscannerpb/web_security_scanner.pb.go index 58caeabd8447..819f2cd9c291 100644 --- a/websecurityscanner/apiv1/websecurityscannerpb/web_security_scanner.pb.go +++ b/websecurityscanner/apiv1/websecurityscannerpb/web_security_scanner.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/websecurityscanner/v1/web_security_scanner.proto package websecurityscannerpb diff --git a/workflows/apiv1/doc.go b/workflows/apiv1/doc.go index ac083fd00f4d..0d97592d624c 100644 --- a/workflows/apiv1/doc.go +++ b/workflows/apiv1/doc.go @@ -87,6 +87,8 @@ package workflows // import "cloud.google.com/go/workflows/apiv1" import ( "context" + "fmt" + "net/http" "os" "runtime" "strconv" @@ -175,3 +177,22 @@ func versionGo() string { } return "UNKNOWN" } + +// maybeUnknownEnum wraps the given proto-JSON parsing error if it is the result +// of receiving an unknown enum value. +func maybeUnknownEnum(err error) error { + if strings.Contains(err.Error(), "invalid value for enum type") { + err = fmt.Errorf("received an unknown enum value; a later version of the library may support it: %w", err) + } + return err +} + +// buildHeaders extracts metadata from the outgoing context, joins it with any other +// given metadata, and converts them into a http.Header. +func buildHeaders(ctx context.Context, mds ...metadata.MD) http.Header { + if cmd, ok := metadata.FromOutgoingContext(ctx); ok { + mds = append(mds, cmd) + } + md := metadata.Join(mds...) + return http.Header(md) +} diff --git a/workflows/apiv1/gapic_metadata.json b/workflows/apiv1/gapic_metadata.json index 964654d9fe42..e2c711a06c98 100644 --- a/workflows/apiv1/gapic_metadata.json +++ b/workflows/apiv1/gapic_metadata.json @@ -36,6 +36,36 @@ ] } } + }, + "rest": { + "libraryClient": "Client", + "rpcs": { + "CreateWorkflow": { + "methods": [ + "CreateWorkflow" + ] + }, + "DeleteWorkflow": { + "methods": [ + "DeleteWorkflow" + ] + }, + "GetWorkflow": { + "methods": [ + "GetWorkflow" + ] + }, + "ListWorkflows": { + "methods": [ + "ListWorkflows" + ] + }, + "UpdateWorkflow": { + "methods": [ + "UpdateWorkflow" + ] + } + } } } } diff --git a/workflows/apiv1/workflows_client.go b/workflows/apiv1/workflows_client.go index 3bbe87a606af..604001ebb08f 100644 --- a/workflows/apiv1/workflows_client.go +++ b/workflows/apiv1/workflows_client.go @@ -17,9 +17,12 @@ package workflows import ( + "bytes" "context" "fmt" + "io/ioutil" "math" + "net/http" "net/url" "time" @@ -27,13 +30,16 @@ import ( lroauto "cloud.google.com/go/longrunning/autogen" workflowspb "cloud.google.com/go/workflows/apiv1/workflowspb" gax "github.com/googleapis/gax-go/v2" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" + httptransport "google.golang.org/api/transport/http" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -70,6 +76,16 @@ func defaultCallOptions() *CallOptions { } } +func defaultRESTCallOptions() *CallOptions { + return &CallOptions{ + ListWorkflows: []gax.CallOption{}, + GetWorkflow: []gax.CallOption{}, + CreateWorkflow: []gax.CallOption{}, + DeleteWorkflow: []gax.CallOption{}, + UpdateWorkflow: []gax.CallOption{}, + } +} + // internalClient is an interface that defines the methods available from Workflows API. type internalClient interface { Close() error @@ -278,6 +294,91 @@ func (c *gRPCClient) Close() error { return c.connPool.Close() } +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type restClient struct { + // The http endpoint to connect to. + endpoint string + + // The http client. + httpClient *http.Client + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD + + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions +} + +// NewRESTClient creates a new workflows rest client. +// +// Workflows is used to deploy and execute workflow programs. +// Workflows makes sure the program executes reliably, despite hardware and +// networking interruptions. +func NewRESTClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { + clientOpts := append(defaultRESTClientOptions(), opts...) + httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...) + if err != nil { + return nil, err + } + + callOpts := defaultRESTCallOptions() + c := &restClient{ + endpoint: endpoint, + httpClient: httpClient, + CallOptions: &callOpts, + } + c.setGoogleClientInfo() + + lroOpts := []option.ClientOption{ + option.WithHTTPClient(httpClient), + option.WithEndpoint(endpoint), + } + opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...) + if err != nil { + return nil, err + } + c.LROClient = &opClient + + return &Client{internalClient: c, CallOptions: callOpts}, nil +} + +func defaultRESTClientOptions() []option.ClientOption { + return []option.ClientOption{ + internaloption.WithDefaultEndpoint("https://workflows.googleapis.com"), + internaloption.WithDefaultMTLSEndpoint("https://workflows.mtls.googleapis.com"), + internaloption.WithDefaultAudience("https://workflows.googleapis.com/"), + internaloption.WithDefaultScopes(DefaultAuthScopes()...), + } +} + +// 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 *restClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN") + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *restClient) Close() error { + // Replace httpClient with nil to force cleanup. + c.httpClient = nil + return nil +} + +// Connection returns a connection to the API service. +// +// Deprecated: This method always returns nil. +func (c *restClient) Connection() *grpc.ClientConn { + return nil +} func (c *gRPCClient) ListWorkflows(ctx context.Context, req *workflowspb.ListWorkflowsRequest, opts ...gax.CallOption) *WorkflowIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) @@ -397,9 +498,379 @@ func (c *gRPCClient) UpdateWorkflow(ctx context.Context, req *workflowspb.Update }, nil } +// ListWorkflows lists Workflows in a given project and location. +// The default order is not specified. +func (c *restClient) ListWorkflows(ctx context.Context, req *workflowspb.ListWorkflowsRequest, opts ...gax.CallOption) *WorkflowIterator { + it := &WorkflowIterator{} + req = proto.Clone(req).(*workflowspb.ListWorkflowsRequest) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + it.InternalFetch = func(pageSize int, pageToken string) ([]*workflowspb.Workflow, string, error) { + resp := &workflowspb.ListWorkflowsResponse{} + if pageToken != "" { + req.PageToken = pageToken + } + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else if pageSize != 0 { + req.PageSize = int32(pageSize) + } + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, "", err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/workflows", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetFilter() != "" { + params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) + } + if req.GetOrderBy() != "" { + params.Add("orderBy", fmt.Sprintf("%v", req.GetOrderBy())) + } + if req.GetPageSize() != 0 { + params.Add("pageSize", fmt.Sprintf("%v", req.GetPageSize())) + } + if req.GetPageToken() != "" { + params.Add("pageToken", fmt.Sprintf("%v", req.GetPageToken())) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + headers := buildHeaders(ctx, c.xGoogMetadata, metadata.Pairs("Content-Type", "application/json")) + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, "", e + } + it.Response = resp + return resp.GetWorkflows(), resp.GetNextPageToken(), 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) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + + return it +} + +// GetWorkflow gets details of a single Workflow. +func (c *restClient) GetWorkflow(ctx context.Context, req *workflowspb.GetWorkflowRequest, opts ...gax.CallOption) (*workflowspb.Workflow, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + opts = append((*c.CallOptions).GetWorkflow[0:len((*c.CallOptions).GetWorkflow):len((*c.CallOptions).GetWorkflow)], opts...) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &workflowspb.Workflow{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("GET", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + return resp, nil +} + +// CreateWorkflow creates a new workflow. If a workflow with the specified name already +// exists in the specified project and location, the long running operation +// will return ALREADY_EXISTS error. +func (c *restClient) CreateWorkflow(ctx context.Context, req *workflowspb.CreateWorkflowRequest, opts ...gax.CallOption) (*CreateWorkflowOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetWorkflow() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v/workflows", req.GetParent()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + params.Add("workflowId", fmt.Sprintf("%v", req.GetWorkflowId())) + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &CreateWorkflowOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// DeleteWorkflow deletes a workflow with the specified name. +// This method also cancels and deletes all running executions of the +// workflow. +func (c *restClient) DeleteWorkflow(ctx context.Context, req *workflowspb.DeleteWorkflowRequest, opts ...gax.CallOption) (*DeleteWorkflowOperation, error) { + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("DELETE", baseUrl.String(), nil) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &DeleteWorkflowOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + +// UpdateWorkflow updates an existing workflow. +// Running this method has no impact on already running executions of the +// workflow. A new revision of the workflow may be created as a result of a +// successful update operation. In that case, such revision will be used +// in new workflow executions. +func (c *restClient) UpdateWorkflow(ctx context.Context, req *workflowspb.UpdateWorkflowRequest, opts ...gax.CallOption) (*UpdateWorkflowOperation, error) { + m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true} + body := req.GetWorkflow() + jsonReq, err := m.Marshal(body) + if err != nil { + return nil, err + } + + baseUrl, err := url.Parse(c.endpoint) + if err != nil { + return nil, err + } + baseUrl.Path += fmt.Sprintf("/v1/%v", req.GetWorkflow().GetName()) + + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + if req.GetUpdateMask() != nil { + updateMask, err := protojson.Marshal(req.GetUpdateMask()) + if err != nil { + return nil, err + } + params.Add("updateMask", string(updateMask)) + } + + baseUrl.RawQuery = params.Encode() + + // Build HTTP headers from client and context metadata. + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "workflow.name", url.QueryEscape(req.GetWorkflow().GetName()))) + + headers := buildHeaders(ctx, c.xGoogMetadata, md, metadata.Pairs("Content-Type", "application/json")) + unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true} + resp := &longrunningpb.Operation{} + e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + if settings.Path != "" { + baseUrl.Path = settings.Path + } + httpReq, err := http.NewRequest("PATCH", baseUrl.String(), bytes.NewReader(jsonReq)) + if err != nil { + return err + } + httpReq = httpReq.WithContext(ctx) + httpReq.Header = headers + + httpRsp, err := c.httpClient.Do(httpReq) + if err != nil { + return err + } + defer httpRsp.Body.Close() + + if err = googleapi.CheckResponse(httpRsp); err != nil { + return err + } + + buf, err := ioutil.ReadAll(httpRsp.Body) + if err != nil { + return err + } + + if err := unm.Unmarshal(buf, resp); err != nil { + return maybeUnknownEnum(err) + } + + return nil + }, opts...) + if e != nil { + return nil, e + } + + override := fmt.Sprintf("/v1/%s", resp.GetName()) + return &UpdateWorkflowOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + pollPath: override, + }, nil +} + // CreateWorkflowOperation manages a long-running operation from CreateWorkflow. type CreateWorkflowOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // CreateWorkflowOperation returns a new CreateWorkflowOperation from a given name. @@ -410,10 +881,21 @@ func (c *gRPCClient) CreateWorkflowOperation(name string) *CreateWorkflowOperati } } +// CreateWorkflowOperation returns a new CreateWorkflowOperation from a given name. +// The name must be that of a previously created CreateWorkflowOperation, possibly from a different process. +func (c *restClient) CreateWorkflowOperation(name string) *CreateWorkflowOperation { + override := fmt.Sprintf("/v1/%s", name) + return &CreateWorkflowOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *CreateWorkflowOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*workflowspb.Workflow, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp workflowspb.Workflow if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -431,6 +913,7 @@ func (op *CreateWorkflowOperation) Wait(ctx context.Context, opts ...gax.CallOpt // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *CreateWorkflowOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*workflowspb.Workflow, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp workflowspb.Workflow if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err @@ -468,7 +951,8 @@ func (op *CreateWorkflowOperation) Name() string { // DeleteWorkflowOperation manages a long-running operation from DeleteWorkflow. type DeleteWorkflowOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // DeleteWorkflowOperation returns a new DeleteWorkflowOperation from a given name. @@ -479,10 +963,21 @@ func (c *gRPCClient) DeleteWorkflowOperation(name string) *DeleteWorkflowOperati } } +// DeleteWorkflowOperation returns a new DeleteWorkflowOperation from a given name. +// The name must be that of a previously created DeleteWorkflowOperation, possibly from a different process. +func (c *restClient) DeleteWorkflowOperation(name string) *DeleteWorkflowOperation { + override := fmt.Sprintf("/v1/%s", name) + return &DeleteWorkflowOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *DeleteWorkflowOperation) Wait(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...) } @@ -496,6 +991,7 @@ func (op *DeleteWorkflowOperation) Wait(ctx context.Context, opts ...gax.CallOpt // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *DeleteWorkflowOperation) Poll(ctx context.Context, opts ...gax.CallOption) error { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) return op.lro.Poll(ctx, nil, opts...) } @@ -526,7 +1022,8 @@ func (op *DeleteWorkflowOperation) Name() string { // UpdateWorkflowOperation manages a long-running operation from UpdateWorkflow. type UpdateWorkflowOperation struct { - lro *longrunning.Operation + lro *longrunning.Operation + pollPath string } // UpdateWorkflowOperation returns a new UpdateWorkflowOperation from a given name. @@ -537,10 +1034,21 @@ func (c *gRPCClient) UpdateWorkflowOperation(name string) *UpdateWorkflowOperati } } +// UpdateWorkflowOperation returns a new UpdateWorkflowOperation from a given name. +// The name must be that of a previously created UpdateWorkflowOperation, possibly from a different process. +func (c *restClient) UpdateWorkflowOperation(name string) *UpdateWorkflowOperation { + override := fmt.Sprintf("/v1/%s", name) + return &UpdateWorkflowOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), + pollPath: override, + } +} + // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *UpdateWorkflowOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*workflowspb.Workflow, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp workflowspb.Workflow if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err @@ -558,6 +1066,7 @@ func (op *UpdateWorkflowOperation) Wait(ctx context.Context, opts ...gax.CallOpt // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *UpdateWorkflowOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*workflowspb.Workflow, error) { + opts = append([]gax.CallOption{gax.WithPath(op.pollPath)}, opts...) var resp workflowspb.Workflow if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err diff --git a/workflows/apiv1/workflows_client_example_test.go b/workflows/apiv1/workflows_client_example_test.go index a597de987856..beb4d639d298 100644 --- a/workflows/apiv1/workflows_client_example_test.go +++ b/workflows/apiv1/workflows_client_example_test.go @@ -41,6 +41,23 @@ func ExampleNewClient() { _ = c } +func ExampleNewRESTClient() { + ctx := context.Background() + // This snippet has been automatically generated and should be regarded as a code template only. + // It will require modifications to work: + // - It may require correct/in-range values for request initialization. + // - It may require specifying regional endpoints when creating the service client as shown in: + // https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options + c, err := workflows.NewRESTClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + // TODO: Use client. + _ = c +} + func ExampleClient_ListWorkflows() { ctx := context.Background() // This snippet has been automatically generated and should be regarded as a code template only. diff --git a/workflows/apiv1/workflowspb/workflows.pb.go b/workflows/apiv1/workflowspb/workflows.pb.go index 95a9e76eed29..0b7cb84043fb 100644 --- a/workflows/apiv1/workflowspb/workflows.pb.go +++ b/workflows/apiv1/workflowspb/workflows.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/workflows/v1/workflows.proto package workflowspb @@ -149,7 +149,6 @@ type Workflow struct { // revision. // // Types that are assignable to SourceCode: - // // *Workflow_SourceContents SourceCode isWorkflow_SourceCode `protobuf_oneof:"source_code"` } diff --git a/workflows/apiv1beta/workflows_client.go b/workflows/apiv1beta/workflows_client.go index 1f5016e5751a..10ab53ad5d87 100644 --- a/workflows/apiv1beta/workflows_client.go +++ b/workflows/apiv1beta/workflows_client.go @@ -521,6 +521,7 @@ func (c *restClient) ListWorkflows(ctx context.Context, req *workflowspb.ListWor baseUrl.Path += fmt.Sprintf("/v1beta/%v/workflows", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetFilter() != "" { params.Add("filter", fmt.Sprintf("%v", req.GetFilter())) } @@ -600,6 +601,11 @@ func (c *restClient) GetWorkflow(ctx context.Context, req *workflowspb.GetWorkfl } baseUrl.Path += fmt.Sprintf("/v1beta/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -663,6 +669,7 @@ func (c *restClient) CreateWorkflow(ctx context.Context, req *workflowspb.Create baseUrl.Path += fmt.Sprintf("/v1beta/%v/workflows", req.GetParent()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") params.Add("workflowId", fmt.Sprintf("%v", req.GetWorkflowId())) baseUrl.RawQuery = params.Encode() @@ -726,6 +733,11 @@ func (c *restClient) DeleteWorkflow(ctx context.Context, req *workflowspb.Delete } baseUrl.Path += fmt.Sprintf("/v1beta/%v", req.GetName()) + params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") + + baseUrl.RawQuery = params.Encode() + // Build HTTP headers from client and context metadata. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) @@ -795,6 +807,7 @@ func (c *restClient) UpdateWorkflow(ctx context.Context, req *workflowspb.Update baseUrl.Path += fmt.Sprintf("/v1beta/%v", req.GetWorkflow().GetName()) params := url.Values{} + params.Add("$alt", "json;enum-encoding=int") if req.GetUpdateMask() != nil { updateMask, err := protojson.Marshal(req.GetUpdateMask()) if err != nil { diff --git a/workflows/apiv1beta/workflowspb/workflows.pb.go b/workflows/apiv1beta/workflowspb/workflows.pb.go index 529d5759b8a0..27f062fc25e9 100644 --- a/workflows/apiv1beta/workflowspb/workflows.pb.go +++ b/workflows/apiv1beta/workflowspb/workflows.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/workflows/v1beta/workflows.proto package workflowspb @@ -147,7 +147,6 @@ type Workflow struct { // revision. // // Types that are assignable to SourceCode: - // // *Workflow_SourceContents SourceCode isWorkflow_SourceCode `protobuf_oneof:"source_code"` } diff --git a/workflows/executions/apiv1/executionspb/executions.pb.go b/workflows/executions/apiv1/executionspb/executions.pb.go index 8ee0d11279a6..8659d55225b4 100644 --- a/workflows/executions/apiv1/executionspb/executions.pb.go +++ b/workflows/executions/apiv1/executionspb/executions.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/workflows/executions/v1/executions.proto package executionspb diff --git a/workflows/executions/apiv1beta/executionspb/executions.pb.go b/workflows/executions/apiv1beta/executionspb/executions.pb.go index fd03571c5213..5af1c01dc8e8 100644 --- a/workflows/executions/apiv1beta/executionspb/executions.pb.go +++ b/workflows/executions/apiv1beta/executionspb/executions.pb.go @@ -14,8 +14,8 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.21.9 +// protoc-gen-go v1.27.1 +// protoc v3.15.8 // source: google/cloud/workflows/executions/v1beta/executions.proto package executionspb